diff --git a/ASSETS.md b/ASSETS.md index 2c7a07478b..029a978153 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -135,6 +135,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `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 | | | `assets/icons/dc-crystallize.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-cube.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-curvature-circle.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (an arch with the circle that touches it at its top, and that circle's center) | MIT OR Apache-2.0 | | | `assets/icons/dc-dash-align.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-dash-exact.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-dimension.svg` | Osama Amin | Original work, drawn for VectorCraft: a dimension line with arrowheads between two extension lines | MIT OR Apache-2.0 | | @@ -220,6 +221,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-polygon.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-pucker.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-puppet.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-quick-pen.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a line and a half circle with a dot at each point) | MIT OR Apache-2.0 | | | `assets/icons/dc-rearrange.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-rect-cut.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-rect-grid.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | diff --git a/Cargo.lock b/Cargo.lock index cb0c72cc0c..fa3b9166e7 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", @@ -6685,6 +6700,16 @@ dependencies = [ "vectorcraft-text", ] +[[package]] +name = "vectorcraft-cdr" +version = "0.24.1" +dependencies = [ + "crc32fast", + "flate2", + "proptest", + "vectorcraft-cdr", +] + [[package]] name = "vectorcraft-cli" version = "0.24.1" @@ -6799,6 +6824,7 @@ dependencies = [ "vectorcraft-apischema", "vectorcraft-brush", "vectorcraft-cad", + "vectorcraft-cdr", "vectorcraft-color", "vectorcraft-doc", "vectorcraft-eps", @@ -7109,6 +7135,7 @@ dependencies = [ name = "vectorcraft-text" version = "0.24.1" dependencies = [ + "craft-font-catalog", "craft-proof", "harfrust 0.13.3", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 6d2ab9e37b..e334f3e9e3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -77,6 +77,7 @@ vectorcraft-affinity = { path = "crates/affinity" } vectorcraft-scriptcheck = { path = "crates/scriptcheck" } vectorcraft-js = { path = "crates/js" } vectorcraft-apischema = { path = "crates/apischema" } +vectorcraft-cdr = { path = "crates/cdr" } # foundation kurbo = { version = "0.13", features = ["serde"] } diff --git a/NOTICE b/NOTICE index a6a1299cde..434cd3e524 100644 --- a/NOTICE +++ b/NOTICE @@ -35,6 +35,11 @@ based in part on the work of the Independent JPEG Group. WebAssembly plug-ins run in the wasmi interpreter (MIT OR Apache-2.0); its wasmparser dependency is under the Apache License 2.0 with the LLVM exception. +The .cdr reader (crates/cdr) reads the record layouts that the Kaitai Struct specification +coreldraw_cdr.ksy (https://github.com/kaitai-io/coreldraw_cdr.ksy, MIT License) and its fork by Zach +Wolfe (https://github.com/filestar/coreldraw_cdr.ksy, branch new_stuff, MIT License) describe. No part +of either specification is copied into the crate; the license text is in crates/cdr/LICENSE-kaitai.txt. + Builds made with craft-fonts (the CRAFT_FONTS_DIR build option; all official releases) embed the fonts listed in https://github.com/storytold/craft-fonts/blob/main/ATTRIBUTION.md (BIZ UDPGothic, Shippori Mincho, BIZ UDMincho, Noto Sans CJK SC and Noto Sans Arabic in the current manifest; diff --git a/ROADMAP.md b/ROADMAP.md index b3877be5c8..c4a6edc8fb 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -124,6 +124,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 2026-11-18: Built-in symbol library Media Controls: adds a seventh procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Play, Pause, Stop, Skip Next, Shuffle, Repeat) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged. + - 2026-11-14: Built-in symbol library Weather Icons: adds a sixth procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Sun, Moon, Cloud, Rain, Thunder, Snow) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged. - 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. @@ -140,8 +142,10 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 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-17: Curvature Circle tool (after the Circle tool in its group): a click on a path draws the circle that touches it there and bends as it bends, on the side it bends toward, or with Shift on the other side; a segment that is the usual cubic of a circular arc of 90° or less gives the arc's own radius, so a click on a circle draws that circle; the tool shows the circle, its center and its radius (with an asterisk for an arc's radius) until the click, or "Straight segment", "Cusp", "Corner" or "Circle too large" where it draws none (`shape.curvatureCircle`). One undo step per circle. A VectorCraft addition: headline numbers 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-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). 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,12 +154,16 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925). - 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917). - 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged. - 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-17: Tangent Circle Tool joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools, and the All Tools drawer): click a path segment, then another, to draw the circle tangent to the first where it was clicked that touches the second; Shift uses the tool's radius and a drag from the second segment sets the radius (Shift in round steps, Cmd/Ctrl slowly), the circle then touching the first segment anywhere along it. The circle shows with its center and radii before the click, one undo step (`tangentCircle`). 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/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/host_services.rs b/apps/vectorcraft/src/host_services.rs index 1ce124c1dd..3efdb9f93f 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -459,6 +459,8 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { open_file: Some(Box::new(open_file)), // Edit Original of a raster image with Use System Defaults for Edit Original off (#5236). open_in_photocraft: Some(Box::new(open_in_photocraft)), + check_application: Some(Box::new(|p| check_app(std::path::Path::new(p)))), + open_in_application: Some(Box::new(open_in_application)), 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. @@ -507,15 +509,32 @@ fn open_in_photocraft(path: &str) -> Result { explorer_safe(path)?; let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(std::path::PathBuf::from); let Some(app) = find_photocraft(home.as_deref(), std::env::var_os("PATH").as_deref()) else { return Ok(false) }; + launch_application(&app, path) +} + +/// A missing chosen editor falls back; invalid applications and failed launches remain errors. +fn open_in_application(app: &str, path: &str) -> Result { + explorer_safe(path)?; + let app = std::path::Path::new(app); + match std::fs::metadata(app) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false), + Err(e) => return Err(format!("cannot inspect {}: {e}", app.display())), + Ok(_) => {} + } + check_app(app)?; + launch_application(app, path) +} + +fn launch_application(app: &std::path::Path, path: &str) -> Result { #[cfg(target_os = "macos")] let mut c = { let mut c = std::process::Command::new("open"); - c.arg("-a").arg(&app).arg(path); + c.arg("-a").arg(app).arg(path); c }; #[cfg(not(target_os = "macos"))] let mut c = { - let mut c = std::process::Command::new(&app); + let mut c = std::process::Command::new(app); c.arg(path); c }; @@ -688,6 +707,17 @@ mod open_with_tests { tempfile::Builder::new().prefix(&format!("vc-open-with-{name}-")).tempdir().unwrap() } + #[test] + fn chosen_editor_only_falls_back_when_missing() { + let dir = scratch("chosen"); + let missing = dir.path().join("Missing.exe"); + assert!(!super::open_in_application(&missing.to_string_lossy(), "image with spaces.png").unwrap()); + let doc = dir.path().join("notes.txt"); + std::fs::write(&doc, "not an application").unwrap(); + assert!(super::open_in_application(&doc.to_string_lossy(), "image.png").is_err()); + assert!(super::open_in_application(&dir.path().to_string_lossy(), "image.png").is_err()); + } + /// #5236: only an application counts as PhotoCraft, never a document, a folder or a missing /// path. #[test] 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/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-curvature-circle.svg b/assets/icons/dc-curvature-circle.svg new file mode 100644 index 0000000000..4abaefe063 --- /dev/null +++ b/assets/icons/dc-curvature-circle.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-quick-pen.svg b/assets/icons/dc-quick-pen.svg new file mode 100644 index 0000000000..e87a486046 --- /dev/null +++ b/assets/icons/dc-quick-pen.svg @@ -0,0 +1 @@ + diff --git a/crates/brush/src/colorize.rs b/crates/brush/src/colorize.rs index 10dc66b587..f0caf2ac01 100644 --- a/crates/brush/src/colorize.rs +++ b/crates/brush/src/colorize.rs @@ -12,13 +12,17 @@ fn luminance(c: &Color) -> f32 { 0.2126 * r + 0.7152 * g + 0.0722 * b } -fn map_color(c: &Color, mode: Colorization, key: &Color) -> Color { - // Black ink alone is its own tint: its amount is the tint, not how light it displays (100% K - // displays lighter than black). - let light = match *c { +/// How light `c` is for colorization, 0 black to 1 white. Black ink alone is its own tint: its +/// amount is the tint, not how light it displays (100% K displays lighter than black). +fn lightness(c: &Color) -> f32 { + match *c { Color::Cmyk { c, m, y, k } if c == 0.0 && m == 0.0 && y == 0.0 => 1.0 - k, _ => luminance(c), - }; + } +} + +fn map_color(c: &Color, mode: Colorization, key: &Color) -> Color { + let light = lightness(c); // A process or gray stroke color's tints and shades stay in its model. let (white, black) = match key { Color::Cmyk { .. } => (Color::cmyk(0.0, 0.0, 0.0, 0.0), Color::cmyk(0.0, 0.0, 0.0, 1.0)), @@ -47,45 +51,61 @@ fn map_color(c: &Color, mode: Colorization, key: &Color) -> Color { } } -fn map_paint(p: &mut Paint, mode: Colorization, key: &Color) { +/// The swatch a stroke paint links to and its tint, for colorization: Tints of a linked color are +/// tints of its swatch (a spot color's tints print on its own plate). +type Link<'a> = Option<(&'a str, f32)>; + +fn map_paint(p: &mut Paint, mode: Colorization, key: &Color, link: Link<'_>) { if let Paint::Solid { color, .. } = p { - *p = Paint::solid(map_color(color, mode, key)); + *p = match (mode, link) { + (Colorization::Tints, Some((swatch, tint))) => { + let t = (1.0 - lightness(color)).clamp(0.0, 1.0); + Paint::Solid { color: key.tinted(t), swatch: Some(swatch.to_string()), tint: tint * t } + } + _ => Paint::solid(map_color(color, mode, key)), + }; } } /// Recolour `n` (recursively) for a stroke painted `stroke`, and strip brushes from its strokes so -/// brush output never recurses. Non-solid stroke paints leave the art's colours alone. Type is +/// brush output never recurses. Non-solid stroke paints leave the art's colours alone. Under Tints, +/// a stroke color linked to a swatch gives tints of that swatch, linked to it, as a spot color's +/// tints are (the art's darkest parts the stroke's own tint, white none of it). Type is /// recolored like paths: its characters' solid fills and strokes as well as its own. pub fn colorize(n: &mut Node, mode: Colorization, stroke: &Paint) { let key = match (mode, stroke.color()) { (Colorization::None, _) | (_, None) => None, (_, Some(c)) => Some(c), }; - fn walk(n: &mut Node, mode: Colorization, key: Option) { + let link = match stroke { + Paint::Solid { swatch: Some(s), tint, .. } => Some((s.as_str(), *tint)), + _ => None, + }; + fn walk(n: &mut Node, mode: Colorization, key: Option, link: Link<'_>) { for it in &mut n.appearance.items { match it { AppearanceItem::Fill(f) => { if let Some(k) = &key { - map_paint(&mut f.paint, mode, k); + map_paint(&mut f.paint, mode, k, link); } } AppearanceItem::Stroke(s) => { s.brush = None; if let Some(k) = &key { - map_paint(&mut s.paint, mode, k); + map_paint(&mut s.paint, mode, k, link); } } } } if let (Some(k), NodeKind::Text(t)) = (&key, &mut n.kind) { for r in &mut t.runs { - map_paint(&mut r.style.fill, mode, k); - map_paint(&mut r.style.stroke, mode, k); + map_paint(&mut r.style.fill, mode, k, link); + map_paint(&mut r.style.stroke, mode, k, link); } } if let Some(ch) = n.children_mut() { for c in ch.iter_mut() { - walk(Arc::make_mut(c), mode, key); + walk(Arc::make_mut(c), mode, key, link); } } // A mask's art is drawn too: a brush on its strokes would run this brush again. Its colours @@ -94,7 +114,7 @@ pub fn colorize(n: &mut Node, mode: Colorization, stroke: &Paint) { strip_brushes(Arc::make_mut(&mut m.art)); } } - walk(n, mode, key); + walk(n, mode, key, link); } /// Mixed into a stroke's seed for its hue jitter, so the amounts come from a sequence of their own diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index c5354d75cd..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 }) } @@ -307,9 +327,10 @@ pub struct Scatter { /// 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]>, } @@ -384,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, @@ -732,7 +754,7 @@ impl Brush { } 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; } diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index f4f2d1ae20..2b1449eddf 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -921,6 +921,47 @@ fn tints_colorization_uses_stroke_colour() { assert_eq!(white.appearance.fill_paint().color().unwrap().to_rgb(), [1.0, 1.0, 1.0]); } +/// Under Tints, a stroke color linked to a swatch gives tints of that swatch, linked to it: black +/// art the stroke's own tint of it, 60% black ink 60% of that, white none; the colors shown are the +/// same as for the unlinked color, a process or an RGB swatch. Tints and Shades stay unlinked. +#[test] +fn tints_of_a_swatch_stay_linked_to_it() { + let spot = Color::cmyk(0.0, 0.5, 1.0, 0.0); + let stroke = Paint::Solid { color: spot.tinted(0.8), swatch: Some("Brand orange".into()), tint: 0.8 }; + let mapped = |art: Color| { + let mut n = rect_art(1.0, 1.0); + n.appearance.set_fill(Paint::solid(art)); + colorize(&mut n, Colorization::Tints, &stroke); + let mut plain = rect_art(1.0, 1.0); + plain.appearance.set_fill(Paint::solid(art)); + colorize(&mut plain, Colorization::Tints, &Paint::solid(spot.tinted(0.8))); + (n.appearance.fill_paint(), plain.appearance.fill_paint().color().unwrap()) + }; + for (art, want) in [(Color::cmyk(0.0, 0.0, 0.0, 1.0), 0.8), (Color::cmyk(0.0, 0.0, 0.0, 0.6), 0.48), (Color::cmyk(0.0, 0.0, 0.0, 0.0), 0.0)] { + let (paint, shown) = mapped(art); + let Paint::Solid { color, swatch: Some(s), tint } = paint else { panic!("linked: {paint:?}") }; + assert_eq!(s, "Brand orange"); + assert!((tint - want).abs() < 1e-5, "{art:?}: {tint}"); + let close = color.to_cmyk().iter().zip(shown.to_cmyk()).all(|(a, b)| (a - b).abs() < 1e-5); + assert!(close, "{color:?} {shown:?}"); + } + // An RGB swatch: its tints mix toward white, as the unlinked color's do. + let rgb = Color::rgb(1.0, 0.4, 0.0); + let mut n = rect_art(1.0, 1.0); + n.appearance.set_fill(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 0.5))); + colorize(&mut n, Colorization::Tints, &Paint::Solid { color: rgb, swatch: Some("Brand red".into()), tint: 1.0 }); + let Paint::Solid { color, swatch: Some(s), tint } = n.appearance.fill_paint() else { panic!("linked") }; + assert_eq!(s, "Brand red"); + assert!((tint - 0.5).abs() < 1e-5, "{tint}"); + let [r, g, b] = color.to_rgb(); + assert!((r - 1.0).abs() < 1e-5 && (g - 0.7).abs() < 1e-5 && (b - 0.5).abs() < 1e-5, "{r} {g} {b}"); + // Tints and Shades darken past the swatch, which a tint can't: its pieces stay unlinked. + let mut n = rect_art(1.0, 1.0); + n.appearance.set_fill(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0))); + colorize(&mut n, Colorization::TintsAndShades, &stroke); + assert!(matches!(n.appearance.fill_paint(), Paint::Solid { swatch: None, .. }), "{:?}", n.appearance.fill_paint()); +} + /// Black ink alone is a tint by its amount: a process black stroke leaves it as it is, and another /// process stroke color takes that share of its inks. Tints of a process color stay process. #[test] @@ -1545,6 +1586,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 { @@ -1611,7 +1710,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(); @@ -1658,7 +1757,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:?}"); } @@ -1726,8 +1825,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. 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/cdr/Cargo.toml b/crates/cdr/Cargo.toml new file mode 100644 index 0000000000..ca2066c879 --- /dev/null +++ b/crates/cdr/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "vectorcraft-cdr" +description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[features] +# Synthetic-file builders for tests and fuzz seeds; not a .cdr writer. +synth = [] + +[dependencies] +crc32fast = { workspace = true } +flate2 = { workspace = true } + +[dev-dependencies] +proptest = { workspace = true } +vectorcraft-cdr = { path = ".", features = ["synth"] } diff --git a/crates/cdr/LICENSE-kaitai.txt b/crates/cdr/LICENSE-kaitai.txt new file mode 100644 index 0000000000..296cf04d0e --- /dev/null +++ b/crates/cdr/LICENSE-kaitai.txt @@ -0,0 +1,33 @@ +The record layouts this crate reads are described in the Kaitai Struct +specification `coreldraw_cdr.ksy` +(https://github.com/kaitai-io/coreldraw_cdr.ksy, commit +9d8e2704b946961f5114115f1a488750a3c86ed0), which is published under the +license below. No part of that specification is copied into this crate; +`PROVENANCE.md` cites it by line. + +Some layouts are also taken from the fork of that specification by Zach Wolfe +(https://github.com/filestar/coreldraw_cdr.ksy, branch new_stuff, commit +2189b68f07e0cafe9afec3dcf699ebc0342144c7), which is published under the same +license and copyright notice. + +MIT License + +Copyright (c) 2020 Kaitai team + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md new file mode 100644 index 0000000000..b710c7d4b2 --- /dev/null +++ b/crates/cdr/PROVENANCE.md @@ -0,0 +1,127 @@ +# Where each layout comes from + +The reader relies on the record layouts below. Code cites a row by its id (`R1` ...), and +`tests/it/provenance.rs` fails when a cited id has no row here. + +Sources: + +- **K**: the Kaitai Struct specification `coreldraw_cdr.ksy` (MIT, notice in `LICENSE-kaitai.txt`), + https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/coreldraw_cdr.ksy +- **KF**: the fork of K by Zach Wolfe, `filestar/coreldraw_cdr.ksy`, branch `new_stuff`, under the same + MIT license and notice as K (`LICENSE-kaitai.txt`), + https://github.com/filestar/coreldraw_cdr.ksy/blob/2189b68f07e0cafe9afec3dcf699ebc0342144c7/coreldraw_cdr.ksy +- **KR**: the README and the `bin/cdr-unpk` script of the Kaitai Struct specification (MIT), at + the same commit as K, + https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/README.md + and https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/bin/cdr-unpk +- **Z**: the PKWARE ZIP specification, APPNOTE.TXT version 6.3.10, + https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT, and RFC 1951 (DEFLATE), + https://www.rfc-editor.org/rfc/rfc1951 +- **F**: the magic database of the `file` utility (BSD-2-Clause), + https://github.com/file/file/blob/b778217dbd35/magic/Magdir/images and + https://github.com/file/file/blob/b778217dbd35/magic/Magdir/riff +- **PR**: the PRONOM registry's signatures for versions 1.0, 2.0 and 4.0, + https://pronom.nationalarchives.gov.uk/fmt/467.xml, + https://pronom.nationalarchives.gov.uk/fmt/466.xml and + https://pronom.nationalarchives.gov.uk/fmt/465.xml +- **S**: own inspection of the bytes of public sample files, checked against the picture each file + carries of its drawing where it has one (versions 2 and 4 to 25; files of versions 1 and 3 carry + none). The files come from: + - **TP**: https://telparia.com/fileFormatSamples/image/cdr/, by file name + - **LT**: https://git.libreoffice.org/libcdr-test at commit + `dafe4fe53d685d89df20a5c0bb18f318ccefb4a8`, `testset//` + - **UC**: https://svn.code.sf.net/p/uniconvertor/code/formats/CDR/testing%20base/ at revision + 434, by file name + - **TDF**: attachments to The Document Foundation's bug tracker, + https://bugs.documentfoundation.org/attachment.cgi?id= + - **NR**: Natural Resources Canada's tactile maps, + https://ftp.maps.canada.ca/pub/nrcan_rncan/raster/tactile/approach-approch/cdr/banff_ap_en.cdr and + https://ftp.maps.canada.ca/pub/nrcan_rncan/raster/tactile/atlas-atlas/cdr/ab_en_br.cdr + - **DM**: the clip art of https://discmaster.textfiles.com/browse/31541, by file name + - **CX**: the `.cmx` files of https://telparia.com/fileFormatSamples/image/cmx/, by file name. The + nine with 32-bit coordinates are `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, + `gold_bar.cmx`, `goldblue.cmx`, `PC.CMX`, `squares.cmx` and `thatch.cmx`; they carry no picture + of their drawing. +- **CN**: the `.cmx` notes of an MIT OR Apache-2.0 drawing program, which mark each layout + "confirmed" when the program's authors found it in sample files, + https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/docs/cmx-format.md. + The same program's `.cmx` reader at that commit, + https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/crates/cdr/src/cmx.rs, + was read for the order of fields that the notes do not spell out (the table entries, the rendering + attributes and the curve body); no code was copied from it + +Status: `public-spec` (K, KF, KR, Z, F or PR), `sample` (S), `public-notes` (a layout CN marks +confirmed that no CX file shows), `unconfirmed` (a point no source states and no sample file shows; +listed so it can be checked against a file, with what the reader does when it is wrong). + +Public specifications cover only parts of versions 1 to 4: the rows that cite K, F or PR, such as +the version 3 fill (R34) and page settings (R38). The other rows of those versions rest on the +sample files they name. +The test inputs are the synthetic files that `src/synth.rs` builds from the rows below; no sample +file is committed. + +| Id | What the code relies on | Source | Status | +|---|---|---|---| +| R1 | `RIFF`, the body length, then the form type `CDR` or `cdr` and a version character: `1` to `9`, `A` (10) to `H` (17), `J` (18) on, `I` unused; `cdr8` is 8.01 from the form type alone, whatever its `vrsn` chunk names, `CDR ` is 3, `CDRX` is another format. Files of versions 23 to 25 carry `O` (23), `P` (24), `Q` (24.3, with a `vrsn` of 2430) and `R` (25), which count differently from the version 24 update on, so their `vrsn` chunk decides (R2) | K L68-L133; S: LT `testset/23` to `testset/25`, such as `circle_redfill_nooutline_cdr25.cdr` | public-spec (letters from version 23: sample; letters of versions 26 and 27: unconfirmed, and the `vrsn` chunk decides when the file has one) | +| R2 | `vrsn`: the version as a u16, in hundreds | K L276-L278 | public-spec | +| R3 | `LIST cmpr`: two (compressed, uncompressed) u32 pairs, then two blocks of `CPng`, `01 00 04 00` and a zlib stream; the first inflates to the chunk stream, the second to a pool of u32 sizes that each chunk's size field indexes | K L193-L220, L2626-L2682 | public-spec | +| R4 | A chunk is an id, a u32 size and the body, padded to an even length; a `LIST` body starts with its form type; from version 7 a `LIST stlt` holds the style tables, not chunks | K L68-L78, L135-L155, L307-L334 | public-spec | +| R5 | Coordinates: i16 in 1/1000 inch before version 6, else i32 in 1/254000 inch; header fields, counts and offsets are u16 before version 6, else u32 | K L58-L66, L2688-L2700 | public-spec | +| R6 | `loda` and `lobj`: length, argument count, offsets table, types table, object type; count + 1 offsets bound the arguments; the types table runs in reverse; object types (1 rectangle, 2 ellipse, 3 curve, 0x14 polygon) and argument types (10 outline, 20 fill, 30 coordinates, 1000 name, 11000 polygon, 19130 page size) | K L335-L450, L846-L893 | public-spec | +| R7 | Angles: i16 tenths of a degree before version 6, else i32 millionths of a degree | K L2835-L2855 | public-spec | +| R8 | `trfd`: length, count, offsets table; each entry has 8 bytes first from version 13, a u16 type, and type 8 is a matrix after 6 bytes (from version 6) of six f64 `a c tx b d ty`, `tx` and `ty` in coordinate units; the matrices of one record apply in file order | K L895-L953, L2808-L2834 | public-spec | +| R9 | Name argument (1000): Windows-1252 up to a NUL before version 12, UTF-16LE from it | K L601-L630 | public-spec | +| R10 | `mcfg`: 12 bytes (13 on), 4 (9 to 12), 28 (6) or none, then the page width and height as coordinates | K L1670-L1765 | public-spec | +| R11 | `fild` (`fill` before 7): id; from 13 a record tagged 1300 with its length, which records tagged 2400 or more may precede; the fill type u16 (0 none, 1 uniform, others not read); uniform: 2 bytes then a color before 13, from 13 a record tagged 1300 holding a property list (u8 type, u32 length, body; 0 ends it; 1 a color, 8 a palette id and a UTF-16 name, 3 a UTF-16 name) | K L1025-L1302; S: LT `testset/15` to `testset/25` `circle_redfill_nooutline_cdr.cdr`, whose fill records hold a record tagged 2400 before the one tagged 1300 | public-spec (2400 records: sample) | +| R12 | `outl`: id; from 13 records (u32 id, u32 length, body) up to id 1, whose body follows; a record of id 2 holds a property list laid out as R11's, and the reader takes the outline's color from it when it names a library color; line type, caps and join u16; 2 bytes (6 to 12); width; stretch u16; 2 bytes (6 on); nib angle; 52 bytes (6 to 12) or 46 (13 on); the color; 16 bytes (10 before 6); the dash count u16 and the dashes, in multiples of the width; the arrowhead ids 22 bytes after the first dash in versions 6 to 12, 20 bytes from 13. Caps 0 butt, 1 round, 2 square; joins 0 miter, 1 round, 2 bevel | K L954-L1024; KF L1225-L1249 (the id 2 record); S: caps and joins in UC `outl_line_caps_cdr7.cdr` and `outl_corner_cdr7.cdr`; arrowhead ids, matched against the drawing's `arrw` records, in TP `web_cd.cdr` (6), UC `rogan_logo_cdr7.cdr`, `rogan_logo_cdr8.cdr` and `rogan_logo_cdr11.cdr`, NR `ab_en_br.cdr` (9) and `banff_ap_en.cdr` (10), TDF 76820 (12) and 140638 (13) | public-spec (caps, joins and arrowhead places: sample; arrowheads before version 6: no sample names one, and the reader does not look for them; the id 2 record: no sample names a library color in it, and a wrong guess changes only the outline's color) | +| R13 | Bit 0 of the outline's line type: no outline | S: LT `square_blackfill_nooutline_cdr.cdr` and the other `nooutline` files of `testset/15` to `testset/25`, whose outline records all have line type 1 and whose pictures show no outline | sample | +| R14 | A color record from version 5: model u16, palette u16, 4 bytes, four value bytes. Models: 2 CMYK in percent, 3 and 17 CMYK 0 to 255, 4 CMY 0 to 255, 5 blue, green, red, 9 gray 0 to 255, 20 registration, 21 blue, green, red and a tint in percent already applied; 1, 14 and 25 a library color's number (u16) and tint in percent (u16) | K L2856-L2965; S: model 25 in LT `testset/12/square_pantoneblackfill_nooutline.cdr` (number 14, tint 100), model 1 in UC `rogan_logo_cdr11.cdr` (number 4, tint 50) | public-spec (library values of models 1 and 25: sample; model 14: unconfirmed, and its color opens as a spot color without a look) | +| R15 | Rectangle coordinates: width, height and one radius, three more radii from version 9, running counterclockwise from the corner at (width, 0) | K L674-L700 | public-spec | +| R16 | Point list: u32 count (before version 6 as R39 gives it), the points, then one type byte each, the count held to what fits; type bits 7 and 6 move, line, curve end, control point; bit 3 closes the subpath | K L782-L787, L840-L845, L2701-L2807 | public-spec | +| R17 | Ellipse coordinates: width, height, start and end angles, pie flag (u16 before 6, else u32); the radii are half the width and height; the angles turn from the ellipse's own axes, which a negative width or height points the other way | K L754-L781; S: the pies of negative height in the ellipse-sector drawings of versions 12 and 13 in UC | public-spec (axis direction of a negative size: sample) | +| R18 | Polygon argument (11000): 4 bytes before 13, the side count u32, the next point u32 (the u32 after it when it is 0 or 1, else 4 bytes), 4 more from 13, rx and ry f64, the centre; the base curve is one side on a circle of 1000 mm from the top vertex to the vertex it runs to clockwise, copied once for each side | K L631-L655; S: the polygons and stars of UC `shapes_cdr10.cdr` | public-spec (base curve: sample) | +| R19 | `flgs`: byte 3 the record type, byte 2 marks the master page. On a layer, group or object, bit 0x01 of byte 1 hides it and bit 0x10 of byte 0 locks it. A layer's own `loda` names what it is by its object type: 11 a grid, 12 guides, 17 the desktop, any other a drawing layer (version 3 one less, R32). Only a layer without a `loda` is taken by the low four bits of its byte 0: 0x0a guides, or a grid when bit 0x10 is also set; in versions 7 to 13 0x02 the same way; 0x08 the desktop when byte 2 is set and a drawing layer when it is clear; any other a drawing layer, except [0, 1, 1] in versions 7 to 13, the desktop | K L1602-L1639 (record types); KF L1831-L1866 (the hidden and lock bits); S: every grid layer of versions 14 to 25 in the sample files (631) carries byte 1 = 1, and 206 of the 927 of versions 7 to 13 do; desktop layers carry byte 1 = 0 except TDF 114901's [0, 1, 1]; the drawing layers with byte 1 = 1 (TDF 114901, NR `banff_ap_en.cdr` and `symbology_en.cdr`) also carry bit 0x08; of the group and object lists in the sample files, only one object of TDF 60491 (version 14) sets either bit, the lock bit; in every sample file of versions 3 to 25 the layer's object type agrees with its name; byte 0 does not: TDF 114901 (version 8) flags its master page's guides [2, 1, 1], desktop [0, 1, 1], grid [0x12, 0, 1] and drawing layer [8, 1, 0], and NR `ab_en_br.cdr` (version 9) flags drawing layers 0x10 and its guides 0x1a; over the sample files of versions 3 to 25, drawing layers carry 0, 0x10, 0x40, or 0x08, 0x18 or 0x58 with byte 2 clear, desktop layers 0x08, 0x18 or 0x48 with byte 2 set, guides 0x0a, 0x4a, 0x02 or (in `ab_en_br.cdr`) 0x1a, and grids 0x1a, 0x5a or 0x12 | public-spec (layer types: sample; byte 0 of a layer without a `loda`: unconfirmed, as no sample has such a layer, and a wrong guess drops or shows that layer's objects; bit 0x10 is also the lock bit, so a locked guides layer without a `loda` reads as a grid) | +| R20 | Fill and outline arguments (20, 10): a u32 record id | K L452-L460, L548-L556 | public-spec | +| R21 | Page size argument (19130): width and height | K L666-L672 | public-spec | +| R22 | `LIST page` holds `LIST layr` lists, directly or in a list it holds (a `LIST gobj` in the samples); a layer holds `LIST obj ` and `LIST grp `; a page, layer or object keeps its own `loda` (and an object its `trfd`, in a `trfl` list) among its chunks or in a `LIST lgob` | K L1602-L1639 (record types); S: the chunk trees of every sample file of versions 3 to 25 | sample | +| R23 | Guideline (object type 0x16), argument 16000: 12 bytes, the angle in millionths of a degree, then points from the page centre; version 7 keeps them in a `guid` chunk: a u32 count, the count again, 40-byte records laid out the same way | S: argument 16000 in NR `ab_en_br.cdr` (9) and TDF 194220 (13); the `guid` chunk of TDF 123971 (7). Pictures do not show guidelines | sample | +| R24 | ZIP: the end of central directory record (signature `PK\5\6`, 22 bytes and a comment of up to 65,535 bytes) gives the member count and where the central directory lies; each central directory entry (46 bytes, then name, extra field and comment) gives the flags, method, CRC-32, sizes and its local header; a local header is 30 bytes, then its name and extra field, then the member's bytes. Flag bit 0 marks an encrypted member; method 0 is stored and 8 deflated; 0xFFFF and 0xFFFFFFFF mark ZIP64 fields, and a ZIP64 locator (`PK\6\7`, 20 bytes) precedes the end record of a ZIP64 archive; disk numbers other than 0 mark an archive split across files | Z 4.3.7, 4.3.12, 4.3.15, 4.3.16, 4.4.1.4, 4.4.4, 4.4.5, 4.4.7, 4.4.8, 4.4.13 | public-spec | +| R25 | Versions 14 and 15 save a ZIP package whose member `content/riffData.cdr` is the RIFF file | KR README L33, `cdr-unpk` L30 | public-spec | +| R26 | From version 16 the package's member `content/root.dat` is the RIFF file; `content/dataFileList.dat` names the data streams, one per line, members of `content/data/`; a redirect's stream number counts lines from 0 | KR README L34, L40, `cdr-unpk` L34-L66; K L173-L180 | public-spec | +| R27 | In a package of version 16 on, a chunk outside a compressed list whose size is 16 (in `root.dat` or in a redirected list's body) is a redirect record: stream u32, length u32, offset u32 and a reserved u32; its body is `length` bytes at `offset` of the stream; stream `0xFFFFFFFF` holds the body (at most 8 bytes) in the record after the length; a redirected list's body starts with its form type | K L144-L193 | public-spec | +| R28 | Templates have the form type `CDT` and a letter of their own; the `vrsn` chunk names the version. The reader takes any letter `A` to `Z` there | none: no sample template | unconfirmed (a template is read as a drawing of the version its `vrsn` chunk names, and one without that chunk is refused) | +| R29 | Rectangle coordinates from version 15: width and height as f64 coordinate units, scale x and y (f64, repeating the transform's scale), the scale-with flag (u8) and 7 bytes, then the four radii as f64, 16 bytes apart (a corner type byte and 15 bytes after the first), in the order of R15. With the flag clear each radius is a share of half the shorter side; with it set the radii are multiplied by 254000 coordinate units, which makes them inches | K L674-L752; S: LT `square_blackfill_nooutline_roundedcorners_cdr.cdr` of `testset/15` to `testset/25` (flag clear, a share of 0.25) | public-spec (radius share with the flag clear: sample; that the scale is not applied: unconfirmed, as every sample has a scale of 1, and a wrong guess changes only the corners' size) | +| R30 | Object type 0x25 (version 10 on) is a path: 4 bytes, two u16 counts that add up to the point count, 16 bytes, then the points and their type bytes as in R16 | K L788-L799, L892; S: TDF 78250 (version 15) and UC `shapes_cdr10.cdr`, `shapes_cdr11.cdr`, `shapes_cdr12.cdr` and `shapes_x3.cdr` (versions 10 to 13), whose type bytes start where the counts put them; no sample before version 10 holds the type | public-spec (from version 10: sample) | +| R31 | Version 3 is a RIFF file with the form type `CDR ` (a space) and a `vrsn` of 300; version 4 has the form type `CDR4` and a `vrsn` chunk. Both use the 16-bit fields of R5 and R7. Their pages, layers, groups and objects are read by the rules of R19 and R22 | K L117-L134; PR fmt/465; F `riff` L786; S: TP `FOX.CDR` and `DALI.CDR` (3), DM `lion1.cdr` and `tiger.cdr` (4) | public-spec (pages and layers as R19 and R22: sample) | +| R32 | Version 3 counts its object types from 0: rectangle 0, ellipse 1, curve 2, text 3, bitmap 4; later versions use these plus one | S: the rectangles, curves and text of TP `ARMYSTF1.CDR`, `DALI.CDR` and `FOX.CDR`, which come out whole | sample (ellipse 1 and bitmap 4: unconfirmed, as no sample holds them; a bitmap is left out with a warning) | +| R33 | Version 3 keeps an object's transforms in argument 100 of its `lobj`: a u16, the entry count (u16), then 10-byte entries of a type (u16) and, at byte 6, where the entry's data starts, counted from the start of the argument. Type 0x8c is a matrix as R37, and the matrices apply in file order. Type 0x14 is an envelope, which this reader does not apply: the shape keeps its outline, placed by the matrices alone, and the drawing's warnings name the envelopes. A group's own `lobj` holds an argument 100 that places all of the group's objects after their own transforms | K L851; S: the matrices of every version 3 file in TP, whose drawings come out whole | sample (envelope type 0x14: unconfirmed, as no sample holds one; it is not applied, with a warning) | +| R34 | Version 3 fill, argument 20: a type byte (0 none, 1 uniform, 2 and 4 fountain, 6 texture, 7 and 10 pattern); a uniform fill's color follows as R36 | K L452-L547 | public-spec | +| R35 | Version 3 outline, argument 10: a flags byte with bit 0 set when the object is outlined, the width (coordinate), the stretch (u16), the nib angle, the color as R36, 7 bytes, the dash count (u8) and 10 bytes that hold the dashes as one byte each, the join (u16 at byte 30) and the caps (u16 at byte 32) numbered as R12, then the two arrowhead ids (u32). Dashes are read in multiples of the width as R12 | K L548-L592; S: the outlines of the version 3 files in TP | public-spec (flag bit: sample; dash unit, and the join, where bytes 32 and 33 of some samples hold 2 and 2: unconfirmed, and a wrong guess changes only how corners, ends and dashes are drawn) | +| R36 | A color before version 5: in versions 1 to 3 a model byte and four value bytes, in version 4 a model u16, four u16 values and 2 bytes. Model 1 is cyan, magenta, yellow and black in percent. Model 0 is an ink number (u16) and a tint in percent (u16): ink 0 is black at the tint, ink 1 is white, and other numbers are inks of a numbered library that the file does not store. Other models are read as R14 | K L2882-L2908; S: model 1 in TP `ARMYSTF1.CDR` (3) and DM `lion1.cdr` (4), model 0 in TP `ARROW5.CDR` (3) and `WI.CDR` (1) | sample (ink 1, and models other than 0 and 1: unconfirmed; an ink of another number opens as a spot color without a look) | +| R37 | A matrix of versions 3 and 4: six i32 `a c tx b d ty`, the four factors in 16.16 fixed point and `tx` and `ty` in coordinate units. A version 4 `trfd` entry of type 8 holds one where R8 has six f64 | S: TP `FOX.CDR` and `DALI.CDR` (3), DM `lion1.cdr` and `tiger.cdr` (4) | sample | +| R38 | `mcfg` of version 3: 2 bytes, then the page's two corners as four coordinates; the page size is the distance between them | K L1676-L1678, L1745-L1756 | public-spec | +| R39 | A point list before version 6 starts with a u16 count and another u16 (1 in some curves of versions 1, 2 and 4, 0 in the others), where K reads the two as one u32 | S: TP `DALI.CDR` (3), DM `headup.cdr` and `lion1.cdr` (4), TP `WI.CDR` (1), `FLAG.CDR` and `MENU.CDR` (2) | sample | +| R40 | Versions 1 and 2 are not RIFF files. A file starts with `WL`, a marker byte, a zero byte and five u32: the start of the settings, the start and the end of the object records, the start of the trailer and that value minus two. Version 1 has the marker `e` and its settings start at byte 28. Version 2 has the marker `m` or `l`, and its settings start after a 1-bit picture of the drawing, whose header starts where the u32 at byte 28 says. The reader takes these three markers | F `images` L4159-L4172; PR fmt/467, fmt/466; S: TP `WI.CDR` (`e`), `FLAG.CDR` (`m`), `MENU.CDR` and `DRINKS.CDR` (`l`) | public-spec (markers `e` and `m`: F and PR; the offsets and the marker `l`: sample) | +| R41 | The page's box in a file of version 1 or 2: four i16 two bytes after the start of the settings (left, top, right, bottom) in 1/1000 inch around the page's centre, y pointing up | S: TP `WI.CDR`, `FLAG.CDR` and `MENU.CDR` | sample | +| R42 | The records of a file of version 1 or 2 run from the front of the stacking order to the back. Every record starts with the u32 24. A group or layer record is 28 bytes, and bit 0x40 of its flags byte at 26 is clear. A drawn object has that bit set (0x40 in files with the markers `e` and `m`, 0xc0 with `l`) and a u16 body size at byte 28; it is the body size plus 32 bytes long. A drawn object of another type than those of R43 gives its length otherwise, and the records after it are not read | S: TP `WI.CDR`, `FLAG.CDR`, `MENU.CDR` and `DRINKS.CDR`; the order checked against the picture of `MENU.CDR` | sample | +| R43 | A drawn object of version 1 or 2: a point (two i16) at byte 32; six i32 in 16.16 fixed point at 36, `a b tx c d ty`, with x' = a x + b y + tx + the point's x and y' = c x + d y + ty + the point's y; the object type at 60 (0 rectangle, 1 ellipse, 2 curve, 3 text); a byte at 67 that is not 0 when the object is outlined, the outline's width (u16) at 68 and its color at 74; the fill type (0 none, 1 uniform) and its color after it, at 94 and 95 with the marker `e` and at 105 and 106 with `l` and `m`; the shape from byte 114 with `e` and 136 with `l` and `m`. Colors are as R36 | S: TP `WI.CDR` (`e`), `FLAG.CDR` (`m`) and `MENU.CDR` (`l`), checked against the pictures of `FLAG.CDR` and `MENU.CDR` | sample | +| R44 | Shapes of version 1 or 2: a rectangle's width and height (i16), then a corner radius; an ellipse's width and height, then two angles; a curve's point list as R39 and R16 | S: rectangles in TP `FLAG.CDR`, ellipses and curves in TP `WI.CDR`, curves in TP `MENU.CDR` | sample (the radius of files with the marker `e`, which no sample shows, and how the angles make an arc: unconfirmed; a radius is kept only when it is at most half the shorter side, and an ellipse whose angles differ is left out with a warning) | +| R45 | `LIST stlt` from version 7: a u32 style count, and when it is not 0: the fill table (a u32 count, entries of a table id, 4 bytes and a `fild` id, 12 bytes each, 60 from version 13), the outline table (12-byte entries laid out the same way, naming `outl` ids), the text tables (fonts of 44 bytes, 60 from version 10; alignments of 12; spacings of 52; tables of 152 and 784; bullets whose length a u32 inside them sets; indents of 28; hyphenation of 32, 36 from 13; drop caps of 28; from 8.01 a table of 12), then the styles: kind (u32), id, parent id, 8 bytes, name length and name (bytes before 12, UTF-16 units from it), the fill and outline table ids, then 16 bytes (20 from 8.01) for kinds above 1 and 20 more for kinds above 2. An object names its style in argument 200 (u16 before version 6, u32 from it). An object without argument 20 or 10 takes the fill or outline of its style; a style whose table id is 0 takes its parent's | K L593-L600, L852, L1926-L2198; S: UC `outl_width_cdr7.cdr`, one of whose lines carries argument 200 and neither 10 nor 20 and names the style whose outline is black and 0.003 inch wide and whose fill is none, as the file's picture shows; the table parses exactly to the end of the list in each of the 498 sample files of versions 7 to 15 that has one, and every object with argument 200 in them names a style whose table ids are in the tables; argument 200 is 2 bytes on all 844 objects of versions 4 and 5 in the sample files that carry it, and 4 bytes on all 18 of version 6 | public-spec (what the table ids name, and that an object takes its style's fill and outline: sample; a style taking its parent's entry: unconfirmed, as only text styles in the samples leave theirs to the parent, and a wrong guess draws a shape without that fill or outline) | +| R46 | A clipping container carries argument 8005; its first u32 is the id that the `spnd` chunk (a u32, a u16 before version 6) of one `LIST grp ` in the document's `LIST clpt` holds. That group's objects are the ones the container clips; they keep their own transforms, in page space like the container's | K L252, L860-L862, L1895-L1901 (the argument and the chunk); S: LT `powerclipsquare_blackfill_whiterectangleinside` of `testset/12` to `testset/25` and eight UC files of versions 7 to 13, in each of which the id in argument 8005 matches one group's `spnd`; in the UC file of version 7 the group's box, -1.96 to 1.97 inches across, overlaps the container's, -1.81 to 1.84 inches, and the file's picture shows the group cut to the container | public-spec (what the id names, and the space of the group's objects: sample) | +| R47 | Argument 8000 marks an object seen through: a lens or a transparency. From version 13 it holds records of a u32 version, a u32 length and a body; a body of version 1300 that is 117 bytes long holds an f64 at byte 61 and a merge mode byte at byte 77, which the reader applies as a uniform transparency. VectorCraft reads the f64 as the transparency in percent (0 opaque, 100 clear) and maps the merge modes 0 normal, 9 multiply, 11 lighten, 12 darken, 14 color, 15 hue, 16 saturation, 17 luminosity, 24 difference, 28 screen, 29 overlay, 30 soft light, 31 hard light, 33 color dodge, 34 color burn and 36 exclusion to its blend modes. Other merge modes, other records (a lens record of version 13 is 84 bytes) and the argument before version 13 are not applied, and the reader names them with lenses in the warnings | K L859 (the argument); KF L707-L798 (the records, the 117-byte body and the merge modes); S: the version 1300 record of LT `square_blackfill_nooutline_transparency50percent` of `testset/15` to `testset/25` is 117 bytes long, with 50.0 at byte 61 and 0 at byte 77; the lens records of UC `corel_lens_test_x3.cdr` (13) are 84 bytes long; of the sample files of versions 7 to 25, the argument is on the see-through objects that the pictures of LT `square_blackfill_nooutline_transparency50percent` of `testset/12` to `testset/25`, TDF 80103 and eight UC lens test files of versions 7 to 13 show, and otherwise only on text in UC `fancytext_cdr7.cdr` to `fancytext_x3.cdr` and on two objects of TDF 114901. The value K reads at byte 10 (14 from version 13) is not the transparency in these samples | public-spec (the argument: K; what it marks: sample; the direction of the value: VectorCraft's own reading, as every sample is at 50%, and a wrong reading shows a 25% transparency at 75%; the layout before version 13: unconfirmed, and it is not read) | +| R48 | Bit 2 (0x04) of the outline's line type marks the outline dashed; the dashes of an outline without it are not drawn | S: every outline of versions 6 to 25 in the sample files with that bit set (316 of them, in 29 files) stores dashes; TDF 76771 (version 15) stores dashes 2 and 1 in an outline of line type 0x22, and the file's picture draws that outline solid | sample | +| R49 | Bit 4 (0x10) of the outline's line type puts the outline behind the fill | S: UC `outl_behind_fill_cdr7.cdr` to `outl_behind_fill_x3.cdr`, whose outline of line type 0x12 the file's picture shows behind the fill, and whose other outlines (0x02) it shows over the fill | sample | +| R50 | Bit 5 (0x20) of the outline's line type scales the outline's width and dashes with the shape's matrix. The engine multiplies them by the square root of the matrix's area factor (VectorCraft's own value for a matrix that scales x and y differently) | S: UC `outl_scale_with_cdr7.cdr` to `outl_scale_with_cdr12.cdr`, of whose outlines only one, 3.969 mm wide, has line type 0x22 and the others 0x02 or 0x01; TDF 76771 (version 15), whose outline of line type 0x22 is 10 mm wide on a shape that the matrix stretches and skews, and whose picture draws that outline several times wider and skewed | sample (the bit; the single width for a matrix that scales x and y differently: VectorCraft's own) | +| R51 | A `trfd` offsets table holds one offset more than the entries; each entry runs from its offset to the next, and the last offset is the record's end | KF L1079, L1113-L1121; S: every `trfd` of versions 4 to 25 in the sample files (25,425 records) has the extra offset, equal to the record's length | public-spec | +| R52 | Byte 0 of argument 14001 is the fill's winding flag. VectorCraft reads a byte other than 0 as the nonzero fill rule, and 0 or an object without the argument as even-odd | KF L575-L583, L1047; S: the argument is 4 bytes in the sample files that carry it, with byte 0 = 1 on LT `complexshape_blackfill_nooutline` of `testset/12` and `testset/15` to `testset/25` and on objects of TDF 127576 (13) and 60026 (14), and 0 on 27 objects of TP `example.cdr` (17) | public-spec (the flag: KF; which rule each value means, and the rule without the argument: VectorCraft's own reading, and a wrong reading fills or leaves holes where a curve's subpaths overlap) | +| R53 | A `.cmx` file is a RIFF form of type `CMX1`, little-endian (a `RIFX` form is big-endian and is refused); its chunks are laid out as R4. A chunk can run short of its contents: when the bytes after it don't read as a chunk id (an ASCII letter, then three ASCII letters, digits or spaces), the next id is the first at an even distance of 2 to 64 bytes that names a chunk the reader uses or whose length keeps it inside its list (VectorCraft's own rule) | CN "Container"; S: all 14 CX files are `RIFF` forms of type `CMX1`; in `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, `gold_bar.cmx`, `goldblue.cmx`, `squares.cmx` and `thatch.cmx` 16 bytes follow `ccmm` and 4 follow `rlst` before the next id | sample | +| R54 | `cont`: byte 52 is the coordinate size as an ASCII digit, `4` for 32-bit coordinates and `2` for 16-bit ones (refused); bytes 64 to 72 hold an f64, the size of a coordinate unit in meters. A value that isn't above 0 and at most 1 reads as 0.1 µm (VectorCraft's own fallback) | CN "Container"; S: the nine CX files with `4` all hold 1e-7; `abydos.cmx`, `CM33.CMX`, `LIZARDS.CMX`, `output.000.cmx` and `test.cmx` hold `2` | sample | +| R55 | A table (`rclr`, `rpen`, `rott`, `rdot`, `rotl`) is a u16 entry count, then one field list per entry; an instruction's body is field lists too. A field is a u8 tag, a u16 length counting its 3 header bytes, and the data; 0xff ends the list. Objects name table entries from 1 | CN "Tables"; S: every one of these tables in the nine CX files with 32-bit coordinates reads its count of entries with no bytes left | sample | +| R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); S: every color of the nine CX files is model 2 in the older fields | sample (model 2), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) | +| R57 | `rpen` field 1: the width as a u32 in coordinate units (then an aspect, an angle and a matrix, not read). `rott` field 1: a flags byte (1 no outline, 2 solid, 4 dashed, 8 behind the fill, 16 scaled with the object), then the caps in the low 4 bits and the join in the high 4 bits, numbered as R12. `rdot` field 1: a u16 count, then the dash and gap lengths in outline widths (u16 each). A pattern whose lengths are all 0 draws a solid line, as R48's | CN "Tables"; S: line types 0x02 and 0x22 with caps and joins 0x00, 0x01 and 0x11 in the CX files | public-notes (the flags 4, 8 and 16 and the cap and join numbering; bit 0x20, set in `balloon.cmx`, is not read) | +| R58 | `rotl` field 1: six u16, the 1-based entries of the outline's line type, screen, color, arrowhead pair, pen and dash pattern | CN "Tables"; S: every `rotl` entry of the CX files names entries that exist | sample | +| R59 | `rota`: a u16 count, then pairs of u16 (start and end arrowheads, 0 for none), not field lists | CN "Tables"; S: `rota` is `01 00 00 00 00 00` in every CX file | sample (pairs of 0), public-notes (other values) | +| R60 | A `page` chunk is a stream of instructions: a u16 size counting the whole instruction and an i16 code, or 0xFFFF, a u32 size and the code (the long form); then field lists. Codes: 9 and 10 begin and end a page, 11 and 12 a layer, 13 and 14 a group, 67 a curve; 20 and 21 a text object, 65 its drawn characters, 66 an ellipse, 68 a rectangle, 69 an image, 88 and 89 add and remove a clipping path, 111 a jump whose field 1 is the u32 file offset to go on from (the bytes jumped over hold images). Objects are drawn in file order, the first at the back | CN "page: instructions"; S: codes 9 to 14 and 67 in the CX files; in `squares.cmx` the large square comes first and the two smaller ones inside it after | sample (9 to 14, 67, the order), public-notes (the long form and the other codes) | +| R61 | Field 4 of instruction 9: the page's width and height, u32 each in coordinate units. Without it, field 1 gives the drawing's bounds: a u16 page number, a u32, then the left, top, right and bottom edges as i32 in coordinate units; the page takes the bounds' size and is centered on them (VectorCraft's own choice). Without either, the page has no size, and the importer gives it 612 × 792 pt as it does a `.cdr` page without one (VectorCraft's own size) | CN "page: instructions"; S: none of the CX files has field 4; in all nine with 32-bit coordinates, the four edges in field 1 match the extent of the file's curves | public-notes (field 4), sample (field 1) | +| R62 | A layer's name: field 4 as a u32 count and UTF-16 units, or field 1 from byte 12 as a u16 count and 8-bit characters (read as Windows-1252, VectorCraft's own choice); a layer without a name is left unnamed, as a `.cdr` layer is. A curve: field 1 its rendering attributes, field 2 a u16 point count, the points as i32 x and y, then a type byte for each as R16; coordinates are from the page's center, y up. A field 2 too short for its count is read as whole points with their type bytes when its length is a multiple of 9, and the curve is left out as damaged otherwise (VectorCraft's own rule) | CN "page: instructions" and "Coordinates"; S: the 8-bit names `Layer 1`, `Desktop`, `Grid` and `Guides` of the CX files (the last three hold nothing in every file); every curve of the CX files has field 2 of exactly 2 + 9 bytes per point | sample (8-bit names, curves), public-notes (field 4) | +| R63 | Rendering attributes: a mask (1 fill, 2 outline, 4 lens, 8 canvas, 16 container; lenses, canvases and containers are not read, with a warning), then a field list for the fill when the mask names it and one for the outline. The fill's field 1 is a u16 type and a field list; type 0 is no fill, type 1 a uniform fill whose field 1 is the color entry (u16) and a screen (u16); other types (2 fountain and more) are not read. The outline's field 1 is its `rotl` entry (u16) | CN "Rendering attributes"; S: masks 1, 2 and 3, fill types 1, 2 and 6, and uniform fills with a 4-byte field 1 in the CX files | sample | diff --git a/crates/cdr/README.md b/crates/cdr/README.md new file mode 100644 index 0000000000..007258e931 --- /dev/null +++ b/crates/cdr/README.md @@ -0,0 +1,98 @@ +# vectorcraft-cdr + +A bounded Rust reader for `.cdr` drawings of versions 1 to 27 (and `.cdt` templates). +It reads the `WL` files of versions 1 and 2, the RIFF chunk tree of versions 3 and later with its +compressed lists, the ZIP packages that versions 14 and later save (with the data streams of +versions 16 and later) and the records listed below, and hands the engine a drawing in points, +with each object's transform. It does not write `.cdr` files. + +## What is read + +| In the `.cdr` file | Read as | +|---|---| +| ZIP packages: `content/riffData.cdr` (versions 14 and 15), `content/root.dat` with the data streams `content/dataFileList.dat` names (16 on) | the RIFF chunk tree; a data stream is inflated only when a chunk the reader reads, or a list it splits, points into it | +| Pages, the page size in `mcfg` or a page's own size | pages, laid out by the engine as artboards side by side | +| Layers (drawing, desktop, guides and grid layers), the master page's among them | layers by name and kind | +| The hidden and locked flags of layers, groups and objects | flags | +| Guidelines (object type 0x16, and the version 7 `guid` chunk) | guidelines at their point and angle | +| Groups (`LIST grp `) | groups | +| Clipping containers and the groups of `LIST clpt` they clip | the container with the objects it clips | +| Curves (point lists of moves, lines and cubic curves) and paths (object type 0x25, version 10 on) | paths | +| Rectangles (one corner radius, four from version 9) | rectangles with each corner's radius | +| Ellipses, arcs and pies | ellipses, and paths for arcs and pies | +| Polygons and stars (a base side copied for each side) | paths | +| Uniform fills: CMYK, CMY, RGB, gray, registration, library colors | colors, spot colors with their tints | +| The fill's winding flag | the nonzero fill rule, or even-odd | +| Outlines: width, caps, joins, dashes, the no-outline and behind-the-fill flags, and from version 13 a library color named in their property list | outlines | +| Uniform transparency (version 13 on) and its merge mode | the shape's opacity and blend mode | +| Styles (`LIST stlt`, versions 7 to 15) that objects name | the fill and outline of an object that has none of its own | + +Text, bitmaps, linked groups (blends, contours, brush strokes), B-spline curves, fountain, +pattern, texture and PostScript fills, outline arrowheads, lenses, transparency other than uniform +transparency of version 13 and later, and merge modes without a VectorCraft blend mode are not +read; the drawing's +`warnings` name each kind it held. Drawings of versions after 27 are refused, and so are packages +that are encrypted, ZIP64 archives or split across files. + +VectorCraft reads a uniform transparency's stored value as the transparency in percent (0 opaque, +100 clear), and a winding flag other than 0 as the nonzero fill rule. These are VectorCraft's own +readings: no public source states either direction. + +## Versions 1 to 4 + +Public specifications cover only parts of these versions, such as the version 3 fill and page +settings. For the rest, the reader follows the layouts of public sample files that +`PROVENANCE.md` lists (rows R31 to R44), and its tests read the synthetic files that +`src/synth.rs` builds from those rows. + +| Version | Read | Left out or refused | +|---|---|---| +| 1 and 2 (`WL` files) | the page size; rectangles with one corner radius, whole ellipses and curves, each with its matrix; uniform fills and outlines with their width and color, in CMYK percent and the inks black and white. The objects come in on one page and one layer, front to back | text and objects of other types, and ellipses whose two angles differ (arcs and pies), with the unsupported-objects warning; fills of other types, with the unsupported-fills warning; inks of a numbered library, which read as spot colors without a look; groups and layers, whose records are passed over; dashes, caps, joins and arrowheads, which the reader does not look for; the records after a drawn object of another type, with the unsupported-objects warning | +| 3 (RIFF, form type `CDR `) | the page size from the page's corners; pages, layers and groups; rectangles, ellipses, arcs and curves with the matrices of the object and of the groups around it; uniform fills; outlines with their width, color, caps, joins and dashes | text and bitmaps; envelopes, with the envelopes warning (the objects and groups under one keep their outlines and matrices); fountain, pattern and texture fills; arrowheads | +| 4 (RIFF, form type `CDR4`) | as version 5, with the colors and the fixed-point transforms of version 4 | as version 5 | + +A file is taken for version 1 or 2 by its content only when, after `WL`, its marker byte is one of +`e`, `l` and `m`, the next byte is zero, and the offsets of its header fit the file. The reader +reports version 1 for the marker `e` and version 2 for the other two. A RIFF file that names +a version before 3 is refused, and so is the version 4 template form type `CDST`, which reads as +not a `.cdr` drawing. + +## `.cmx` files + +`read_cmx` reads `.cmx` exchange files with 32-bit coordinates (rows R53 to R63) into the same +drawing model, with a version of 0. It reads the color, pen, line type, dash, outline and +arrowhead tables, then each page's instructions in drawing order: + +| In the `.cmx` file | Read as | +|---|---| +| Pages, with the size the page gives, or else the size of the drawing's bounds that the page stores | pages; a page sized to the bounds is centered on them | +| Layers, by their UTF-16 or 8-bit name | drawing layers, unnamed when the file gives no name; a layer that holds nothing is left out | +| Groups | groups | +| Curves (moves, lines and cubic curves, as `.cdr` point lists) | paths | +| Uniform fills: CMYK in percent or 0 to 255, CMY, RGB, gray, and library colors with their names | colors, spot colors | +| Outlines: width, color, caps, joins, dashes, the no-outline, behind-the-fill and scaled-with flags | outlines | + +Text, images, rectangles, ellipses, clipping paths, fills other than uniform ones, outline +arrowheads and lenses are not read; the drawing's `warnings` name each kind it held. A clipping +path is left out and the objects it clips are read without it. Files in big-endian byte order and +files with 16-bit coordinates are refused. + +## Provenance + +`PROVENANCE.md` lists every record layout the reader relies on, with its public source and status. +Code cites the rows by id (`R1` ...), and `tests/it/provenance.rs` fails when a cited id has no row. +The test inputs are synthetic drawings built by `src/synth.rs` and `src/synth_cmx.rs` (the +`synth` feature); no third-party file is committed. + +## Limits + +`Limits` bounds the input size, the bytes inflated from compressed lists and package members, the +size of one package member, the number of members, the nesting depth, the chunk count, the +objects, the coordinates and the outline dashes of one read. Past a limit the reader stops with an +error or leaves the rest out with a warning; it does not recurse and does not panic. Each record +of a version 1 or 2 file counts toward the chunk count, and the transform entries of a version 3 +object are held to the arguments one record may have. A package's +data stream is read once however many lines of `content/dataFileList.dat` name it. A redirected +list whose bytes overlap those of an earlier redirected list is left out with the damage warning. +Other records may share bytes, and the bytes read again may add up to the member limit; past it +the records are left out with the limit warning. diff --git a/crates/cdr/src/build.rs b/crates/cdr/src/build.rs new file mode 100644 index 0000000000..758c8886b6 --- /dev/null +++ b/crates/cdr/src/build.rs @@ -0,0 +1,816 @@ +//! The drawing the chunk index holds: pages, layers, objects and the fills and outlines they name +//! (R19 to R23). Records are decoded only when an object refers to them. + +use std::collections::HashMap; + +use crate::bytes::Rd; +use crate::geometry; +use crate::inline; +use crate::layout::{self, Profile}; +use crate::limits::Budget; +use crate::model::{Blend, Color, Drawing, Flags, Geometry, Guideline, Layer, LayerKind, Matrix, Object, Outline, Page, Pt, Shape}; +use crate::records::{self, Loda}; +use crate::riff::{Chunk, Index, push}; +use crate::styles::Styles; +use crate::{Error, Warning}; + +/// Object types (R6). +const RECTANGLE: u32 = 1; +const ELLIPSE: u32 = 2; +const CURVE: u32 = 3; +const POLYGON: u32 = 0x14; +const GUIDELINE: u32 = 0x16; +const PATH: u32 = 0x25; +/// Argument types (R6, R20, R21, R33, R52). +const ARG_OUTLINE: u32 = 10; +const ARG_FILL: u32 = 20; +const ARG_COORDS: u32 = 30; +const ARG_TRANSFORMS: u32 = 100; +const ARG_STYLE: u32 = 200; +const ARG_NAME: u32 = 1000; +const ARG_LENS: u32 = 8000; +const ARG_CONTAINER: u32 = 8005; +const ARG_POLYGON: u32 = 11000; +const ARG_WINDING: u32 = 14001; +const ARG_GUIDE: u32 = 16000; +const ARG_PAGE_SIZE: u32 = 19130; + +/// What a RIFF file that names a version before 3 is refused as. +const BEFORE_3: &str = "RIFF files of versions before 3"; + +/// What one read keeps while mapping. +struct Ctx<'a, 'b> { + ix: &'b Index<'a>, + p: Profile, + budget: &'b mut Budget, + warn: &'b mut Vec, + /// Fill and outline records by id, decoded on first use. + fill_chunks: HashMap, + outline_chunks: HashMap, + fills: HashMap>, + outlines: HashMap>, + /// The styles objects name in argument 200 (R45): `Err` when the file's style table doesn't + /// parse. + styles: Result, + /// The groups of `LIST clpt` that containers clip, by the id in their `spnd` chunk (R46). + clips: HashMap, + /// The clipped groups being read, innermost last. + open_clips: Vec, + /// Whether the walk of a clipped group stopped at the clipped chunk limit. + clip_cut: bool, +} + +/// The most clipped groups read one inside another: VectorCraft's own limit. +const MAX_CLIP_DEPTH: usize = 64; + +pub(crate) fn drawing(ix: &Index, budget: &mut Budget, warn: &mut Vec) -> Result { + let root = ix.root().ok_or(Error::NotCdr)?; + let version = ix.version(); + // A template whose `vrsn` chunk doesn't name a version read (R28). + if version == 0 { + return Err(Error::NotCdr); + } + // Versions 1 and 2 are `WL` files (R40); no source shows a RIFF file that names a version + // before 3. + if version < layout::OLDEST_RIFF { + return Err(Error::Unsupported(BEFORE_3)); + } + let p = layout::for_version(version).ok_or(Error::Version(version))?; + let mut found = Found::default(); + collect(ix, root, &mut found); + let page_size = found.mcfg.and_then(|c| page_size(ix.data(c), &p)); + // Before version 7 a `LIST stlt` holds chunks, not the style table (R4). + let styles = match found.stlt { + Some(c) if version >= 700 => Styles::read(ix.data(c), version, budget)?.ok_or(()), + _ => Ok(Styles::default()), + }; + let mut cx = Ctx { + ix, + p, + budget, + warn, + fill_chunks: HashMap::new(), + outline_chunks: HashMap::new(), + fills: HashMap::new(), + outlines: HashMap::new(), + styles, + clips: HashMap::new(), + open_clips: Vec::new(), + clip_cut: false, + }; + // The `spnd` id is a u16 in files of 16-bit fields (R46). + let spnd = |b: &[u8]| if p.short { Rd::new(b).u16().map(u32::from) } else { Rd::new(b).u32() }; + for g in found.clpt.iter().flat_map(|c| ix.children(c)).filter(|g| g.is_list(b"grp ")) { + if let Some(id) = ix.children(g).iter().find(|c| &c.id == b"spnd").and_then(|c| spnd(ix.data(c))) { + cx.clips.entry(id).or_insert(g); + } + } + for c in &found.fills { + if let Some(id) = Rd::new(ix.data(c)).u32() { + cx.fill_chunks.entry(id).or_insert(ix.data(c)); + } + } + for c in &found.outlines { + if let Some(id) = Rd::new(ix.data(c)).u32() { + cx.outline_chunks.entry(id).or_insert(ix.data(c)); + } + } + let mut guides = found.guid.map(|c| guid_chunk(ix.data(c), &cx.p, cx.budget, cx.warn)).unwrap_or_default(); + let mut pages = Vec::new(); + let mut master = Vec::new(); + for page in &found.pages { + let (is_master, read) = cx.page(page); + if is_master { + // Guidelines on any of the master page's layers show on every page. + for mut layer in read.layers { + guides.append(&mut layer.guides); + if !layer.objects.is_empty() && layer.kind != LayerKind::Grid { + master.push(layer); + } + } + } else { + pages.push(read); + } + } + // A file of only a master page keeps it as its page. + if pages.is_empty() && !master.is_empty() { + pages.push(Page { size: None, layers: std::mem::take(&mut master) }); + } + Ok(Drawing { version, page_size, pages, master, guides, warnings: std::mem::take(cx.warn) }) +} + +#[derive(Default)] +struct Found<'i> { + fills: Vec<&'i Chunk>, + outlines: Vec<&'i Chunk>, + mcfg: Option<&'i Chunk>, + guid: Option<&'i Chunk>, + stlt: Option<&'i Chunk>, + clpt: Vec<&'i Chunk>, + pages: Vec<&'i Chunk>, +} + +/// Every fill, outline, `LIST clpt` and page in file order, and the first `mcfg`, `guid` and +/// `LIST stlt`; pages are not looked into. +fn collect<'i>(ix: &'i Index, root: &'i Chunk, found: &mut Found<'i>) { + let mut stack: Vec<&Chunk> = ix.children(root).iter().rev().collect(); + while let Some(c) = stack.pop() { + match &c.id { + b"fild" | b"fill" => found.fills.push(c), + b"outl" => found.outlines.push(c), + b"mcfg" => found.mcfg = found.mcfg.or(Some(c)), + b"guid" => found.guid = found.guid.or(Some(c)), + // Before version 7 the list holds chunks, which are looked through. + _ if c.is_list(b"stlt") => { + found.stlt = found.stlt.or(Some(c)); + stack.extend(ix.children(c).iter().rev()); + } + _ if c.is_list(b"clpt") => found.clpt.push(c), + _ if c.is_list(b"page") => found.pages.push(c), + _ => stack.extend(ix.children(c).iter().rev()), + } + } +} + +/// The page size in `mcfg` (R10); in version 3 the distance between the page's two corners, after +/// 2 bytes (R38). +fn page_size(b: &[u8], p: &Profile) -> Option<(f64, f64)> { + let mut r = Rd::at(b, p.mcfg_skip); + if p.mcfg_corners { + r.skip(2)?; + let (x0, y0, x1, y1) = (records::coord(&mut r, p)?, records::coord(&mut r, p)?, records::coord(&mut r, p)?, records::coord(&mut r, p)?); + return sane_size(x1 - x0, y1 - y0); + } + sane_size(records::coord(&mut r, p)?, records::coord(&mut r, p)?) +} + +fn sane_size(w: f64, h: f64) -> Option<(f64, f64)> { + let (w, h) = (w.abs(), h.abs()); + (w > 0.0 && h > 0.0).then_some((w, h)) +} + +/// The version 7 `guid` chunk (R23): two counts, then 40-byte records laid out as argument 16000. +/// Each guideline counts toward the objects a read maps; past them the rest are left out. +fn guid_chunk(b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Vec { + let mut r = Rd::new(b); + let Some(n) = r.u32() else { return Vec::new() }; + let _again = r.u32(); + let fits = r.left() / 40; + if n as usize > fits { + push(warn, Warning::Damaged); + } + let n = (n as usize).min(fits); + let mut out = Vec::new(); + for i in 0..n { + if !budget.take_object() { + push(warn, Warning::TooDeep); + break; + } + out.extend(b.get(8 + i * 40..8 + (i + 1) * 40).and_then(|g| guideline(g, p))); + } + out +} + +/// A guideline record (R23): 12 bytes, the angle in millionths of a degree, then a point. +fn guideline(b: &[u8], p: &Profile) -> Option { + if p.short { + return None; + } + let mut r = Rd::at(b, 12); + let angle = f64::from(r.i32()?) / 1_000_000.0; + let at = Pt { x: records::coord(&mut r, p)?, y: records::coord(&mut r, p)? }; + Some(Guideline { at, angle, hidden: false }) +} + +/// Marks the guidelines from `from` on hidden when `flags` hide what holds them. +fn hide_guides(guides: &mut [Guideline], from: usize, flags: Flags) { + if flags.hidden { + for g in guides.iter_mut().skip(from) { + g.hidden = true; + } + } +} + +/// A list's flags (R19): four bytes. +fn flags(ix: &Index, list: &Chunk) -> Option<[u8; 4]> { + let c = ix.children(list).iter().find(|c| &c.id == b"flgs")?; + ix.data(c).get(..4)?.try_into().ok() +} + +/// Whether a layer, group or object list is hidden (bit 0x01 of byte 1) or locked (bit 0x10 of +/// byte 0) (R19). +fn state(ix: &Index, list: &Chunk) -> Flags { + flags(ix, list).map_or(Flags::default(), |[b0, b1, _, _]| Flags { hidden: b1 & 0x01 != 0, locked: b0 & 0x10 != 0 }) +} + +/// `o` with `f` added to its own flags: the objects of a group left ungrouped keep the group's. +fn inherit(o: &mut Object, f: Flags) { + let own = match o { + Object::Shape(s) => &mut s.flags, + Object::Group { flags, .. } => flags, + Object::Clip { container, .. } => &mut container.flags, + }; + own.hidden |= f.hidden; + own.locked |= f.locked; +} + +/// What a layer's object type makes it (R19): 11 a grid, 12 guides, 17 the desktop, any other a +/// drawing layer. Version 3 counts its types from 0, one less (R32). +fn layer_kind_of_type(kind: u32, types_from_zero: bool) -> LayerKind { + match kind.saturating_add(u32::from(types_from_zero)) { + 11 => LayerKind::Grid, + 12 => LayerKind::Guides, + 17 => LayerKind::Desktop, + _ => LayerKind::Drawing, + } +} + +/// What a layer's flags make it, for a layer without an object type of its own (R19). The low +/// four bits of byte 0 hold the kind: 0x0a guides, or a grid with bit 0x10 set (versions 7 to 13 +/// also flag them 0x02); 0x08 the desktop when byte 2 is set, a drawing layer when it is clear. +/// Versions 7 to 13 may flag the master page's desktop layer 0 with bytes 1 and 2 set. Bit 0x10 +/// alone does not make a grid. +fn layer_kind(f: [u8; 4], version_below_14: bool) -> LayerKind { + let [b0, b1, b2, _] = f; + let grid_bit = b0 & 0x10 != 0; + match b0 & 0x0f { + 0x0a if grid_bit => LayerKind::Grid, + 0x0a => LayerKind::Guides, + 0x02 if version_below_14 && grid_bit => LayerKind::Grid, + 0x02 if version_below_14 => LayerKind::Guides, + 0x08 if b2 != 0 => LayerKind::Desktop, + 0 if version_below_14 && b1 == 1 && b2 == 1 => LayerKind::Desktop, + _ => LayerKind::Drawing, + } +} + +/// The first chunk of one of `ids` that a page, layer or object keeps for itself: among its own +/// chunks, or in its `lgob` list and the `trfl` list there (R22). +fn own_chunk<'i>(ix: &'i Index, list: &'i Chunk, ids: &[&[u8; 4]]) -> Option<&'i Chunk> { + let mut stack: Vec<(&Chunk, u8)> = ix.children(list).iter().rev().map(|c| (c, 0)).collect(); + while let Some((c, depth)) = stack.pop() { + if ids.contains(&&c.id) { + return Some(c); + } + if depth < 2 && (c.is_list(b"lgob") || c.is_list(b"trfl")) { + stack.extend(ix.children(c).iter().rev().map(|k| (k, depth + 1))); + } + } + None +} + +/// The `loda` (or `lobj`) a page, layer or object keeps for itself. +fn own_loda<'i>(ix: &'i Index, list: &'i Chunk) -> Option<&'i Chunk> { + own_chunk(ix, list, &[b"loda", b"lobj"]) +} + +/// A page's layer lists in file order: its own, and those in the lists it holds, such as the +/// `gobj` list of files of versions 7 to 13 (R22). +fn page_layers<'i>(ix: &'i Index, page: &'i Chunk) -> Vec<&'i Chunk> { + let mut out = Vec::new(); + let mut stack: Vec<&Chunk> = ix.children(page).iter().rev().collect(); + while let Some(c) = stack.pop() { + if c.is_list(b"layr") { + out.push(c); + } else if c.id == crate::riff::LIST && !c.is_list(b"lgob") { + stack.extend(ix.children(c).iter().rev()); + } + } + out +} + +/// One frame of the object walk: a list's chunks, the next one to look at, and the objects so far. +struct Frame<'i> { + chunks: &'i [Chunk], + next: usize, + objects: Vec, + /// Whether its objects form a group in the frame below. + group: bool, + /// The group's own flags. + flags: Flags, + /// The first of the guidelines read inside it. + guides_from: usize, + /// What places its objects after their own transforms: the matrices of the version 3 groups + /// around them (R33). The identity in other versions, whose objects hold their whole transform. + outer: Matrix, +} + +impl<'a, 'b> Ctx<'a, 'b> { + /// A page: whether it is the master page, and its layers. + fn page(&mut self, page: &Chunk) -> (bool, Page) { + let ix = self.ix; + let is_master = flags(ix, page).is_some_and(|f| f[2] != 0); + let size = own_loda(ix, page) + .and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn)) + .and_then(|l| l.arg(ARG_PAGE_SIZE).and_then(|b| self.size_arg(b))); + let mut layers = Vec::new(); + for l in page_layers(ix, page) { + let layer = self.layer(l); + let empty = layer.objects.is_empty() && layer.guides.is_empty(); + // The entries that stand for the master page's layers hold nothing of the page's own. + if empty && (is_master || layer.kind != LayerKind::Drawing) { + continue; + } + layers.push(layer); + } + (is_master, Page { size, layers }) + } + + fn size_arg(&self, b: &[u8]) -> Option<(f64, f64)> { + let mut r = Rd::new(b); + sane_size(records::coord(&mut r, &self.p)?, records::coord(&mut r, &self.p)?) + } + + fn layer(&mut self, list: &Chunk) -> Layer { + let ix = self.ix; + let loda = own_loda(ix, list).and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn)); + // The layer's own object type says what it is; its flags, only when it has none (R19). + let kind = match &loda { + Some(l) => layer_kind_of_type(l.kind, self.p.types_from_zero), + None => flags(ix, list).map_or(LayerKind::Drawing, |f| layer_kind(f, self.p.old_master_flags)), + }; + let name = loda.and_then(|l| l.arg(ARG_NAME).map(|b| records::name(b, &self.p, self.warn))).unwrap_or_default(); + let mut guides = Vec::new(); + let objects = self.objects(ix.children(list), &mut guides); + let flags = state(ix, list); + hide_guides(&mut guides, 0, flags); + Layer { name, kind, flags, objects, guides } + } + + /// The objects of a layer's chunks, groups nested, front to back; guidelines go to `guides`. + fn objects(&mut self, chunks: &'b [Chunk], guides: &mut Vec) -> Vec { + let ix = self.ix; + let mut stack = vec![Frame { + chunks, + next: 0, + objects: Vec::new(), + group: false, + flags: Flags::default(), + guides_from: guides.len(), + outer: Matrix::IDENTITY, + }]; + loop { + let Some(top) = stack.last_mut() else { return Vec::new() }; + let (here, outer) = (top.chunks, top.outer); + let Some(c) = here.get(top.next) else { + let Some(done) = stack.pop() else { return Vec::new() }; + // A hidden group hides the guidelines inside it. + hide_guides(guides, done.guides_from, done.flags); + match stack.last_mut() { + // A group counts toward the objects a read maps; past them its objects stay, + // ungrouped, with the group's flags. + Some(parent) if done.group && !done.objects.is_empty() => { + if self.budget.take_object() { + parent.objects.push(Object::Group { objects: done.objects, flags: done.flags }); + } else { + push(self.warn, Warning::TooDeep); + let mut objects = done.objects; + for o in &mut objects { + inherit(o, done.flags); + } + parent.objects.extend(objects); + } + } + Some(parent) if !done.group => parent.objects.extend(done.objects), + Some(_) => {} + None => return done.objects, + } + continue; + }; + top.next += 1; + // Every chunk of a clipped group counts, empty groups included, each time a container + // names the group; past the limit the group is left out. + if !self.open_clips.is_empty() && !self.budget.take_clipped_chunk() { + push(self.warn, Warning::TooDeep); + self.clip_cut = true; + return Vec::new(); + } + if c.is_list(b"obj ") { + if let Some(o) = self.object(c, guides, &outer) { + top.objects.push(o); + } + } else if c.is_list(b"grp ") { + let own = self.group_placement(c); + let flags = state(ix, c); + let guides_from = guides.len(); + stack.push(Frame { chunks: ix.children(c), next: 0, objects: Vec::new(), group: true, flags, guides_from, outer: outer.after(&own) }); + } else if c.is_list(b"lnkg") { + // Linked groups (brush strokes, blends, contours) place their objects with a + // matrix of their own, which this reader doesn't apply: they are left out. + push(self.warn, Warning::UnsupportedObjects); + } else if c.id == crate::riff::LIST && !c.is_list(b"lgob") { + // Other lists under a layer are looked through (R22). + let guides_from = guides.len(); + stack.push(Frame { chunks: ix.children(c), next: 0, objects: Vec::new(), group: false, flags: Flags::default(), guides_from, outer }); + } + } + } + + /// The matrix a group places its objects with. Only a version 3 group has one, in the + /// transforms argument of its own `lobj` (R33); one that can't be read is damage, and the + /// group's objects stay where their own transforms put them. + fn group_placement(&mut self, list: &Chunk) -> Matrix { + if !self.p.inline_styles { + return Matrix::IDENTITY; + } + let ix = self.ix; + let Some(arg) = + own_loda(ix, list).and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn)).and_then(|l| l.arg(ARG_TRANSFORMS)) + else { + return Matrix::IDENTITY; + }; + self.placement(arg) + } + + /// The matrices of a transforms argument (R33). An envelope among them is not applied: the + /// shapes keep their outlines, placed by the matrices alone, with the envelopes warning. + fn placement(&mut self, arg: &[u8]) -> Matrix { + match inline::transforms(arg, &self.p, &self.budget.limits, self.warn) { + Some(t) => { + if t.envelope { + push(self.warn, Warning::Envelopes); + } + t.matrix + } + None => { + push(self.warn, Warning::Damaged); + Matrix::IDENTITY + } + } + } + + /// One `LIST obj `: a shape placed by its own transform and then by `outer`, or `None` (a + /// guideline goes to `guides`). + fn object(&mut self, list: &Chunk, guides: &mut Vec, outer: &Matrix) -> Option { + let ix = self.ix; + let Some(loda) = own_loda(ix, list).and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn)) else { + push(self.warn, Warning::Damaged); + return None; + }; + // Guidelines count toward the objects a read maps. + if !self.budget.take_object() { + push(self.warn, Warning::TooDeep); + return None; + } + let flags = state(ix, list); + if loda.kind == GUIDELINE { + guides.extend(loda.arg(ARG_GUIDE).and_then(|b| guideline(b, &self.p)).map(|g| Guideline { hidden: flags.hidden, ..g })); + return None; + } + if self.p.inline_styles { + return self.inline_object(&loda, outer, flags); + } + let geometry = self.geometry(&loda)?; + // A uniform transparency from version 13 applies (R47); a lens, and a transparency of + // another kind or version, is not applied: the shape shows opaque. + let (opacity, blend) = match loda.arg(ARG_LENS) { + None => (1.0, Blend::Normal), + Some(b) => match records::transparency(b).filter(|_| self.p.tagged) { + Some(t) => t, + None => { + push(self.warn, Warning::Lenses); + (1.0, Blend::Normal) + } + }, + }; + let nonzero = self.nonzero(&loda); + // A transform that is there but can't be read is damage; the shape stays where it is. + let matrix = match own_chunk(ix, list, &[b"trfd"]) { + None => Matrix::IDENTITY, + Some(c) => records::trfd(ix.data(c), &self.p).unwrap_or_else(|| { + push(self.warn, Warning::Damaged); + Matrix::IDENTITY + }), + }; + // Without a fill or outline argument of its own, an object takes its style's (R45). The + // style id is a u16 in files of 16-bit fields. + let style = loda.arg(ARG_STYLE).and_then(|b| if self.p.short { self.short_id(b) } else { self.id(b) }); + let fill_id = match loda.arg(ARG_FILL) { + Some(b) => self.id(b), + None => style.and_then(|s| self.style_entry(s, Styles::fill)), + }; + let outline_id = match loda.arg(ARG_OUTLINE) { + Some(b) => self.id(b), + None => style.and_then(|s| self.style_entry(s, Styles::outline)), + }; + let fill = fill_id.and_then(|id| self.fill(id)); + let outline = outline_id.and_then(|id| self.outline(id)); + let shape = Box::new(Shape { geometry, matrix, fill, outline, nonzero, opacity, blend, flags }); + // A container clips the group its argument 8005 names (R46). + Some(match loda.arg(ARG_CONTAINER).and_then(|b| self.id(b)) { + Some(id) => self.clip(shape, id, guides), + None => Object::Shape(shape), + }) + } + + /// `container` and the objects of the clipped group `id`, which keep their own transforms. + /// A group that isn't there is damage; one already being read, past the depth limit or past + /// the chunks clipped groups may walk is left out with the limit warning, the guidelines it + /// holds included. Either way the container stays, as a plain shape. + fn clip(&mut self, container: Box, id: u32, guides: &mut Vec) -> Object { + let Some(&group) = self.clips.get(&id) else { + push(self.warn, Warning::Damaged); + return Object::Shape(container); + }; + if self.open_clips.contains(&id) || self.open_clips.len() >= MAX_CLIP_DEPTH { + push(self.warn, Warning::TooDeep); + return Object::Shape(container); + } + self.open_clips.push(id); + let (ix, mark) = (self.ix, guides.len()); + let objects = self.objects(ix.children(group), guides); + self.open_clips.pop(); + if std::mem::take(&mut self.clip_cut) { + guides.truncate(mark); + return Object::Shape(container); + } + // The clipped group's own flags hide or lock the objects it holds; it and the container + // hide its guidelines. + let flags = state(ix, group); + hide_guides(guides, mark, flags); + hide_guides(guides, mark, container.flags); + if objects.is_empty() { + return Object::Shape(container); + } + let mut objects = objects; + for o in &mut objects { + inherit(o, flags); + } + Object::Clip { container, objects } + } + + /// The record id that argument `b` names; an argument too short for one is damage. + fn id(&mut self, b: &[u8]) -> Option { + let id = id_of(b); + if id.is_none() { + push(self.warn, Warning::Damaged); + } + id + } + + /// A u16 id at the start of argument `b`; an argument too short for one is damage. + fn short_id(&mut self, b: &[u8]) -> Option { + let id = Rd::new(b).u16().map(u32::from); + if id.is_none() { + push(self.warn, Warning::Damaged); + } + id + } + + /// Whether the object's fill rule is nonzero: byte 0 of argument 14001 set (R52). Without the + /// argument the fill is even-odd; an argument without its byte is damage. + fn nonzero(&mut self, loda: &Loda) -> bool { + let Some(b) = loda.arg(ARG_WINDING) else { return false }; + match b.first() { + Some(v) => *v != 0, + None => { + push(self.warn, Warning::Damaged); + false + } + } + } + + /// The fill or outline record that style `id` names; a style table that doesn't parse is + /// damage, and the object is drawn without it. + fn style_entry(&mut self, id: u32, entry: fn(&Styles, u32) -> Option) -> Option { + match &self.styles { + Ok(s) => entry(s, id), + Err(()) => { + push(self.warn, Warning::Damaged); + None + } + } + } + + /// A version 3 object, whose transforms, fill and outline are arguments of its own record + /// (R33, R34, R35). A fill or an outline that is there but can't be read is damage. + fn inline_object(&mut self, loda: &Loda, outer: &Matrix, flags: Flags) -> Option { + let own = match loda.arg(ARG_TRANSFORMS) { + None => Matrix::IDENTITY, + Some(arg) => self.placement(arg), + }; + let geometry = self.geometry(loda)?; + let fill = loda.arg(ARG_FILL).and_then(|b| { + let read = inline::fill(b, &self.p, self.warn); + if read.is_none() { + push(self.warn, Warning::Damaged); + } + read.flatten() + }); + let outline = loda.arg(ARG_OUTLINE).and_then(|b| { + let read = inline::outline(b, &self.p, self.warn); + if read.is_none() { + push(self.warn, Warning::Damaged); + } + read.flatten() + }); + // Past the dashes a read takes, the outline is solid. + let outline = outline.map(|mut o| { + if !o.dashes.is_empty() && !self.budget.take_dashes(o.dashes.len()) { + o.dashes = Vec::new(); + push(self.warn, Warning::TooDeep); + } + o + }); + let nonzero = self.nonzero(loda); + let shape = Shape { nonzero, flags, ..Shape::new(geometry, outer.after(&own), fill, outline) }; + Some(Object::Shape(Box::new(shape))) + } + + fn geometry(&mut self, loda: &Loda) -> Option { + let coords = loda.arg(ARG_COORDS); + // Version 3 counts the first object types from 0, one below the later numbers (R32). + let kind = if self.p.types_from_zero && loda.kind <= 4 { loda.kind + 1 } else { loda.kind }; + // A shape without its coordinates, or a polygon without its sides, is damage like a shape + // whose coordinates can't be read; one left out at the coordinate limit is not. + self.budget.coordinates_refused(); + let g = match kind { + RECTANGLE => coords.and_then(|c| geometry::rect(c, &self.p)), + ELLIPSE => coords.and_then(|c| geometry::ellipse(c, &self.p)), + CURVE => coords.and_then(|c| geometry::point_list(c, &self.p, self.budget, self.warn)).map(Geometry::Path), + PATH if self.p.paths => coords.and_then(|c| geometry::path_record(c, &self.p, self.budget, self.warn)).map(Geometry::Path), + POLYGON => match loda.arg(ARG_POLYGON) { + Some(sides) => coords + .and_then(|c| geometry::point_list(c, &self.p, self.budget, self.warn)) + .and_then(|base| geometry::polygon(&base, sides, &self.p, self.budget, self.warn)), + None => { + push(self.warn, Warning::Damaged); + return None; + } + }, + _ => { + push(self.warn, Warning::UnsupportedObjects); + return None; + } + }; + if g.is_none() && !self.budget.coordinates_refused() { + push(self.warn, Warning::Damaged); + } + g + } + + fn fill(&mut self, id: u32) -> Option { + if let Some(f) = self.fills.get(&id) { + return f.clone(); + } + // A record that is missing or can't be read is damage, and the shape is drawn without a + // fill; id 0 without a record is no fill. + if id != 0 && !self.fill_chunks.contains_key(&id) { + push(self.warn, Warning::Damaged); + } + let read = self.fill_chunks.get(&id).and_then(|b| { + let read = records::fill(b, &self.p, self.warn); + if read.is_none() { + push(self.warn, Warning::Damaged); + } + read.and_then(|(_, c)| c) + }); + self.fills.insert(id, read.clone()); + read + } + + /// The outline of record `id`. Its dashes count toward the read's dashes for every shape that + /// uses it; past them the shape's outline is solid. + fn outline(&mut self, id: u32) -> Option { + if !self.outlines.contains_key(&id) { + // A record that is missing is damage, as one that can't be read is; id 0 without a + // record is no outline. + if id != 0 && !self.outline_chunks.contains_key(&id) { + push(self.warn, Warning::Damaged); + } + let read = self.outline_chunks.get(&id).and_then(|b| { + let read = records::outline(b, &self.p, self.warn); + if read.is_none() { + push(self.warn, Warning::Damaged); + } + read.and_then(|(_, o)| o) + }); + // An outline with more dashes than the read may still take is kept solid. + let read = read.map(|mut o| { + if o.dashes.len() > self.budget.dashes_left() { + o.dashes = Vec::new(); + push(self.warn, Warning::TooDeep); + } + o + }); + self.outlines.insert(id, read); + } + let o = self.outlines.get_mut(&id)?.as_mut()?; + // The dashes left only shrink, so an outline refused once is refused for every later + // shape: its dashes are dropped from the cache, and later shapes take it solid. + if !o.dashes.is_empty() && !self.budget.take_dashes(o.dashes.len()) { + o.dashes = Vec::new(); + push(self.warn, Warning::TooDeep); + } + Some(o.clone()) + } +} + +/// A fill or outline argument: the record id (R20). +fn id_of(b: &[u8]) -> Option { + Rd::new(b).u32() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn layer_flags_name_the_kinds() { + assert_eq!(layer_kind([0, 0, 0, 0x98], true), LayerKind::Drawing); + assert_eq!(layer_kind([0x0a, 0, 0, 0x98], true), LayerKind::Guides); + assert_eq!(layer_kind([0x02, 1, 1, 0x98], true), LayerKind::Guides); + assert_eq!(layer_kind([0x08, 0, 1, 0x98], true), LayerKind::Desktop); + assert_eq!(layer_kind([0, 1, 1, 0x98], true), LayerKind::Desktop); + assert_eq!(layer_kind([0x1a, 0, 1, 0x98], true), LayerKind::Grid); + assert_eq!(layer_kind([0x12, 0, 1, 0x98], true), LayerKind::Grid); + // From version 14 the master page flags its layers by byte 0 alone. + assert_eq!(layer_kind([0x0a, 0, 1, 0x98], false), LayerKind::Guides); + assert_eq!(layer_kind([0x08, 0, 1, 0x98], false), LayerKind::Desktop); + assert_eq!(layer_kind([0x5a, 1, 1, 0x98], false), LayerKind::Grid); + assert_eq!(layer_kind([0x02, 1, 1, 0x98], false), LayerKind::Drawing); + assert_eq!(layer_kind([0, 1, 1, 0x98], false), LayerKind::Drawing); + // Drawing layers flagged 0x10, 0x08, 0x18, 0x40 and 0x58 with byte 2 clear, as sample + // files flag them, and desktop and guides layers with bit 0x40 or 0x10 set. + for f in [[0x10, 0, 0, 0x98], [0x08, 1, 0, 0x98], [0x18, 1, 0, 0x98], [0x40, 0, 0, 0x98], [0x58, 1, 0, 0x98]] { + assert_eq!(layer_kind(f, true), LayerKind::Drawing, "{f:?}"); + assert_eq!(layer_kind(f, false), LayerKind::Drawing, "{f:?}"); + } + assert_eq!(layer_kind([0x18, 0, 1, 0x98], true), LayerKind::Desktop); + assert_eq!(layer_kind([0x48, 0, 1, 0x98], false), LayerKind::Desktop); + assert_eq!(layer_kind([0x4a, 1, 1, 0x98], true), LayerKind::Guides); + } + + /// An outline record refused at the dash limit keeps no dashes in the cache, so the shapes + /// that use it later copy none. + #[test] + fn an_outline_past_the_dash_limit_keeps_no_dashes() { + let v = crate::synth::V(1100); + let pen = crate::synth::Pen { line_type: 4, width: 1.0, cap: 0, join: 0 }; + let record = v.outline(1, pen, &crate::synth::color(5, [0, 0, 0, 255]), &[3, 1, 3]); + let file = crate::synth::riff(1100, &[]); + let mut budget = Budget::new(crate::Limits { dashes: 4, ..crate::Limits::default() }); + let mut warn = Vec::new(); + let ix = crate::riff::Index::build(&file, None, &mut budget, &mut warn).unwrap(); + let mut cx = Ctx { + ix: &ix, + p: layout::for_version(1100).unwrap(), + budget: &mut budget, + warn: &mut warn, + fill_chunks: HashMap::new(), + outline_chunks: HashMap::from([(1, record.as_slice())]), + fills: HashMap::new(), + outlines: HashMap::new(), + styles: Ok(Styles::default()), + clips: HashMap::new(), + open_clips: Vec::new(), + clip_cut: false, + }; + assert_eq!(cx.outline(1).map(|o| o.dashes.len()), Some(3)); + for _ in 0..3 { + assert_eq!(cx.outline(1).map(|o| o.dashes.len()), Some(0)); + assert_eq!(cx.outlines.get(&1).and_then(|o| o.as_ref()).map(|o| o.dashes.len()), Some(0)); + } + assert_eq!(*cx.warn, vec![Warning::TooDeep]); + } +} diff --git a/crates/cdr/src/bytes.rs b/crates/cdr/src/bytes.rs new file mode 100644 index 0000000000..216bd90024 --- /dev/null +++ b/crates/cdr/src/bytes.rs @@ -0,0 +1,76 @@ +//! Little-endian reads that fail instead of panicking. + +/// A cursor over one record's bytes. Every read returns `None` past the end. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Rd<'a> { + b: &'a [u8], + pos: usize, +} + +impl<'a> Rd<'a> { + pub(crate) fn new(b: &'a [u8]) -> Self { + Rd { b, pos: 0 } + } + + pub(crate) fn at(b: &'a [u8], pos: usize) -> Self { + Rd { b, pos } + } + + pub(crate) fn pos(&self) -> usize { + self.pos + } + + pub(crate) fn left(&self) -> usize { + self.b.len().saturating_sub(self.pos) + } + + pub(crate) fn skip(&mut self, n: usize) -> Option<()> { + let end = self.pos.checked_add(n)?; + (end <= self.b.len()).then(|| self.pos = end) + } + + pub(crate) fn bytes(&mut self, n: usize) -> Option<&'a [u8]> { + let end = self.pos.checked_add(n)?; + let s = self.b.get(self.pos..end)?; + self.pos = end; + Some(s) + } + + fn array(&mut self) -> Option<[u8; N]> { + self.bytes(N)?.try_into().ok() + } + + pub(crate) fn u8(&mut self) -> Option { + Some(self.array::<1>()?[0]) + } + + pub(crate) fn u16(&mut self) -> Option { + self.array().map(u16::from_le_bytes) + } + + pub(crate) fn i16(&mut self) -> Option { + self.array().map(i16::from_le_bytes) + } + + pub(crate) fn u32(&mut self) -> Option { + self.array().map(u32::from_le_bytes) + } + + pub(crate) fn i32(&mut self) -> Option { + self.array().map(i32::from_le_bytes) + } + + /// A finite f64; NaN and the infinities read as `None`. + pub(crate) fn f64(&mut self) -> Option { + self.array().map(f64::from_le_bytes).filter(|v| v.is_finite()) + } + + pub(crate) fn fourcc(&mut self) -> Option<[u8; 4]> { + self.array() + } +} + +/// The u32 at `pos` of `b`. +pub(crate) fn u32_at(b: &[u8], pos: usize) -> Option { + Rd::at(b, pos).u32() +} diff --git a/crates/cdr/src/cmx.rs b/crates/cdr/src/cmx.rs new file mode 100644 index 0000000000..fc343a1870 --- /dev/null +++ b/crates/cdr/src/cmx.rs @@ -0,0 +1,651 @@ +//! Reader for `.cmx` exchange files with 32-bit coordinates: the RIFF form `CMX1` (R53), its +//! header (R54), the color, pen, line type, dash, outline and arrowhead tables (R55 to R59) and the +//! instructions of each page (R60): pages, layers, groups and curves (R61, R62) with uniform fills +//! and outlines (R63). Text, images, rectangles, ellipses, clipping paths, other fills and lenses +//! are left out with a warning. + +use crate::bytes::{Rd, u32_at}; +use crate::geometry::path_of; +use crate::layout::{self, Profile}; +use crate::limits::Budget; +use crate::model::{Cap, Color, Drawing, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Pt, Shape}; +use crate::records::{name, property_color}; +use crate::riff::{LIST, push}; +use crate::{Error, Warning}; + +const FORM: [u8; 4] = *b"CMX1"; +/// Meters per coordinate unit when the header gives no usable value: the 0.1 µm of every sample +/// file with 32-bit coordinates (R54). +const DEFAULT_UNIT: f64 = 1e-7; +/// How far past a chunk that runs short the next chunk id is looked for (R53). +const RESYNC: usize = 64; +/// The chunks the reader uses (R53 to R60). +const READ_IDS: [[u8; 4]; 9] = [*b"LIST", *b"cont", *b"page", *b"rclr", *b"rpen", *b"rott", *b"rdot", *b"rotl", *b"rota"]; +/// The most UTF-16 units read of a layer's name; [`name`] keeps 256 of them. +const MAX_NAME_UNITS: usize = 4096; + +// Instruction codes (R60). +const BEGIN_PAGE: i16 = 9; +const END_PAGE: i16 = 10; +const BEGIN_LAYER: i16 = 11; +const END_LAYER: i16 = 12; +const BEGIN_GROUP: i16 = 13; +const END_GROUP: i16 = 14; +const BEGIN_TEXT: i16 = 20; +const END_TEXT: i16 = 21; +const GLYPH_RUN: i16 = 65; +const ELLIPSE: i16 = 66; +const CURVE: i16 = 67; +const RECTANGLE: i16 = 68; +const IMAGE: i16 = 69; +const ADD_CLIP: i16 = 88; +const REMOVE_CLIP: i16 = 89; +const JUMP: i16 = 111; + +/// Does `bytes` start as a CMX file: a RIFF or RIFX form of type `CMX1` (R53)? +pub(crate) fn is_cmx(bytes: &[u8]) -> bool { + matches!(bytes.get(0..4), Some(b"RIFF" | b"RIFX")) && bytes.get(8..12) == Some(FORM.as_slice()) +} + +/// A chunk outside the `LIST` chunks: its id, its body and where the body starts in the file. +struct Chunk<'a> { + id: [u8; 4], + body: &'a [u8], + start: usize, +} + +/// The tables that page instructions refer to by 1-based index (R55 to R59). +#[derive(Default)] +struct Tables { + colors: Vec>, + /// Outline widths in points. + pens: Vec>, + /// Flags, and the caps and join. + line_types: Vec>, + dashes: Vec>, + /// Line type, screen, color, arrowheads, pen and dashes. + outlines: Vec>, + arrowheads: Vec<(u16, u16)>, +} + +pub(crate) fn drawing(bytes: &[u8], budget: &mut Budget) -> Result { + if !is_cmx(bytes) { + return Err(Error::NotCmx); + } + if bytes.get(0..4) == Some(b"RIFX") { + return Err(Error::Unsupported("big-endian CMX files")); + } + let mut warn = Vec::new(); + let chunks = chunks(bytes, budget, &mut warn)?; + let cont = chunks.iter().find(|c| c.id == *b"cont").map(|c| c.body).ok_or(Error::Damaged("CMX header"))?; + match cont.get(52) { + Some(b'4') => {} + Some(b'2') => return Err(Error::Unsupported("CMX files with 16-bit coordinates")), + _ => return Err(Error::Damaged("CMX header")), + } + let meters = Rd::at(cont, 64).f64().filter(|m| *m > 0.0 && *m <= 1.0).unwrap_or(DEFAULT_UNIT); + let unit = meters / 0.0254 * 72.0; + let tables = Tables::read(&chunks, unit, budget, &mut warn)?; + let mut pages = Vec::new(); + for c in chunks.iter().filter(|c| c.id == *b"page") { + pages.push(PageRead::new(&tables, unit, budget, &mut warn).read(c)?); + } + Ok(Drawing { version: 0, page_size: None, pages, master: Vec::new(), guides: Vec::new(), warnings: warn }) +} + +/// The chunks of the file in order, those inside `LIST` chunks in place (R53). +fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec) -> Result>, Error> { + let declared = u32_at(b, 4).and_then(|n| (n as usize).checked_add(8)).unwrap_or(b.len()); + if declared > b.len() { + // The file was cut short of the size its header gives. + push(warn, Warning::Damaged); + } + let end = declared.min(b.len()); + let mut out = Vec::new(); + // (position, end, depth) of the lists still to walk; a list's children go before the rest of + // the list that holds it. + let mut stack = vec![(12usize, end, 0usize)]; + while let Some((mut pos, end, depth)) = stack.pop() { + while pos.saturating_add(8) <= end { + let Some(id) = Rd::at(b, pos).fourcc() else { break }; + if !is_id(&id) { + match resync(b, pos, end) { + Some(next) => { + pos = next; + continue; + } + None => { + push(warn, Warning::Damaged); + break; + } + } + } + budget.take_chunk()?; + let size = u32_at(b, pos + 4).map_or(0, |s| s as usize); + let start = pos + 8; + let stop = start.saturating_add(size); + if stop > end { + // Stray bytes that happen to start with four letters give a length past the list: + // look for the next chunk id after them. A chunk the reader uses is kept, cut at + // the end of the list. + if !READ_IDS.contains(&id) + && let Some(next) = resync(b, pos, end) + { + pos = next; + continue; + } + push(warn, Warning::Damaged); + } + let stop = stop.min(end); + let next = stop.saturating_add(size & 1); + if id == LIST { + if depth >= budget.limits.depth { + push(warn, Warning::TooDeep); + pos = next; + continue; + } + stack.push((next, end, depth)); + stack.push((start + 4, stop, depth + 1)); + break; + } + if let Some(body) = b.get(start..stop) { + out.push(Chunk { id, body, start }); + } + pos = next; + } + } + Ok(out) +} + +/// Is `t` a chunk id: an ASCII letter, then three ASCII letters, digits or spaces (R53)? +fn is_id(t: &[u8]) -> bool { + matches!(t, [first, rest @ ..] if t.len() == 4 && first.is_ascii_alphabetic() && rest.iter().all(|c| c.is_ascii_alphanumeric() || *c == b' ')) +} + +/// Where the next chunk after `pos` lies: the first chunk id at an even distance of 2 to [`RESYNC`] +/// bytes that names a chunk the reader uses, or another chunk whose length keeps it inside the list +/// that ends at `end` (R53). +fn resync(b: &[u8], pos: usize, end: usize) -> Option { + let fits = |p: usize| u32_at(b, p + 4).and_then(|s| (p + 8).checked_add(s as usize)).is_some_and(|stop| stop <= end); + let chunk_at = |p: usize| Rd::at(b, p).fourcc().is_some_and(|id| is_id(&id) && (READ_IDS.contains(&id) || fits(p))); + (pos + 2..=pos.saturating_add(RESYNC).min(end.saturating_sub(8))).step_by(2).find(|&p| chunk_at(p)) +} + +/// The end of the field list at `pos` of `b`: after its 0xff, or the end of `b` when a field runs +/// past it (R55). +fn list_end(b: &[u8], mut pos: usize) -> usize { + while let Some(&tag) = b.get(pos) { + if tag == 0xff { + return pos + 1; + } + match Rd::at(b, pos + 1).u16().map(usize::from).filter(|n| *n >= 3) { + Some(n) if pos + n <= b.len() => pos += n, + _ => break, + } + } + b.len() +} + +/// The data of field `tag` in the field list `b` (R55). +fn field(b: &[u8], tag: u8) -> Option<&[u8]> { + let mut pos = 0; + while let Some(&t) = b.get(pos) { + if t == 0xff { + return None; + } + let n = usize::from(Rd::at(b, pos + 1).u16()?); + let data = b.get(pos + 3..pos.checked_add(n)?).filter(|_| n >= 3)?; + if t == tag { + return Some(data); + } + pos += n; + } + None +} + +/// The field lists of a table: a u16 count, then that many lists (R55). Each entry counts toward +/// the chunk limit. +fn entries<'a>(d: &'a [u8], budget: &mut Budget) -> Result, Error> { + let count = Rd::new(d).u16().map_or(0, usize::from); + let mut out = Vec::new(); + let mut pos = 2; + for _ in 0..count { + if pos >= d.len() { + break; + } + budget.take_chunk()?; + let end = list_end(d, pos); + out.push(d.get(pos..end).unwrap_or_default()); + pos = end; + } + Ok(out) +} + +impl Tables { + /// The first chunk of each table; a table that is missing is empty. + fn read(chunks: &[Chunk], unit: f64, budget: &mut Budget, warn: &mut Vec) -> Result { + let first = |id: &[u8; 4]| chunks.iter().find(|c| c.id == *id).map_or(&[][..], |c| c.body); + // A color record of field 10 holds a property list as a `.cdr` fill does (R56). + let record = layout::for_version(1300); + let mut t = Tables::default(); + for e in entries(first(b"rclr"), budget)? { + t.colors.push(color(e, record.as_ref(), warn)); + } + for e in entries(first(b"rpen"), budget)? { + t.pens.push(field(e, 1).and_then(|f| Rd::new(f).u32()).map(|w| f64::from(w) * unit)); + } + for e in entries(first(b"rott"), budget)? { + t.line_types.push(field(e, 1).and_then(|f| Some((*f.first()?, f.get(1).copied().unwrap_or(0))))); + } + for e in entries(first(b"rdot"), budget)? { + let mut r = Rd::new(field(e, 1).unwrap_or_default()); + let n = r.u16().map_or(0, usize::from); + t.dashes.push((0..n).map_while(|_| r.u16()).collect()); + } + for e in entries(first(b"rotl"), budget)? { + t.outlines.push(field(e, 1).and_then(|f| { + let mut r = Rd::new(f); + Some([r.u16()?, r.u16()?, r.u16()?, r.u16()?, r.u16()?, r.u16()?]) + })); + } + // Arrowhead pairs are plain u16 pairs after the count, not field lists (R59). + let mut r = Rd::new(first(b"rota")); + let n = r.u16().map_or(0, usize::from); + for _ in 0..n { + let Some(pair) = r.u16().zip(r.u16()) else { break }; + budget.take_chunk()?; + t.arrowheads.push(pair); + } + Ok(t) + } + + /// Entry `index` (1-based) of `list`, or `None` with a warning when there is none. + fn get(list: &[Option], index: u16, warn: &mut Vec) -> Option { + let found = usize::from(index).checked_sub(1).and_then(|i| list.get(i)).cloned().flatten(); + if found.is_none() { + push(warn, Warning::Damaged); + } + found + } + + fn color(&self, index: u16, warn: &mut Vec) -> Color { + Tables::get(&self.colors, index, warn).unwrap_or(Color::Rgb([0.0; 3])) + } + + /// The outline of `rotl` entry `index`, or `None` when its line type draws none (R57, R58). + fn outline(&self, index: u16, budget: &mut Budget, warn: &mut Vec) -> Option { + let [line, _screen, color, arrows, pen, dash] = Tables::get(&self.outlines, index, warn)?; + let (flags, caps_join) = Tables::get(&self.line_types, line, warn).unwrap_or((2, 0)); + if flags & 1 != 0 { + return None; + } + let width = Tables::get(&self.pens, pen, warn).unwrap_or(0.0); + let mut dashes = Vec::new(); + if flags & 4 != 0 { + let stored = usize::from(dash).checked_sub(1).and_then(|i| self.dashes.get(i)); + match stored { + // A pattern of zero lengths draws as a solid line, as in a `.cdr` outline (R48). + Some(d) if d.iter().all(|x| *x == 0) => {} + Some(d) if budget.take_dashes(d.len()) => dashes = d.iter().map(|x| f64::from(*x)).collect(), + Some(_) => push(warn, Warning::TooDeep), + None => push(warn, Warning::Damaged), + } + } + if usize::from(arrows).checked_sub(1).and_then(|i| self.arrowheads.get(i)).is_some_and(|(s, e)| *s != 0 || *e != 0) { + push(warn, Warning::Arrowheads); + } + Some(Outline { + width, + color: self.color(color, warn), + cap: match caps_join & 0x0f { + 1 => Cap::Round, + 2 => Cap::Square, + _ => Cap::Butt, + }, + join: match caps_join >> 4 { + 1 => Join::Round, + 2 => Join::Bevel, + _ => Join::Miter, + }, + dashes, + behind_fill: flags & 8 != 0, + scale_with: flags & 16 != 0, + }) + } +} + +/// A color entry (R56): the property list of field 10 when there is one, else the model and +/// palette bytes of field 1 and the values of field 2. Colors in other models read as black with a +/// warning. +fn color(e: &[u8], record: Option<&Profile>, warn: &mut Vec) -> Option { + if let (Some(f), Some(p)) = (field(e, 10), record) { + let mut r = Rd::new(f); + let len = r.u32()? as usize; + return property_color(r.bytes(len.min(r.left()))?, p, warn); + } + let model = *field(e, 1)?.first()?; + let v = field(e, 2)?; + let byte = |i: usize| v.get(i).map(|b| f32::from(*b)); + let pct = |i: usize| byte(i).map(|x| (x / 100.0).clamp(0.0, 1.0)); + let full = |i: usize| byte(i).map(|x| x / 255.0); + Some(match model { + 2 => Color::Cmyk([pct(0)?, pct(1)?, pct(2)?, pct(3)?]), + 3 => Color::Cmyk([full(0)?, full(1)?, full(2)?, full(3)?]), + 4 => Color::Cmyk([full(0)?, full(1)?, full(2)?, 0.0]), + 5 => Color::Rgb([full(0)?, full(1)?, full(2)?]), + 9 => Color::Gray(1.0 - full(0)?), + _ => { + push(warn, Warning::UnknownColors); + Color::Rgb([0.0; 3]) + } + }) +} + +/// The objects of one layer while it is read: the layer's own list, then one list for each group +/// left open. +struct LayerRead { + name: String, + lists: Vec>, +} + +impl LayerRead { + /// The layer, its open groups closed. Lists are drawn back to front (R60), and the model holds + /// them front to back. + fn finish(mut self) -> Layer { + while self.lists.len() > 1 { + close_group(&mut self.lists); + } + let mut objects = self.lists.pop().unwrap_or_default(); + objects.reverse(); + Layer { name: self.name, kind: LayerKind::Drawing, flags: Default::default(), objects, guides: Vec::new() } + } +} + +/// Close the innermost open group of `lists` into the one that holds it. +fn close_group(lists: &mut Vec>) { + if lists.len() < 2 { + return; + } + let mut objects = lists.pop().unwrap_or_default(); + objects.reverse(); + if let Some(top) = lists.last_mut() { + top.push(Object::Group { objects, flags: Default::default() }); + } +} + +/// The reading of one page chunk. +struct PageRead<'t, 'b> { + tables: &'t Tables, + unit: f64, + budget: &'b mut Budget, + warn: &'b mut Vec, + size: Option<(f64, f64)>, + /// The page's center in the file's coordinates when the page takes its size from the + /// drawing's bounds; points are moved by it so the art lies on the page. + center: (f64, f64), + layers: Vec, + open: Option, + /// Groups nested past the depth limit that are still open; their content is left out. + skipped: usize, +} + +impl<'t, 'b> PageRead<'t, 'b> { + fn new(tables: &'t Tables, unit: f64, budget: &'b mut Budget, warn: &'b mut Vec) -> Self { + PageRead { tables, unit, budget, warn, size: None, center: (0.0, 0.0), layers: Vec::new(), open: None, skipped: 0 } + } + + /// The instructions of a page chunk: a u16 size counting the whole instruction and an i16 code, + /// or 0xFFFF, a u32 size and the code; then the code's field lists (R60). + fn read(mut self, c: &Chunk) -> Result { + let d = c.body; + let mut pos = 0usize; + while pos.saturating_add(4) <= d.len() { + self.budget.take_chunk()?; + let mut r = Rd::at(d, pos); + let (size, code, head) = match r.u16() { + Some(0xFFFF) => match (r.u32(), r.i16()) { + (Some(size), Some(code)) => (size as usize, code, 8), + _ => break, + }, + Some(size) => match r.i16() { + Some(code) => (usize::from(size), code, 4), + None => break, + }, + None => break, + }; + if size < head { + push(self.warn, Warning::Damaged); + break; + } + let end = pos.saturating_add(size); + if end > d.len() { + push(self.warn, Warning::Damaged); + } + let body = d.get(pos + head..end.min(d.len())).unwrap_or_default(); + if code == JUMP { + // Field 1 is the file offset the instructions go on from; the bytes passed over + // hold the page's images (R60). + let target = field(body, 1).and_then(|f| Rd::new(f).u32()).and_then(|t| (t as usize).checked_sub(c.start)); + pos = target.filter(|t| *t >= end && *t <= d.len()).unwrap_or(end); + if pos > end { + push(self.warn, Warning::UnsupportedObjects); + } + continue; + } + self.instruction(code, body); + pos = end; + } + if pos < d.len() { + // An instruction whose head runs past the page was not read. + push(self.warn, Warning::Damaged); + } + self.close_layer(); + // A layer that holds nothing (the special layers every sample file lists empty) is left + // out. The file lists layers back to front. + let mut layers = self.layers; + layers.retain(|l| !l.objects.is_empty()); + layers.reverse(); + Ok(Page { size: self.size, layers }) + } + + fn instruction(&mut self, code: i16, body: &[u8]) { + match code { + BEGIN_PAGE => { + // Field 4: the page's width and height (R61). + let mut r = Rd::new(field(body, 4).unwrap_or_default()); + if let (Some(w), Some(h)) = (r.u32(), r.u32()) { + let (w, h) = (f64::from(w) * self.unit, f64::from(h) * self.unit); + self.size = (w > 0.0 && h > 0.0).then_some((w, h)); + } + if self.size.is_none() { + self.size_from_bounds(field(body, 1).unwrap_or_default()); + } + } + BEGIN_LAYER => { + self.close_layer(); + // A layer without a name is left unnamed, as in a `.cdr` drawing. + let name = self.layer_name(body).unwrap_or_default(); + self.open = Some(LayerRead { name, lists: vec![Vec::new()] }); + } + END_LAYER => self.close_layer(), + BEGIN_GROUP => { + let open = self.layer().lists.len(); + if self.skipped > 0 || open > self.budget.limits.depth { + self.skipped += 1; + push(self.warn, Warning::TooDeep); + } else if self.budget.take_object() { + self.layer().lists.push(Vec::new()); + } else { + // Past the object limit the group's content joins the group that holds it. + self.skipped += 1; + push(self.warn, Warning::TooDeep); + } + } + END_GROUP => { + if self.skipped > 0 { + self.skipped -= 1; + } else { + close_group(&mut self.layer().lists); + } + } + CURVE if self.skipped == 0 => { + if let Some(shape) = self.curve(body) { + if self.budget.take_object() { + if let Some(list) = self.layer().lists.last_mut() { + list.push(Object::Shape(Box::new(shape))); + } + } else { + push(self.warn, Warning::TooDeep); + } + } + } + BEGIN_TEXT | GLYPH_RUN | ELLIPSE | RECTANGLE | IMAGE | ADD_CLIP => push(self.warn, Warning::UnsupportedObjects), + // These and the other codes (text styles and characters, color contexts) draw nothing + // on their own. + END_PAGE | END_TEXT | REMOVE_CLIP => {} + _ => {} + } + } + + /// A page without a size of its own is sized to the drawing's bounds in field 1 (R61): a u16 + /// page number, a u32 of flags, then the left, top, right and bottom edges as i32 in + /// coordinate units. The page is centered on those bounds. + fn size_from_bounds(&mut self, f: &[u8]) { + let mut r = Rd::new(f); + if r.u16().is_none() || r.u32().is_none() { + return; + } + let (Some(l), Some(t), Some(rt), Some(b)) = (r.i32(), r.i32(), r.i32(), r.i32()) else { + return; + }; + let (l, t, rt, b) = (f64::from(l) * self.unit, f64::from(t) * self.unit, f64::from(rt) * self.unit, f64::from(b) * self.unit); + let (w, h) = ((rt - l).abs(), (t - b).abs()); + if w > 0.0 && h > 0.0 { + self.size = Some((w, h)); + self.center = ((l + rt) / 2.0, (t + b) / 2.0); + } + } + + /// The open layer, or a new unnamed one when objects come before any layer begins. + fn layer(&mut self) -> &mut LayerRead { + self.open.get_or_insert_with(|| LayerRead { name: String::new(), lists: vec![Vec::new()] }) + } + + fn close_layer(&mut self) { + self.skipped = 0; + if let Some(l) = self.open.take() { + self.layers.push(l.finish()); + } + } + + /// A layer's name: field 4 as a u32 count and UTF-16 units, else field 1 from byte 12 as a + /// u16 count and 8-bit characters (R62). + fn layer_name(&mut self, body: &[u8]) -> Option { + // A field 4 that can't be read leaves the name to field 1. + let wide = field(body, 4).and_then(|f| { + let mut r = Rd::new(f); + let n = (r.u32()? as usize).min(MAX_NAME_UNITS).min(r.left() / 2); + Some((r.bytes(n * 2)?, layout::for_version(1200)?)) + }); + if let Some((units, l)) = wide { + let s = name(units, &l, self.warn); + if !s.trim().is_empty() { + return Some(s); + } + } + let mut r = Rd::at(field(body, 1)?, 12); + let n = usize::from(r.u16()?).min(r.left()); + let s = name(r.bytes(n)?, &layout::for_version(1100)?, self.warn); + (!s.trim().is_empty()).then_some(s) + } + + /// A curve (R62): field 1 its rendering attributes, field 2 a u16 point count, the points (i32 + /// x and y) and one type byte for each. Points are from the page's center, y up. + fn curve(&mut self, body: &[u8]) -> Option { + let mut r = Rd::new(field(body, 2).unwrap_or_default()); + let Some(count) = r.u16().map(usize::from) else { + // A curve without its points is lost. + push(self.warn, Warning::Damaged); + return None; + }; + // `stored` points are read, so the type bytes are found after all of them, and the first + // `n`, those that have a type byte, are kept. When the field holds every point, a short + // field has lost type bytes. When it holds whole points and their types for fewer points, + // the count is too large. Otherwise the field lost points, and its type bytes can't be + // found: the curve is lost. + let left = r.left(); + let (stored, n) = match count.checked_mul(8).filter(|c| *c <= left) { + Some(c) => (count, count.min(left - c)), + None if left.is_multiple_of(9) => (left / 9, left / 9), + None => { + push(self.warn, Warning::Damaged); + return None; + } + }; + if n < count { + push(self.warn, Warning::Damaged); + } + if !self.budget.take_coordinates(stored) { + push(self.warn, Warning::TooDeep); + return None; + } + let mut points = Vec::with_capacity(stored); + for _ in 0..stored { + let (x, y) = (f64::from(r.i32()?) * self.unit, f64::from(r.i32()?) * self.unit); + points.push(Pt { x: x - self.center.0, y: y - self.center.1 }); + } + points.truncate(n); + let path = path_of(&points, r.bytes(n)?); + if path.subpaths.is_empty() { + return None; + } + let (fill, outline) = self.attributes(field(body, 1).unwrap_or_default()); + Some(Shape::new(Geometry::Path(path), Matrix::IDENTITY, fill, outline)) + } + + /// Rendering attributes (R63): a mask (1 fill, 2 outline, 4 lens), then a field list for the + /// fill and one for the outline when the mask names them. + fn attributes(&mut self, a: &[u8]) -> (Option, Option) { + let Some(&mask) = a.first() else { return (None, None) }; + let mut pos = 1; + let mut fill = None; + if mask & 1 != 0 { + let end = list_end(a, pos); + let list = a.get(pos..end).unwrap_or_default(); + pos = end; + // Field 1: the fill type (u16), then its own field list; type 1, uniform, names its + // color in field 1. + let v = field(list, 1).unwrap_or_default(); + match Rd::new(v).u16() { + Some(0) | None => {} + Some(1) => { + let index = field(v.get(2..).unwrap_or_default(), 1).and_then(|c| Rd::new(c).u16()); + fill = Some(match index { + Some(i) => self.tables.color(i, self.warn), + None => { + push(self.warn, Warning::Damaged); + Color::Rgb([0.0; 3]) + } + }); + } + Some(_) => push(self.warn, Warning::UnsupportedFills), + } + } + let mut outline = None; + if mask & 2 != 0 { + let list = a.get(pos..list_end(a, pos)).unwrap_or_default(); + match field(list, 1).and_then(|f| Rd::new(f).u16()) { + Some(i) => outline = self.tables.outline(i, self.budget, self.warn), + None => push(self.warn, Warning::Damaged), + } + } + if mask & 4 != 0 { + push(self.warn, Warning::Lenses); + } + // A canvas (8) or a container (16) is not read. + if mask & (8 | 16) != 0 { + push(self.warn, Warning::UnsupportedObjects); + } + (fill, outline) + } +} diff --git a/crates/cdr/src/geometry.rs b/crates/cdr/src/geometry.rs new file mode 100644 index 0000000000..61b776f23a --- /dev/null +++ b/crates/cdr/src/geometry.rs @@ -0,0 +1,455 @@ +//! The coordinates argument (30) of each object type read as geometry: curves (R16), rectangles +//! (R15), ellipses and arcs (R17) and polygons (R18). + +use std::f64::consts::PI; + +use crate::Warning; +use crate::bytes::Rd; +use crate::layout::Profile; +use crate::limits::Budget; +use crate::model::{Geometry, Path, Pt, Segment, SubPath}; +use crate::records::{angle, coord}; +use crate::riff::push; + +/// The most sides a polygon record may give (VectorCraft's own bound). +const MAX_POLYGON_SIDES: u32 = 1000; +/// The base curve of a polygon lies on a circle of 1000 mm (R18), in points. +const POLYGON_UNIT_RADIUS: f64 = 1000.0 / 25.4 * 72.0; + +/// What a point type byte asks for (R16): bits 7 and 6. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Op { + Move, + Line, + Curve, + Control, +} + +fn op(t: u8) -> Op { + match t >> 6 { + 0 => Op::Move, + 1 => Op::Line, + 2 => Op::Curve, + _ => Op::Control, + } +} + +/// Bit 3 closes the subpath (R16). +const CLOSES: u8 = 0x08; + +/// A point list (R16): the count, the points, then one type byte each. The count is a u32 from +/// version 6 and a u16 followed by another u16 before it (R39). It is held to what the bytes hold; +/// `None` when the points are past the budget. +pub(crate) fn point_list(b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option { + let mut r = Rd::new(b); + let count = if p.short { + let count = usize::from(r.u16()?); + r.skip(2)?; + count + } else { + r.u32()? as usize + }; + points(b, r, count, p, budget, warn) +} + +/// A path record (object type 0x25, R30): 4 bytes, two u16 counts whose sum is the point count, 16 +/// bytes, then the points and their type bytes as in a point list. +pub(crate) fn path_record(b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option { + let mut r = Rd::new(b); + r.skip(4)?; + let count = usize::from(r.u16()?) + usize::from(r.u16()?); + r.skip(16)?; + points(b, r, count, p, budget, warn) +} + +/// `count` points from `r` over `b`, then their type bytes. A list cut short is read two ways: as +/// all `count` points with the type bytes after them, and as the points and type bytes the bytes +/// hold split evenly. The reading that keeps more points with a type byte wins, the first on a tie. +fn points(b: &[u8], mut r: Rd, count: usize, p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option { + let each = 2 * p.word(); + let left = r.left(); + let split = (left / (each + 1)).min(count); + let whole = count.checked_mul(each).filter(|len| *len <= left).map(|len| (left - len).min(count)); + let stored = match whole { + Some(typed) if typed >= split => count, + _ => split, + }; + let types = b.get(r.pos() + stored * each..)?; + let n = stored.min(types.len()); + if count > n { + push(warn, Warning::Damaged); + } + if !budget.take_coordinates(n) { + push(warn, Warning::TooDeep); + return None; + } + let mut points = Vec::with_capacity(n); + for _ in 0..n { + points.push(Pt { x: coord(&mut r, p)?, y: coord(&mut r, p)? }); + } + Some(path_of(&points, types)) +} + +/// The subpaths that points and their type bytes draw. +pub(crate) fn path_of(points: &[Pt], types: &[u8]) -> Path { + let mut subpaths = Vec::new(); + let mut cur: Option = None; + // The last two control points: a curve end uses only those. + let mut controls: Vec = Vec::with_capacity(2); + for (&pt, &t) in points.iter().zip(types) { + let o = op(t); + if o == Op::Control { + if controls.len() == 2 { + controls.remove(0); + } + controls.push(pt); + continue; + } + if o == Op::Move || cur.is_none() { + subpaths.extend(cur.take()); + cur = Some(SubPath { start: pt, segments: Vec::new(), closed: t & CLOSES != 0 && o == Op::Move }); + controls.clear(); + if o == Op::Move { + continue; + } + } + let Some(sp) = cur.as_mut() else { continue }; + let seg = match (o, controls.as_slice()) { + (Op::Curve, [c1, c2]) => Segment::Cubic(*c1, *c2, pt), + _ => Segment::Line(pt), + }; + controls.clear(); + sp.segments.push(seg); + if t & CLOSES != 0 { + sp.closed = true; + } + } + subpaths.extend(cur); + // A closed subpath with no segments, or an open one with none, draws nothing. + subpaths.retain(|s| !s.segments.is_empty()); + Path { subpaths } +} + +/// A rectangle record (R15): width, height, then one corner radius for every corner, four from +/// version 9. +pub(crate) fn rect(b: &[u8], p: &Profile) -> Option { + if p.f64_rect { + return rect_f64(b, p); + } + let mut r = Rd::new(b); + let (w, h) = (coord(&mut r, p)?, coord(&mut r, p)?); + let first = coord(&mut r, p)?.abs(); + let mut radii = [first; 4]; + if p.four_radii { + for slot in radii.iter_mut().skip(1) { + *slot = coord(&mut r, p)?.abs(); + } + } + Some(Geometry::Rect { w, h, radii }) +} + +/// A rectangle record from version 15 (R29): width and height as f64 coordinate units, two scale +/// factors that repeat the transform's (not applied), the scale-with flag and 7 bytes, then the +/// four radii as f64 16 bytes apart. With the flag clear each radius is a share of half the shorter +/// side; with it set the radius is in inches. A corner is held to half the shorter side, and +/// sizes to the range of the 32-bit coordinates of earlier versions. +fn rect_f64(b: &[u8], p: &Profile) -> Option { + let mut r = Rd::new(b); + let size = |v: f64| (v.abs() <= f64::from(i32::MAX)).then(|| v * p.unit()); + let (w, h) = (size(r.f64()?)?, size(r.f64()?)?); + r.skip(8 + 8)?; + let inches = r.u8()? != 0; + r.skip(7)?; + let short = w.abs().min(h.abs()); + let mut radii = [0.0; 4]; + for (k, slot) in radii.iter_mut().enumerate() { + if k > 0 { + r.skip(16)?; + } + let v = r.f64()?.abs(); + let radius = if inches { v * 72.0 } else { v * short / 2.0 }; + *slot = radius.min(short / 2.0); + } + Some(Geometry::Rect { w, h, radii }) +} + +/// An ellipse record (R17): the box's width and height, the start and end angles and whether +/// the arc closes through the centre. Equal angles make a whole ellipse. +pub(crate) fn ellipse(b: &[u8], p: &Profile) -> Option { + let mut r = Rd::new(b); + let (w, h) = (coord(&mut r, p)?, coord(&mut r, p)?); + let (a1, a2) = (angle(&mut r, p)?, angle(&mut r, p)?); + let pie = if p.short { r.u16()? != 0 } else { r.u32()? != 0 }; + let sweep = (a2 - a1).rem_euclid(360.0); + if sweep.abs() < 1e-9 { + return Some(Geometry::Ellipse { w, h }); + } + Some(Geometry::Path(arc(w, h, a1, sweep, pie))) +} + +/// The arc of the ellipse in the box from the origin to (`w`, `h`), from `start` degrees through +/// `sweep` degrees, in the ellipse's own axes; a pie runs from the centre and closes there. The +/// radii are half the size, and a negative width or height points its axis the other way (R17), so +/// with a negative height 0 to 180 degrees is the half below the centre. +fn arc(w: f64, h: f64, start: f64, sweep: f64, pie: bool) -> Path { + let (cx, cy, rx, ry) = (w / 2.0, h / 2.0, w / 2.0, h / 2.0); + let at = |t: f64| Pt { x: cx + rx * t.cos(), y: cy + ry * t.sin() }; + let tangent = |t: f64| Pt { x: -rx * t.sin(), y: ry * t.cos() }; + let pieces = (sweep / 90.0).ceil().max(1.0) as usize; + let step = sweep.to_radians() / pieces as f64; + let k = 4.0 / 3.0 * (step / 4.0).tan(); + let t0 = start.to_radians(); + let mut segments = Vec::with_capacity(pieces + 2); + if pie { + segments.push(Segment::Line(at(t0))); + } + for i in 0..pieces { + let (a, b) = (t0 + step * i as f64, t0 + step * (i + 1) as f64); + let (p0, p1, d0, d1) = (at(a), at(b), tangent(a), tangent(b)); + segments.push(Segment::Cubic(Pt { x: p0.x + k * d0.x, y: p0.y + k * d0.y }, Pt { x: p1.x - k * d1.x, y: p1.y - k * d1.y }, p1)); + } + let start = if pie { Pt { x: cx, y: cy } } else { at(t0) }; + Path { subpaths: vec![SubPath { start, segments, closed: pie }] } +} + +/// A polygon (R18): its base curve, one side of the outline on a circle of 1000 mm with its top +/// vertex first, copied once per side and turned clockwise each time by the vertices the side +/// spans, then scaled by (`rx`, `ry`) and moved to the centre the polygon argument (11000) gives. +/// A star whose sides skip vertices draws as one outline, or as several when the side count and +/// the step share a factor. +pub(crate) fn polygon(base: &Path, b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option { + let mut r = Rd::new(b); + if !p.tagged { + r.skip(4)?; + } + let sides = r.u32()?; + // The next point: the first field, or the second when the first is 0 or 1. + let (first, second) = (r.u32()?, r.u32()?); + let next = if first > 1 { first } else { second }; + if p.tagged { + r.skip(4)?; + } + let (rx, ry) = (r.f64()?, r.f64()?); + let (cx, cy) = (coord(&mut r, p)?, coord(&mut r, p)?); + let side = base.subpaths.first()?; + if !(1..=MAX_POLYGON_SIDES).contains(&sides) { + push(warn, Warning::Damaged); + return None; + } + if !budget.take_coordinates(side.segments.len().saturating_mul(3).saturating_mul(sides as usize)) { + push(warn, Warning::TooDeep); + return None; + } + // The base curve's own unit radius, measured from its first point, keeps the scale right + // whatever unit the file's coordinates are in. + let unit = side.start.x.hypot(side.start.y); + let unit = if unit > 0.0 { unit } else { POLYGON_UNIT_RADIUS }; + let place = |q: Pt, turn: f64| { + let (s, c) = turn.sin_cos(); + let (x, y) = (q.x * c - q.y * s, q.x * s + q.y * c); + Pt { x: x / unit * POLYGON_UNIT_RADIUS * rx + cx, y: y / unit * POLYGON_UNIT_RADIUS * ry + cy } + }; + let step = side_step(side, sides, next); + let outlines = gcd(sides, step); + let each = sides / outlines; + let angle = |k: u32| -2.0 * PI * f64::from(k % sides) / f64::from(sides); + let mut subpaths = Vec::with_capacity(outlines as usize); + for o in 0..outlines { + let mut segments = Vec::with_capacity(side.segments.len() * each as usize); + for j in 0..each { + let turn = angle(o + j * step); + segments.extend(side.segments.iter().map(|s| match *s { + Segment::Line(a) => Segment::Line(place(a, turn)), + Segment::Cubic(a, b, c) => Segment::Cubic(place(a, turn), place(b, turn), place(c, turn)), + })); + } + subpaths.push(SubPath { start: place(side.start, angle(o)), segments, closed: true }); + } + Some(Geometry::Path(Path { subpaths })) +} + +/// How many vertices the base side moves on from its first point (R18): the vertex its last +/// point lies at, clockwise; else the next-point field when it names one; else 1. +fn side_step(side: &SubPath, sides: u32, next: u32) -> u32 { + let field = if (1..sides).contains(&next) { next } else { 1 }; + let Some(end) = side.segments.last().map(|s| match *s { + Segment::Line(e) | Segment::Cubic(_, _, e) => e, + }) else { + return field; + }; + let (r0, r1) = (side.start.x.hypot(side.start.y), end.x.hypot(end.y)); + if !(r0 > 0.0 && (r1 - r0).abs() <= r0 * 1e-3) { + return field; + } + let turned = (side.start.y.atan2(side.start.x) - end.y.atan2(end.x)) / (2.0 * PI / f64::from(sides)); + let k = turned.round(); + if !k.is_finite() || (turned - k).abs() > 1e-3 { + return field; + } + match k.rem_euclid(f64::from(sides)) as u32 { + 0 => field, + k => k, + } +} + +fn gcd(a: u32, b: u32) -> u32 { + let (mut a, mut b) = (a, b); + while b != 0 { + (a, b) = (b, a % b); + } + a.max(1) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn pt(x: f64, y: f64) -> Pt { + Pt { x, y } + } + + #[test] + fn type_bytes_make_moves_lines_curves_and_closes() { + let points = [pt(0.0, 0.0), pt(10.0, 0.0), pt(10.0, 5.0), pt(5.0, 10.0), pt(0.0, 10.0), pt(20.0, 20.0), pt(30.0, 20.0)]; + // move (closed), line, control, control, curve end closing; move, line. + let types = [0x08, 0x40, 0xC0, 0xC0, 0x88, 0x00, 0x40]; + let path = path_of(&points, &types); + assert_eq!(path.subpaths.len(), 2); + let first = &path.subpaths[0]; + assert!(first.closed); + assert_eq!(first.segments, vec![Segment::Line(pt(10.0, 0.0)), Segment::Cubic(pt(10.0, 5.0), pt(5.0, 10.0), pt(0.0, 10.0))]); + assert!(!path.subpaths[1].closed); + } + + #[test] + fn a_point_list_short_of_type_bytes_reads_them_after_all_its_points() { + let p = crate::layout::for_version(1300).unwrap_or_else(|| panic!("profile")); + // Three points, (0, 0), (1 inch, 0) and (0, 0), and type bytes for the first two only. + let mut b = 3u32.to_le_bytes().to_vec(); + for v in [0i32, 0, 254_000, 0, 0, 0] { + b.extend(v.to_le_bytes()); + } + b.extend([0x00, 0x40]); + let mut warn = vec![]; + let path = point_list(&b, &p, &mut Budget::new(crate::Limits::default()), &mut warn).unwrap_or_else(|| panic!("path")); + assert_eq!(path.subpaths.len(), 1); + assert_eq!(path.subpaths[0].segments, vec![Segment::Line(pt(72.0, 0.0))]); + assert_eq!(warn, vec![Warning::Damaged]); + // A count past the points the bytes hold keeps the points that have a type byte. + // Eight points and their eight type bytes take the bytes of nine points. + let mut b = 9u32.to_le_bytes().to_vec(); + for i in 0..8 { + b.extend((i * 254_000i32).to_le_bytes()); + b.extend(0i32.to_le_bytes()); + } + b.extend([0x00, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40]); + let mut warn = vec![]; + let path = point_list(&b, &p, &mut Budget::new(crate::Limits::default()), &mut warn).unwrap_or_else(|| panic!("path")); + assert_eq!(path.subpaths[0].segments.len(), 7); + assert!(matches!(path.subpaths[0].segments[6], Segment::Line(end) if (end.x - 504.0).abs() < 1e-9 && end.y == 0.0)); + assert_eq!(warn, vec![Warning::Damaged]); + } + + #[test] + fn a_run_of_control_points_keeps_the_last_two() { + let points: Vec = (0..7).map(|i| pt(f64::from(i), 0.0)).collect(); + let path = path_of(&points, &[0x00, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0x80]); + assert_eq!(path.subpaths[0].segments, vec![Segment::Cubic(pt(4.0, 0.0), pt(5.0, 0.0), pt(6.0, 0.0))]); + } + + #[test] + fn a_curve_end_without_two_controls_is_a_line() { + let path = path_of(&[pt(0.0, 0.0), pt(1.0, 1.0)], &[0x00, 0x80]); + assert_eq!(path.subpaths[0].segments, vec![Segment::Line(pt(1.0, 1.0))]); + } + + #[test] + fn a_quarter_arc_ends_on_the_ellipse() { + let p = arc(20.0, 10.0, 0.0, 90.0, false); + let sp = &p.subpaths[0]; + assert_eq!(sp.start, pt(20.0, 5.0)); + let Some(Segment::Cubic(_, _, end)) = sp.segments.last() else { panic!("no curve") }; + assert!((end.x - 10.0).abs() < 1e-9 && (end.y - 10.0).abs() < 1e-9); + let pie = arc(20.0, 10.0, 0.0, 180.0, true); + assert!(pie.subpaths[0].closed && pie.subpaths[0].start == pt(10.0, 5.0)); + } + + #[test] + fn a_negative_height_turns_the_arc_below_the_centre() { + let p = arc(20.0, -10.0, 0.0, 180.0, false); + let sp = &p.subpaths[0]; + assert_eq!(sp.start, pt(20.0, -5.0)); + let Some(Segment::Cubic(_, _, mid)) = sp.segments.first() else { panic!("no curve") }; + assert!((mid.x - 10.0).abs() < 1e-9 && (mid.y + 10.0).abs() < 1e-9, "{mid:?}"); + } + + /// A version 13 polygon argument: `sides`, the two next-point fields, then rx = ry = 1 at the + /// origin. + fn polygon_arg(sides: u32, first: u32, second: u32) -> Vec { + let mut b = Vec::new(); + for v in [sides, first, second, 0] { + b.extend(v.to_le_bytes()); + } + b.extend(1.0f64.to_le_bytes()); + b.extend(1.0f64.to_le_bytes()); + b.extend([0; 8]); + b + } + + /// Vertex `k` of `sides`, counted clockwise from the top, on the base circle. + fn vertex(k: u32, sides: u32) -> Pt { + let a = PI / 2.0 - 2.0 * PI * f64::from(k) / f64::from(sides); + pt(POLYGON_UNIT_RADIUS * a.cos(), POLYGON_UNIT_RADIUS * a.sin()) + } + + fn ends(sp: &SubPath) -> Vec { + sp.segments + .iter() + .map(|s| match *s { + Segment::Line(e) | Segment::Cubic(_, _, e) => e, + }) + .collect() + } + + fn close(a: &[Pt], b: &[Pt]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(p, q)| (p.x - q.x).abs() < 1e-6 && (p.y - q.y).abs() < 1e-6) + } + + fn star(sides: u32, step: u32, first: u32, second: u32) -> Path { + let p = crate::layout::for_version(1300).unwrap(); + let base = Path { subpaths: vec![SubPath { start: vertex(0, sides), segments: vec![Segment::Line(vertex(step, sides))], closed: false }] }; + let mut budget = Budget::new(crate::Limits::default()); + let Some(Geometry::Path(path)) = polygon(&base, &polygon_arg(sides, first, second), &p, &mut budget, &mut vec![]) else { + panic!("no polygon") + }; + path + } + + #[test] + fn a_star_whose_sides_skip_a_vertex_chains_its_points() { + // {5/2}: each side runs two vertices on, so the outline visits 2, 4, 1, 3 and 0. + let path = star(5, 2, 2, 0); + assert_eq!(path.subpaths.len(), 1); + let want: Vec = [2, 4, 1, 3, 0].iter().map(|&k| vertex(k, 5)).collect(); + assert!(close(&ends(&path.subpaths[0]), &want), "{:?}", ends(&path.subpaths[0])); + // The base side alone tells the step when the field doesn't. + assert!(close(&ends(&star(5, 2, 0, 0).subpaths[0]), &want)); + } + + #[test] + fn a_star_sharing_a_factor_with_its_sides_draws_one_outline_for_each() { + // {6/2}: two triangles, 0-2-4 and 1-3-5. + let path = star(6, 2, 0, 2); + assert_eq!(path.subpaths.len(), 2); + assert!(close(&ends(&path.subpaths[0]), &[vertex(2, 6), vertex(4, 6), vertex(0, 6)])); + assert!(close(&[path.subpaths[1].start], &[vertex(1, 6)])); + assert!(close(&ends(&path.subpaths[1]), &[vertex(3, 6), vertex(5, 6), vertex(1, 6)])); + } + + #[test] + fn a_plain_polygon_turns_one_vertex_for_each_side() { + let path = star(4, 1, 0, 1); + assert_eq!(path.subpaths.len(), 1); + assert!(close(&ends(&path.subpaths[0]), &[1, 2, 3, 0].map(|k| vertex(k, 4)))); + } +} diff --git a/crates/cdr/src/inline.rs b/crates/cdr/src/inline.rs new file mode 100644 index 0000000000..3d5214f136 --- /dev/null +++ b/crates/cdr/src/inline.rs @@ -0,0 +1,230 @@ +//! What a version 3 object holds as arguments where later versions name records: its transforms +//! (argument 100, R33), its fill (argument 20, R34) and its outline (argument 10, R35). + +use crate::bytes::Rd; +use crate::layout::Profile; +use crate::model::{Cap, Color, Join, Matrix, Outline}; +use crate::records::{self, angle, coord}; +use crate::riff::push; +use crate::{Limits, Warning}; + +/// Transform entry types (R33): a matrix, and an envelope. +const MATRIX: u16 = 0x8c; +const ENVELOPE: u16 = 0x14; +/// The bytes of one transform entry (R33). +const ENTRY: usize = 10; +/// The bytes an outline keeps for its dashes, one byte each (R35). +const DASH_AREA: usize = 10; + +/// The transforms of one object or group. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Placement { + /// The matrices composed in file order, in points. + pub(crate) matrix: Matrix, + /// An envelope bends the shape. The reader doesn't apply envelopes. + pub(crate) envelope: bool, +} + +/// The transforms argument (R33): a u16, the entry count, then 10-byte entries of a type and, at +/// byte 6, where the entry's data starts in the argument. The count is held to the entries the +/// argument holds and to the arguments a record may have. Entries of other types are passed over. +pub(crate) fn transforms(b: &[u8], p: &Profile, limits: &Limits, warn: &mut Vec) -> Option { + let mut r = Rd::new(b); + r.skip(2)?; + let stored = usize::from(r.u16()?); + let count = stored.min(r.left() / ENTRY).min(limits.arguments); + if count < stored { + push(warn, Warning::Damaged); + } + let mut out = Placement { matrix: Matrix::IDENTITY, envelope: false }; + for _ in 0..count { + let mut e = Rd::new(r.bytes(ENTRY)?); + let kind = e.u16()?; + e.skip(4)?; + let at = usize::from(e.u16()?); + match kind { + MATRIX => out.matrix = records::fixed_matrix(&mut Rd::at(b, at), p.unit())?.after(&out.matrix), + ENVELOPE => out.envelope = true, + _ => {} + } + } + Some(out) +} + +/// The fill argument (R34): a type byte, 0 for none and 1 for a uniform fill with its color. Fills +/// of other types read as none with a warning. The outer `None` is an argument that can't be read. +pub(crate) fn fill(b: &[u8], p: &Profile, warn: &mut Vec) -> Option> { + let mut r = Rd::new(b); + match r.u8()? { + 0 => Some(None), + 1 => Some(Some(records::color(&mut r, p, warn)?)), + _ => { + push(warn, Warning::UnsupportedFills); + Some(None) + } + } +} + +/// The outline argument (R35): a flags byte whose bit 0 is set when the object is outlined, the +/// width, the stretch, the nib angle, the color, 7 bytes, the dash count and 10 bytes that hold the +/// dashes, the join and the caps (u16 each), then the two arrowhead ids. An argument that ends +/// after its color gives a solid line with butt caps and miter joins. The outer `None` is an +/// argument that can't be read. +pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec) -> Option> { + let mut r = Rd::new(b); + if r.u8()? & 1 == 0 { + return Some(None); + } + let width = coord(&mut r, p)?.abs(); + let _stretch = r.u16()?; + let _nib = angle(&mut r, p)?; + let color = records::color(&mut r, p, warn)?; + let mut out = Outline { width, color, cap: Cap::Butt, join: Join::Miter, dashes: Vec::new(), behind_fill: false, scale_with: false }; + let Some(stored) = r.skip(7).and_then(|()| r.u8()).map(usize::from) else { return Some(Some(out)) }; + let Some(area) = r.bytes(DASH_AREA) else { return Some(Some(out)) }; + if stored > DASH_AREA { + push(warn, Warning::Damaged); + } + let dashes: Vec = area.iter().take(stored).map(|d| f64::from(*d)).collect(); + if dashes.iter().any(|d| *d > 0.0) { + out.dashes = dashes; + } + out.join = match r.u16() { + Some(1) => Join::Round, + Some(2) => Join::Bevel, + _ => Join::Miter, + }; + out.cap = match r.u16() { + Some(1) => Cap::Round, + Some(2) => Cap::Square, + _ => Cap::Butt, + }; + if matches!((r.u32(), r.u32()), (Some(s), Some(e)) if s != 0 || e != 0) { + push(warn, Warning::Arrowheads); + } + Some(Some(out)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn p3() -> Profile { + crate::layout::for_version(300).unwrap() + } + + /// A transforms argument of `entries` (type, data offset), then `data` from byte 4 + 10 for + /// each entry. + fn arg(count: u16, entries: &[(u16, u16)], data: &[i32]) -> Vec { + let mut b = vec![0, 0]; + b.extend(count.to_le_bytes()); + for (kind, at) in entries { + b.extend(kind.to_le_bytes()); + b.extend([0; 4]); + b.extend(at.to_le_bytes()); + b.extend([0; 2]); + } + b.extend(data.iter().flat_map(|v| v.to_le_bytes())); + b + } + + #[test] + fn matrices_compose_in_file_order_and_other_entries_are_passed_over() { + // Scale by 2, then move 1 inch right: entry types 0x8c, an unknown one and 0x8c. + let scale = [131072, 0, 0, 0, 131072, 0]; + let shift = [65536, 0, 1000, 0, 65536, 0]; + let b = arg(3, &[(MATRIX, 34), (0x99, 0), (MATRIX, 58)], &[scale, shift].concat()); + let mut w = vec![]; + let t = transforms(&b, &p3(), &Limits::default(), &mut w).unwrap(); + assert_eq!((t.matrix, t.envelope), (Matrix([2.0, 0.0, 0.0, 2.0, 72.0, 0.0]), false)); + assert!(w.is_empty()); + let b = arg(2, &[(MATRIX, 24), (ENVELOPE, 0)], &scale); + assert!(transforms(&b, &p3(), &Limits::default(), &mut vec![]).unwrap().envelope); + } + + #[test] + fn hostile_transform_arguments_do_not_read_past_their_bytes() { + let scale = [131072, 0, 0, 0, 131072, 0]; + // A count of 65,535 over one entry reads that entry, with the damage warning. + let b = arg(u16::MAX, &[(MATRIX, 14)], &scale); + let mut w = vec![]; + assert_eq!(transforms(&b, &p3(), &Limits::default(), &mut w).unwrap().matrix.0[0], 2.0); + assert_eq!(w, vec![Warning::Damaged]); + // A data offset past the argument, and one that leaves less than a matrix. + for at in [5000, 14 + 4] { + assert!(transforms(&arg(1, &[(MATRIX, at)], &scale), &p3(), &Limits::default(), &mut vec![]).is_none(), "{at}"); + } + // More entries than a record may have arguments. + let many: Vec<(u16, u16)> = vec![(0x99, 0); 100]; + let limits = Limits { arguments: 8, ..Limits::default() }; + let mut w = vec![]; + assert!(transforms(&arg(100, &many, &[]), &p3(), &limits, &mut w).is_some()); + assert_eq!(w, vec![Warning::Damaged]); + for len in 0..4 { + assert!(transforms(&b[..len], &p3(), &Limits::default(), &mut vec![]).is_none()); + } + } + + /// An outline argument: flags, width in 1/1000 inch, black, `dashes`, join, caps, arrowheads. + fn outline_arg(flags: u8, count: u8, dashes: &[u8], join: u16, cap: u16, heads: [u32; 2]) -> Vec { + let mut b = vec![flags]; + b.extend(28i16.to_le_bytes()); + b.extend([100, 0, 0, 0]); + b.extend([1, 0, 0, 0, 100]); + b.extend([0; 7]); + b.push(count); + let mut area = dashes.to_vec(); + area.resize(DASH_AREA, 0); + b.extend(area); + b.extend(join.to_le_bytes()); + b.extend(cap.to_le_bytes()); + b.extend(heads.iter().flat_map(|h| h.to_le_bytes())); + b + } + + #[test] + fn an_outline_reads_its_width_color_dashes_join_and_caps() { + let mut w = vec![]; + let o = outline(&outline_arg(1, 2, &[3, 1], 1, 2, [0, 0]), &p3(), &mut w).unwrap().unwrap(); + assert!((o.width - 2.016).abs() < 1e-9, "{}", o.width); + assert_eq!((o.color, o.join, o.cap, o.dashes), (Color::Cmyk([0.0, 0.0, 0.0, 1.0]), Join::Round, Cap::Square, vec![3.0, 1.0])); + assert!(w.is_empty()); + // Bit 0 clear: no outline, whatever follows. + assert_eq!(outline(&outline_arg(0, 2, &[3, 1], 1, 2, [7, 0]), &p3(), &mut w), Some(None)); + assert_eq!(outline(&[0], &p3(), &mut w), Some(None)); + assert!(w.is_empty()); + outline(&outline_arg(1, 0, &[], 0, 0, [0, 9]), &p3(), &mut w).unwrap().unwrap(); + assert_eq!(w, vec![Warning::Arrowheads]); + } + + #[test] + fn a_dash_count_past_the_dash_bytes_is_held_to_them() { + let mut w = vec![]; + let o = outline(&outline_arg(1, 255, &[2; 10], 0, 0, [0, 0]), &p3(), &mut w).unwrap().unwrap(); + assert_eq!(o.dashes.len(), DASH_AREA); + assert_eq!(w, vec![Warning::Damaged]); + // An argument that ends inside the dashes keeps a solid line; one cut before the color is + // unreadable. + let full = outline_arg(1, 255, &[2; 10], 0, 0, [0, 0]); + assert_eq!(outline(&full[..25], &p3(), &mut vec![]).unwrap().unwrap().dashes, Vec::::new()); + assert_eq!(outline(&full[..12], &p3(), &mut vec![]).unwrap().unwrap().cap, Cap::Butt); + for len in 0..12 { + assert!(outline(&full[..len], &p3(), &mut vec![]).is_none(), "{len}"); + } + } + + #[test] + fn fills_read_none_uniform_and_other_types() { + let mut w = vec![]; + assert_eq!(fill(&[0], &p3(), &mut w), Some(None)); + assert_eq!(fill(&[1, 1, 100, 0, 0, 0], &p3(), &mut w), Some(Some(Color::Cmyk([1.0, 0.0, 0.0, 0.0])))); + assert!(w.is_empty()); + for kind in [2, 4, 6, 7, 10] { + let mut w = vec![]; + assert_eq!(fill(&[kind, 0, 0], &p3(), &mut w), Some(None)); + assert_eq!(w, vec![Warning::UnsupportedFills], "{kind}"); + } + assert_eq!(fill(&[], &p3(), &mut w), None); + assert_eq!(fill(&[1, 1, 100], &p3(), &mut w), None); + } +} diff --git a/crates/cdr/src/layout.rs b/crates/cdr/src/layout.rs new file mode 100644 index 0000000000..46c28496cf --- /dev/null +++ b/crates/cdr/src/layout.rs @@ -0,0 +1,181 @@ +//! Where the fields of each record lie, by version: one table, resolved once per file. Each field +//! names the `PROVENANCE.md` row it rests on. + +/// The layouts of one range of versions. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Profile { + /// Coordinates are i16 in 1/1000 inch, record headers, counts and angles 16-bit (R5, R6, R7). + pub(crate) short: bool, + /// Bytes before the page size in `mcfg` (R10). + pub(crate) mcfg_skip: usize, + /// Bytes before a `trfd` entry's type (R8). + pub(crate) trfd_head: usize, + /// Bytes between a matrix entry's type and its six numbers (R8). + pub(crate) matrix_skip: usize, + /// Fill and outline records start with tagged records (R11, R12). + pub(crate) tagged: bool, + /// Outline: bytes after the join, after the stretch, after the nib angle and after the color + /// (R12). + pub(crate) outl_after_join: usize, + pub(crate) outl_after_stretch: usize, + pub(crate) outl_after_angle: usize, + pub(crate) outl_after_color: usize, + /// Where the start marker id lies after the first dash (R13); `None` where no source says. + pub(crate) marker_after_dash: Option, + /// Rectangles carry four corner radii, not one (R15). + pub(crate) four_radii: bool, + /// Rectangles are f64 sizes with radii as shares of half the shorter side (R29). + pub(crate) f64_rect: bool, + /// The master page flags its guides and desktop layers the way of versions 7 to 13 (R19). + pub(crate) old_master_flags: bool, + /// Object type 0x25 is a path (R30). + pub(crate) paths: bool, + /// Names are UTF-16LE, not Windows-1252 (R9). + pub(crate) utf16_names: bool, + /// An object holds its transform, fill and outline as arguments; there are no `trfd`, `fill` + /// or `outl` records (R33, R34, R35). + pub(crate) inline_styles: bool, + /// Object types count from 0: rectangle 0, ellipse 1, curve 2, text 3, bitmap 4 (R32). + pub(crate) types_from_zero: bool, + /// How a color is laid out (R14, R36). + pub(crate) color: ColorLayout, + /// A matrix is six i32 with its factors in 16.16 fixed point, not six f64 (R37). + pub(crate) fixed_matrix: bool, + /// `mcfg` holds 2 bytes and the page's two corners, not its width and height (R38). + pub(crate) mcfg_corners: bool, +} + +/// The layouts of a color. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ColorLayout { + /// A model byte and four value bytes (R36). + Bytes5, + /// A model u16, four u16 values and 2 bytes (R36). + Words12, + /// A model u16, a palette u16, 4 bytes and four value bytes (R14). + Record12, +} + +const fn profile(from: u16) -> Profile { + let short = from < 600; + Profile { + short, + inline_styles: from < 400, + types_from_zero: from < 400, + color: if from < 400 { + ColorLayout::Bytes5 + } else if from < 500 { + ColorLayout::Words12 + } else { + ColorLayout::Record12 + }, + fixed_matrix: from < 500, + mcfg_corners: from < 400, + mcfg_skip: if from >= 1300 { + 12 + } else if from >= 900 { + 4 + } else if from >= 600 && from < 700 { + 28 + } else { + 0 + }, + trfd_head: if from >= 1300 { 8 } else { 0 }, + matrix_skip: if short { 0 } else { 6 }, + tagged: from >= 1300, + outl_after_join: if from >= 600 && from < 1300 { 2 } else { 0 }, + outl_after_stretch: if short { 0 } else { 2 }, + outl_after_angle: if from >= 1300 { + 46 + } else if !short { + 52 + } else { + 0 + }, + outl_after_color: if short { 10 } else { 16 }, + marker_after_dash: if from >= 1300 { + Some(20) + } else if from >= 600 { + Some(22) + } else { + None + }, + four_radii: from >= 900, + f64_rect: from >= 1500, + old_master_flags: from < 1400, + paths: from >= 1000, + utf16_names: from >= 1200, + } +} + +/// The newest version read: 27, as the `vrsn` chunk names it (R1, R2). +pub(crate) const NEWEST: u16 = 2799; + +/// The first version of each range, with its layouts. Ranges start where a field moves. +const PROFILES: &[(u16, Profile)] = &[ + (300, profile(300)), + (400, profile(400)), + (500, profile(500)), + (600, profile(600)), + (700, profile(700)), + (800, profile(800)), + (900, profile(900)), + (1000, profile(1000)), + (1100, profile(1100)), + (1200, profile(1200)), + (1300, profile(1300)), + (1400, profile(1400)), + (1500, profile(1500)), + (1600, profile(1600)), +]; + +/// The oldest version of a RIFF file read: 3 (R31). Versions 1 and 2 are not RIFF files (`wl.rs`). +pub(crate) const OLDEST_RIFF: u16 = 300; + +/// The layouts of the RIFF file of `version` (hundreds; 801 is the 8.01 variant, 2430 is 24.3), or +/// `None` outside 3 to 27. +pub(crate) fn for_version(version: u16) -> Option { + if !(OLDEST_RIFF..=NEWEST).contains(&version) { + return None; + } + PROFILES.iter().rev().find(|(from, _)| *from <= version).map(|(_, p)| *p) +} + +impl Profile { + /// Points per coordinate unit. + pub(crate) fn unit(&self) -> f64 { + if self.short { 72.0 / 1000.0 } else { 72.0 / 254_000.0 } + } + + /// Bytes of a coordinate, and of header fields and counts. + pub(crate) fn word(&self) -> usize { + if self.short { 2 } else { 4 } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_version_from_3_to_27_has_one_profile() { + assert!(for_version(299).is_none() && for_version(2800).is_none()); + assert!(for_version(300).is_some_and(|p| p.short && p.inline_styles && p.types_from_zero && p.mcfg_corners && p.fixed_matrix)); + assert!(for_version(399).is_some_and(|p| p.color == ColorLayout::Bytes5)); + assert!(for_version(400).is_some_and(|p| p.short && !p.inline_styles && !p.mcfg_corners && p.fixed_matrix)); + assert!(for_version(499).is_some_and(|p| p.color == ColorLayout::Words12)); + assert!(for_version(500).is_some_and(|p| !p.fixed_matrix && !p.types_from_zero && p.color == ColorLayout::Record12)); + assert!(for_version(1300).is_some_and(|p| p.old_master_flags)); + assert!(for_version(1400).is_some_and(|p| p.tagged && !p.f64_rect && !p.old_master_flags)); + assert!(for_version(1500).is_some_and(|p| p.tagged && p.f64_rect && p.mcfg_skip == 12 && p.paths)); + assert!(for_version(2430).is_some_and(|p| p.f64_rect && p.paths && p.utf16_names)); + assert!(for_version(500).is_some_and(|p| p.short && p.mcfg_skip == 0 && p.marker_after_dash.is_none())); + assert!(for_version(600).is_some_and(|p| !p.short && p.mcfg_skip == 28 && p.marker_after_dash == Some(22))); + assert!(for_version(801).is_some_and(|p| p.mcfg_skip == 0 && p.marker_after_dash == Some(22))); + assert!(for_version(999).is_some_and(|p| !p.paths && p.marker_after_dash == Some(22))); + assert!(for_version(1000).is_some_and(|p| p.mcfg_skip == 4 && p.four_radii && !p.utf16_names && p.paths)); + assert!(for_version(1300).is_some_and(|p| p.tagged && p.trfd_head == 8 && p.outl_after_angle == 46)); + // The table is in order, so the search finds each range's own row. + assert!(PROFILES.windows(2).all(|w| w[0].0 < w[1].0)); + } +} diff --git a/crates/cdr/src/lib.rs b/crates/cdr/src/lib.rs new file mode 100644 index 0000000000..64cdae512a --- /dev/null +++ b/crates/cdr/src/lib.rs @@ -0,0 +1,110 @@ +//! Reader for `.cdr` drawings of versions 1 to 27 (`.cdr`, and `.cdt` templates): the `WL` files +//! of versions 1 and 2, the RIFF chunk tree of versions 3 on with its compressed lists, the ZIP +//! packages of versions 14 on with their data streams, then pages, layers, guidelines, groups, +//! curves, rectangles, ellipses, arcs and polygons with uniform fills and outlines. It also reads +//! `.cmx` exchange files with 32-bit coordinates ([`read_cmx`]): their pages, layers, groups and +//! curves with uniform fills and outlines. +//! +//! Every record layout the reader relies on is listed in `PROVENANCE.md` with its public source +//! and status; code cites the row ids (R1 ...). Reading is bounded by [`Limits`], never recurses and does not +//! panic. Nothing here writes `.cdr` or `.cmx` files. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +use std::fmt; + +mod build; +mod bytes; +mod cmx; +mod geometry; +mod inline; +mod layout; +mod limits; +pub mod model; +mod package; +mod records; +mod riff; +mod styles; +#[cfg(any(test, feature = "synth"))] +pub mod synth; +#[cfg(any(test, feature = "synth"))] +pub mod synth_cmx; +mod wl; +mod zip; + +pub use limits::Limits; +pub use model::{Drawing, Warning}; + +/// Does `bytes` look like a `.cdr` drawing: a RIFF file, a ZIP package holding one, or a `WL` file +/// of version 1 or 2 whose header offsets fit the file? +pub fn is_cdr(bytes: &[u8]) -> bool { + riff::is_cdr_riff(bytes) || package::is_package(bytes) || wl::is_wl(bytes) +} + +/// Does `bytes` start as a `.cmx` exchange file: a RIFF form (or its big-endian RIFX form) of type +/// `CMX1`? +pub fn is_cmx(bytes: &[u8]) -> bool { + cmx::is_cmx(bytes) +} + +/// Why a file can't be read. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Error { + /// Not a `.cdr` drawing. + NotCdr, + /// Not a `.cmx` file. + NotCmx, + /// A drawing of a version this reader doesn't read (hundreds: 2800 is version 28). + Version(u16), + /// A container structure that doesn't parse. + Damaged(&'static str), + /// Past one of the [`Limits`]. + Limit(&'static str), + /// A file this reader doesn't open: an encrypted, ZIP64 or split package, or a RIFF file that + /// names a version before 3; a big-endian `.cmx` file or one with 16-bit coordinates. + Unsupported(&'static str), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::NotCdr => write!(f, "not a CDR drawing"), + Error::NotCmx => write!(f, "not a CMX file"), + Error::Version(v) => write!(f, "version {} drawings are not read", v / 100), + Error::Damaged(what) => write!(f, "damaged {what}"), + Error::Limit(what) => write!(f, "past the {what} limit"), + Error::Unsupported(what) => write!(f, "{what} are not read"), + } + } +} + +impl std::error::Error for Error {} + +/// Read a drawing within `limits`. +pub fn read(bytes: &[u8], limits: Limits) -> Result { + if bytes.len() > limits.input { + return Err(Error::Limit("input size")); + } + let mut budget = limits::Budget::new(limits); + // Versions 1 and 2 are not RIFF files (R40). + if wl::is_wl(bytes) { + return wl::drawing(bytes, &mut budget); + } + let mut warnings = Vec::new(); + // Versions 14 on save a ZIP package around the RIFF stream (R24, R25, R26). + let (stream, streams) = if zip::is_zip(bytes) { package::open(bytes, &mut budget)? } else { (std::borrow::Cow::Borrowed(bytes), None) }; + let ix = riff::Index::build(&stream, streams, &mut budget, &mut warnings)?; + let mut drawing = build::drawing(&ix, &mut budget, &mut warnings)?; + ix.stream_warnings(&mut drawing.warnings); + Ok(drawing) +} + +/// Read a `.cmx` exchange file within `limits`. Files in big-endian byte order and files with +/// 16-bit coordinates are refused with [`Error::Unsupported`]. Its [`Drawing::version`] is 0. +pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result { + if bytes.len() > limits.input { + return Err(Error::Limit("input size")); + } + let mut budget = limits::Budget::new(limits); + cmx::drawing(bytes, &mut budget) +} diff --git a/crates/cdr/src/limits.rs b/crates/cdr/src/limits.rs new file mode 100644 index 0000000000..684029c014 --- /dev/null +++ b/crates/cdr/src/limits.rs @@ -0,0 +1,166 @@ +//! What one read may take. The values are VectorCraft's own; wasm32 gets half the memory limits. + +use crate::Error; + +/// The most a read may take, checked before every allocation and descent. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Limits { + /// Bytes of input. + pub input: usize, + /// Bytes inflated from compressed lists and package members, all of one file together. + pub inflated: usize, + /// Bytes of one package member. + pub member: usize, + /// Members of a package. + pub members: usize, + /// Nested lists below the file's own. Deeper content is left out with a warning. + pub depth: usize, + /// Chunks in the index, nested ones included, and the entries and styles of the style table; + /// in a `.cmx` file, its chunks, table entries and page instructions. + pub chunks: usize, + /// Objects mapped (shapes, groups and guidelines). + pub objects: usize, + /// Points of all curves together. + pub coordinates: usize, + /// Arguments of one `loda` record. + pub arguments: usize, + /// Dashes of all outlines together, an outline's counted again for every shape that uses it. + /// Past them a shape's outline is solid, with a warning. + pub dashes: usize, + /// Chunks walked inside clipped groups, all containers together, a group's counted again for + /// every container that names it. Past them a container's group is left out, with a warning. + pub clipped_chunks: usize, +} + +#[cfg(not(target_arch = "wasm32"))] +const MIB: usize = 1 << 20; + +impl Default for Limits { + #[cfg(not(target_arch = "wasm32"))] + fn default() -> Self { + Limits { + input: 512 * MIB, + inflated: 1024 * MIB, + member: 512 * MIB, + members: 4096, + depth: 256, + chunks: 2_000_000, + objects: 1_000_000, + coordinates: 16_000_000, + arguments: 64, + dashes: 16_000_000, + clipped_chunks: 2_000_000, + } + } + + #[cfg(target_arch = "wasm32")] + fn default() -> Self { + Limits { + input: 256 << 20, + inflated: 512 << 20, + member: 256 << 20, + members: 4096, + depth: 256, + chunks: 2_000_000, + objects: 1_000_000, + coordinates: 16_000_000, + arguments: 64, + dashes: 8_000_000, + clipped_chunks: 2_000_000, + } + } +} + +/// The running counters of one read against its [`Limits`]. +#[derive(Debug)] +pub(crate) struct Budget { + pub(crate) limits: Limits, + inflated: usize, + chunks: usize, + objects: usize, + coordinates: usize, + dashes: usize, + clipped_chunks: usize, + /// A request for coordinates was refused since [`Budget::coordinates_refused`] last asked. + refused: bool, +} + +impl Budget { + pub(crate) fn new(limits: Limits) -> Self { + Budget { limits, inflated: 0, chunks: 0, objects: 0, coordinates: 0, dashes: 0, clipped_chunks: 0, refused: false } + } + + /// Whether a request for coordinates was refused since the last call, which tells a shape + /// left out at the limit from one whose bytes don't parse. + pub(crate) fn coordinates_refused(&mut self) -> bool { + std::mem::take(&mut self.refused) + } + + /// Bytes an inflate may still produce. + pub(crate) fn inflate_left(&self) -> usize { + self.limits.inflated.saturating_sub(self.inflated) + } + + pub(crate) fn take_inflated(&mut self, n: usize) -> Result<(), Error> { + self.inflated = self.inflated.checked_add(n).filter(|&t| t <= self.limits.inflated).ok_or(Error::Limit("inflated size"))?; + Ok(()) + } + + pub(crate) fn take_chunk(&mut self) -> Result<(), Error> { + self.take_chunks(1) + } + + /// `n` more chunks or style table entries. + pub(crate) fn take_chunks(&mut self, n: usize) -> Result<(), Error> { + self.chunks = self.chunks.saturating_add(n); + if self.chunks > self.limits.chunks { Err(Error::Limit("chunk count")) } else { Ok(()) } + } + + /// One more object, or `false` when the drawing already holds as many as a read maps. + pub(crate) fn take_object(&mut self) -> bool { + if self.objects >= self.limits.objects { + return false; + } + self.objects += 1; + true + } + + /// `n` more curve points, or `false` past the limit (nothing is taken then). + pub(crate) fn take_coordinates(&mut self, n: usize) -> bool { + match self.coordinates.checked_add(n).filter(|&t| t <= self.limits.coordinates) { + Some(t) => { + self.coordinates = t; + true + } + None => { + self.refused = true; + false + } + } + } + + /// Dashes the read may still take. + pub(crate) fn dashes_left(&self) -> usize { + self.limits.dashes.saturating_sub(self.dashes) + } + + /// `n` more dashes, or `false` past the limit (nothing is taken then). + pub(crate) fn take_dashes(&mut self, n: usize) -> bool { + match self.dashes.checked_add(n).filter(|&t| t <= self.limits.dashes) { + Some(t) => { + self.dashes = t; + true + } + None => false, + } + } + + /// One more chunk walked inside a clipped group, or `false` past the limit. + pub(crate) fn take_clipped_chunk(&mut self) -> bool { + if self.clipped_chunks >= self.limits.clipped_chunks { + return false; + } + self.clipped_chunks += 1; + true + } +} diff --git a/crates/cdr/src/model.rs b/crates/cdr/src/model.rs new file mode 100644 index 0000000000..e4af34f365 --- /dev/null +++ b/crates/cdr/src/model.rs @@ -0,0 +1,255 @@ +//! What a drawing reads as. Lengths are in points (1/72 inch), from the centre of the page, with y +//! pointing up, as the file stores them. + +/// A point in points. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Pt { + pub x: f64, + pub y: f64, +} + +/// An affine map `[a, b, c, d, e, f]`: x' = a x + c y + e, y' = b x + d y + f. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Matrix(pub [f64; 6]); + +impl Matrix { + pub const IDENTITY: Matrix = Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]); + + /// `self` after `first`: the map that applies `first`, then `self`. + pub fn after(&self, first: &Matrix) -> Matrix { + let [a, b, c, d, e, f] = self.0; + let [p, q, r, s, t, u] = first.0; + Matrix([a * p + c * q, b * p + d * q, a * r + c * s, b * r + d * s, a * t + c * u + e, b * t + d * u + f]) + } + + pub fn apply(&self, p: Pt) -> Pt { + let [a, b, c, d, e, f] = self.0; + Pt { x: a * p.x + c * p.y + e, y: b * p.x + d * p.y + f } + } +} + +/// One segment after the previous point. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Segment { + Line(Pt), + /// Two control points, then the end point. + Cubic(Pt, Pt, Pt), +} + +#[derive(Clone, Debug, PartialEq)] +pub struct SubPath { + pub start: Pt, + pub segments: Vec, + pub closed: bool, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Path { + pub subpaths: Vec, +} + +/// The shape of an object, in its own space ([`Shape::matrix`] places it). +#[derive(Clone, Debug, PartialEq)] +pub enum Geometry { + Path(Path), + /// A rectangle from the origin to (`w`, `h`) (either may be negative). `radii` round its + /// corners counterclockwise from the one at (`w`, 0): (`w`, 0), (`w`, `h`), (0, `h`), (0, 0). + Rect { + w: f64, + h: f64, + radii: [f64; 4], + }, + /// A whole ellipse in the box from the origin to (`w`, `h`). + Ellipse { + w: f64, + h: f64, + }, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Color { + Rgb([f32; 3]), + Cmyk([f32; 4]), + /// Ink: 0 is white, 1 black. + Gray(f32), + /// Every ink at full strength. + Registration, + /// A color of a named library, printed on its own plate. `look` is its full-strength color + /// when the file stores one (an approximation in sRGB); `tint` is 0 to 1. + Spot { + name: String, + tint: f32, + look: Option<[f32; 3]>, + }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Cap { + Butt, + Round, + Square, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Join { + Miter, + Round, + Bevel, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Outline { + pub width: f64, + pub color: Color, + pub cap: Cap, + pub join: Join, + /// Dash and gap lengths, in outline widths; empty for a solid line. + pub dashes: Vec, + /// Drawn behind the fill, so that a filled shape shows only the outer half of it. + pub behind_fill: bool, + /// Scaled with the shape: the shape's matrix scales the width and dashes as it scales the + /// geometry. + pub scale_with: bool, +} + +/// Whether a layer, group or shape is hidden or locked. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Flags { + pub hidden: bool, + pub locked: bool, +} + +/// How a shape's colors combine with the art below it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Blend { + #[default] + Normal, + Multiply, + Screen, + Overlay, + SoftLight, + HardLight, + ColorDodge, + ColorBurn, + Darken, + Lighten, + Difference, + Exclusion, + Hue, + Saturation, + Color, + Luminosity, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Shape { + pub geometry: Geometry, + pub matrix: Matrix, + pub fill: Option, + pub outline: Option, + /// The fill covers every area its subpaths wind around (nonzero); otherwise subpaths that + /// overlap leave holes (even-odd). + pub nonzero: bool, + /// 1 opaque, 0 clear. + pub opacity: f32, + pub blend: Blend, + pub flags: Flags, +} + +impl Shape { + /// An opaque, shown shape filled even-odd. + pub fn new(geometry: Geometry, matrix: Matrix, fill: Option, outline: Option) -> Shape { + Shape { geometry, matrix, fill, outline, nonzero: false, opacity: 1.0, blend: Blend::Normal, flags: Flags::default() } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Object { + Shape(Box), + Group { + objects: Vec, + flags: Flags, + }, + /// A clipping container and the objects it clips: `objects` (front to back) show only + /// inside the container's shape, with its fill behind them and its outline over them. + Clip { + container: Box, + objects: Vec, + }, +} + +/// A guideline through `at`, at `angle` degrees counterclockwise from horizontal. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Guideline { + pub at: Pt, + pub angle: f64, + /// The guideline, a group around it or its layer is hidden. + pub hidden: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LayerKind { + Drawing, + /// The objects left beside the pages. + Desktop, + Guides, + Grid, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Layer { + pub name: String, + pub kind: LayerKind, + pub flags: Flags, + /// Front to back, as the file lists them. + pub objects: Vec, + pub guides: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Page { + /// Width and height in points, when the page gives its own. + pub size: Option<(f64, f64)>, + /// Front to back, as the file lists them. + pub layers: Vec, +} + +/// What was left out or changed while reading. Each kind is listed once. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Warning { + /// Text, bitmaps, splines and other objects not read yet. + UnsupportedObjects, + /// Fountain, pattern, texture and PostScript fills. + UnsupportedFills, + /// Colors in models not read; shown black. + UnknownColors, + /// Library spot colors whose look the file doesn't store; shown black. + SpotLooks, + /// Outline arrowheads. + Arrowheads, + /// Envelopes, which are not applied: the shapes under them keep their outlines. + Envelopes, + /// Lenses, and object transparency that isn't read, which are not applied: the objects show + /// opaque. + Lenses, + /// Content nested deeper, or past the counts, that a read takes. + TooDeep, + /// Chunks or records that end early or don't parse. + Damaged, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Drawing { + /// In hundreds, as a RIFF file stores it: 300 to 2799. A file of version 1 or 2 stores no + /// number: it gives 200 when its marker byte is the one of version 2, and 100 otherwise. A + /// `.cmx` file gives 0. + pub version: u16, + /// Page size from the document settings, in points. + pub page_size: Option<(f64, f64)>, + pub pages: Vec, + /// Layers every page shows, from the master page. + pub master: Vec, + /// Guidelines every page shows, kept outside any layer. + pub guides: Vec, + pub warnings: Vec, +} diff --git a/crates/cdr/src/package.rs b/crates/cdr/src/package.rs new file mode 100644 index 0000000000..c46fa31e39 --- /dev/null +++ b/crates/cdr/src/package.rs @@ -0,0 +1,147 @@ +//! The packages of versions 14 on (R25, R26): a ZIP archive holding the RIFF stream as +//! `content/riffData.cdr` (14 and 15), or as `content/root.dat` with its chunk bodies in the data +//! streams that `content/dataFileList.dat` names (16 on). A data stream is inflated only when a +//! chunk the reader reads, or a list it splits, points into it. + +use std::borrow::Cow; +use std::cell::{Cell, OnceCell}; + +use crate::limits::{Budget, Limits}; +use crate::riff::push; +use crate::zip::{self, Archive}; +use crate::{Error, Warning}; + +const RIFF_DATA: &[u8] = b"content/riffData.cdr"; +const ROOT: &[u8] = b"content/root.dat"; +const DATA_FILE_LIST: &[u8] = b"content/dataFileList.dat"; +const DATA_DIR: &[u8] = b"content/data/"; + +/// Is `bytes` a ZIP archive with a `.cdr` drawing's root stream? +pub(crate) fn is_package(bytes: &[u8]) -> bool { + zip::is_zip(bytes) && Archive::open(bytes, Limits::default().members).is_ok_and(|a| a.find(RIFF_DATA).or_else(|| a.find(ROOT)).is_some()) +} + +/// The RIFF stream of the package `bytes`, and its data streams when it has them (16 on). +pub(crate) fn open<'a>(bytes: &'a [u8], budget: &mut Budget) -> Result<(Cow<'a, [u8]>, Option>), Error> { + let zip = Archive::open(bytes, budget.limits.members)?; + if let Some(i) = zip.find(RIFF_DATA) { + return Ok((member(&zip, i, budget)?, None)); + } + let root = zip.find(ROOT).ok_or(Error::NotCdr)?; + let root = member(&zip, root, budget)?; + let list = match zip.find(DATA_FILE_LIST) { + Some(i) => member(&zip, i, budget)?, + None => Cow::Borrowed(&[][..]), + }; + // One name for each line; a line feed after the last name ends it. + let list = list.strip_suffix(b"\n").unwrap_or(&list); + let mut members = Vec::new(); + if !list.is_empty() { + for line in list.split(|&b| b == b'\n') { + if members.len() == budget.limits.members { + return Err(Error::Limit("package member count")); + } + let name = line.strip_suffix(b"\r").unwrap_or(line); + let found = zip.find(&[DATA_DIR, name].concat()); + // A data stream that is encrypted or packed some other way refuses the file, as the + // root stream does. + if let Some(i) = found { + zip.check(i)?; + } + members.push(found); + } + } + let loaded = (0..zip.count()).map(|_| OnceCell::new()).collect(); + let streams = Streams { zip, members, loaded, member_limit: budget.limits.member, damaged: Cell::new(false) }; + Ok((root, Some(streams))) +} + +/// Member `i` within the member limit and, when deflated, what is left to inflate. +fn member<'a>(zip: &Archive<'a>, i: usize, budget: &mut Budget) -> Result, Error> { + let m = zip.read(i, budget.limits.member, budget.inflate_left())?; + if let Cow::Owned(v) = &m { + budget.take_inflated(v.len())?; + } + Ok(m) +} + +/// What reading one package member gave. +#[derive(Debug)] +enum Slot<'a> { + Read(Cow<'a, [u8]>), + Damaged, + PastLimit, +} + +/// The data streams of a version 16+ package, in `dataFileList.dat` order (R26). +#[derive(Debug)] +pub(crate) struct Streams<'a> { + zip: Archive<'a>, + /// The member holding each stream; `None` when the archive lacks it. + members: Vec>, + /// Each member's bytes once read, so that streams naming one member read it once. + loaded: Vec>>, + member_limit: usize, + /// A stream, or a chunk's bytes in one, could not be found. + damaged: Cell, +} + +impl<'a> Streams<'a> { + /// The member holding stream `s`; `None` when there is no such stream. + pub(crate) fn member_of(&self, s: usize) -> Option { + *self.members.get(s)? + } + + /// The size the archive gives stream `s`; `None` when there is no such stream. + pub(crate) fn size(&self, s: usize) -> Option { + Some(self.zip.size(self.member_of(s)?)) + } + + /// Stream `s`, its member read on first use within the member limit and, when deflated, + /// within `left` more inflated bytes (which it takes from). + pub(crate) fn get(&self, s: usize, left: &Cell) -> Option<&[u8]> { + let Some(i) = self.member_of(s) else { + self.damaged.set(true); + return None; + }; + let slot = self.loaded.get(i)?.get_or_init(|| { + let read = self.zip.read(i, self.member_limit, left.get()); + if !matches!(read, Err(Error::Limit(_))) { + left.set(left.get().saturating_sub(self.zip.inflate_cost(i))); + } + match read { + Ok(b) => Slot::Read(b), + Err(Error::Limit(_)) => Slot::PastLimit, + Err(_) => { + self.damaged.set(true); + Slot::Damaged + } + } + }); + match slot { + Slot::Read(b) => Some(b.as_ref()), + Slot::Damaged | Slot::PastLimit => None, + } + } + + /// Was stream `s` left out because it is past a limit? Chunks in it are then not damage. + pub(crate) fn past_limit(&self, s: usize) -> bool { + let slot = self.member_of(s).and_then(|i| self.loaded.get(i)).and_then(OnceCell::get); + matches!(slot, Some(Slot::PastLimit)) + } + + /// Mark a chunk whose stream bytes could not be found. + pub(crate) fn note_damage(&self) { + self.damaged.set(true); + } + + /// The warnings for streams that were left out. + pub(crate) fn warnings(&self, warn: &mut Vec) { + if self.damaged.get() { + push(warn, Warning::Damaged); + } + if self.loaded.iter().any(|s| matches!(s.get(), Some(Slot::PastLimit))) { + push(warn, Warning::TooDeep); + } + } +} diff --git a/crates/cdr/src/records.rs b/crates/cdr/src/records.rs new file mode 100644 index 0000000000..f4f2a3b6ef --- /dev/null +++ b/crates/cdr/src/records.rs @@ -0,0 +1,655 @@ +//! Hand-written decoders of the records a drawing's objects refer to: the `loda` argument table +//! (R6), transforms (R8), colors (R14), fills (R11) and outlines (R12, R13). + +use crate::bytes::Rd; +use crate::layout::{ColorLayout, Profile}; +use crate::model::{Blend, Cap, Color, Join, Matrix, Outline}; +use crate::riff::push; +use crate::{Limits, Warning}; + +/// The tag of a record's current layout in tagged files (R11, R12). +const TAG_1300: u32 = 1300; +/// The most tagged records skipped before a fill's own (R11). +const MAX_SKIPPED: usize = 4; +/// The most records skipped before an outline's own (R12). +const MAX_OUTLINE_RECORDS: usize = 16; +/// The most UTF-16 units of a library color's name kept, and the most bytes or UTF-16 units of +/// a layer's. +const MAX_NAME: usize = 256; + +/// A header field: u16 in short files, u32 otherwise. +fn word(r: &mut Rd, p: &Profile) -> Option { + if p.short { r.u16().map(usize::from) } else { r.u32().map(|v| v as usize) } +} + +/// A coordinate in points. +pub(crate) fn coord(r: &mut Rd, p: &Profile) -> Option { + let raw = if p.short { f64::from(r.i16()?) } else { f64::from(r.i32()?) }; + Some(raw * p.unit()) +} + +/// An angle in degrees: tenths in short files, millionths otherwise (R7). +pub(crate) fn angle(r: &mut Rd, p: &Profile) -> Option { + if p.short { Some(f64::from(r.i16()?) / 10.0) } else { Some(f64::from(r.i32()?) / 1_000_000.0) } +} + +/// A `loda` record (R6): its object type and arguments as (type, bytes). +pub(crate) struct Loda<'a> { + pub(crate) kind: u32, + pub(crate) args: Vec<(u32, &'a [u8])>, +} + +impl<'a> Loda<'a> { + pub(crate) fn arg(&self, kind: u32) -> Option<&'a [u8]> { + self.args.iter().find(|(k, _)| *k == kind).map(|(_, b)| *b) + } +} + +pub(crate) fn loda<'a>(b: &'a [u8], p: &Profile, limits: &Limits, warn: &mut Vec) -> Option> { + let mut r = Rd::new(b); + let (_len, count, offsets_at, types_at, kind) = (word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?); + // The types table is indexed from the stored count, however many arguments are read. + let stored = count; + let count = if count > limits.arguments { + push(warn, Warning::Damaged); + limits.arguments + } else { + count + }; + let mut offsets = Vec::with_capacity(count + 1); + let mut ro = Rd::at(b, offsets_at); + for _ in 0..=count { + offsets.push(word(&mut ro, p)?); + } + let mut args = Vec::with_capacity(count); + for i in 0..count { + // The types table runs the other way: offset i pairs with type stored - 1 - i. + let kind = word(&mut Rd::at(b, types_at.checked_add((stored - 1 - i).checked_mul(p.word())?)?), p)? as u32; + let (start, end) = (*offsets.get(i)?, *offsets.get(i + 1)?); + match b.get(start..end) { + Some(body) => args.push((kind, body)), + None => push(warn, Warning::Damaged), + } + } + Some(Loda { kind: kind as u32, args }) +} + +/// The matrices of a `trfd` record composed in file order, in points (R8). Each entry ends where +/// the next offset points, and the last at the offset after it (R51); an entry too short for its +/// matrix makes the record unreadable. +pub(crate) fn trfd(b: &[u8], p: &Profile) -> Option { + let mut r = Rd::new(b); + let (_len, count, offsets_at) = (word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?); + let mut m = Matrix::IDENTITY; + let k = p.unit(); + // Each entry takes at least its offset's bytes, which bounds the count by the record's size. + for i in 0..count.min(b.len() / p.word()) { + let slot = offsets_at.checked_add(i.checked_mul(p.word())?)?; + let start = word(&mut Rd::at(b, slot), p)?; + // A table that stops before the last entry's end offset leaves that entry the rest of the + // record. + let end = word(&mut Rd::at(b, slot.checked_add(p.word())?), p).unwrap_or(b.len()); + let mut e = Rd::at(b.get(start..end)?, p.trfd_head); + if e.u16()? != 8 { + continue; + } + e.skip(p.matrix_skip)?; + let next = if p.fixed_matrix { + fixed_matrix(&mut e, k)? + } else { + let (a, c, tx, bb, d, ty) = (e.f64()?, e.f64()?, e.f64()?, e.f64()?, e.f64()?, e.f64()?); + Matrix([a, bb, c, d, tx * k, ty * k]) + }; + m = next.after(&m); + } + Some(m) +} + +/// A number in 16.16 fixed point. +pub(crate) fn fixed(r: &mut Rd) -> Option { + Some(f64::from(r.i32()?) / 65536.0) +} + +/// A matrix of versions 3 and 4 (R37): six i32 `a c tx b d ty`, the factors in 16.16 fixed point +/// and `tx` and `ty` in coordinate units of `k` points. +pub(crate) fn fixed_matrix(r: &mut Rd, k: f64) -> Option { + let (a, c, tx) = (fixed(r)?, fixed(r)?, f64::from(r.i32()?)); + let (b, d, ty) = (fixed(r)?, fixed(r)?, f64::from(r.i32()?)); + Some(Matrix([a, b, c, d, tx * k, ty * k])) +} + +/// A color in the layout of the file's version (R14, R36). Unknown models read as black with a +/// warning. +pub(crate) fn color(r: &mut Rd, p: &Profile, warn: &mut Vec) -> Option { + match p.color { + ColorLayout::Record12 => { + let model = r.u16()?; + let palette = r.u16()?; + r.skip(4)?; + let v: [u8; 4] = r.bytes(4)?.try_into().ok()?; + Some(model_color(model, palette, v, warn)) + } + ColorLayout::Words12 => { + let model = r.u16()?; + let w = [r.u16()?, r.u16()?, r.u16()?, r.u16()?]; + r.skip(2)?; + // The models take 8-bit values, as in the other layouts; a larger value reads as 255. + Some(early_color(model, w.map(|x| u8::try_from(x).unwrap_or(u8::MAX)), w[0], w[1], warn)) + } + ColorLayout::Bytes5 => Some(color5(r.bytes(5)?.try_into().ok()?, warn)), + } +} + +/// A 5-byte color (R36): a model byte and four value bytes. +pub(crate) fn color5(b: [u8; 5], warn: &mut Vec) -> Color { + let [model, v @ ..] = b; + early_color(u16::from(model), v, u16::from_le_bytes([v[0], v[1]]), u16::from_le_bytes([v[2], v[3]]), warn) +} + +/// A color of versions 1 to 4 (R36). Model 1 is CMYK in percent. Model 0 is a numbered ink and +/// its tint in percent: 0 is black, 1 is white, and other numbers are inks of a library the file +/// doesn't store. Other models read as in later versions. +fn early_color(model: u16, v: [u8; 4], index: u16, tint: u16, warn: &mut Vec) -> Color { + let pct = |x: f32| (x / 100.0).clamp(0.0, 1.0); + match (model, index) { + (1, _) => Color::Cmyk(v.map(|x| pct(f32::from(x)))), + (0, 0) => Color::Gray(pct(f32::from(tint))), + (0, 1) => Color::Gray(0.0), + (0, number) => { + push(warn, Warning::SpotLooks); + Color::Spot { name: format!("Spot 0:{number}"), tint: pct(f32::from(tint)), look: None } + } + _ => model_color(model, 0, v, warn), + } +} + +/// The color of `model` with the four value bytes `v`, from version 5 (R14). +fn model_color(model: u16, palette: u16, v: [u8; 4], warn: &mut Vec) -> Color { + let (v0, v1, v2, v3) = (f32::from(v[0]), f32::from(v[1]), f32::from(v[2]), f32::from(v[3])); + let pct = |x: f32| (x / 100.0).clamp(0.0, 1.0); + let byte = |x: f32| x / 255.0; + match model { + 2 => Color::Cmyk([pct(v0), pct(v1), pct(v2), pct(v3)]), + 3 | 17 => Color::Cmyk([byte(v0), byte(v1), byte(v2), byte(v3)]), + 4 => Color::Cmyk([byte(v0), byte(v1), byte(v2), 0.0]), + 5 | 21 => Color::Rgb([byte(v2), byte(v1), byte(v0)]), + 9 => Color::Gray(1.0 - byte(v0)), + 20 => Color::Registration, + 1 | 14 | 25 => { + let number = u16::from_le_bytes([v[0], v[1]]); + let tint = pct(f32::from(u16::from_le_bytes([v[2], v[3]]))); + push(warn, Warning::SpotLooks); + // Each library numbers its own colors: the name holds the palette and the number. + Color::Spot { name: format!("Spot {palette}:{number}"), tint, look: None } + } + _ => { + push(warn, Warning::UnknownColors); + Color::Rgb([0.0; 3]) + } + } +} + +/// A UTF-16 name stored as a character count and its code units. Every shape that uses the color +/// gets its own copy of the name: a name longer than [`MAX_NAME`] units keeps its first ones and a +/// hash of the whole name, with a warning, so two long names that start alike stay apart. +fn counted_utf16(r: &mut Rd, warn: &mut Vec) -> Option { + let n = r.u32()? as usize; + let b = r.bytes(n.checked_mul(2)?)?; + // Trailing NULs are padding. + let all = b.as_chunks::<2>().0; + let all = all.get(..all.iter().rposition(|c| *c != [0, 0]).map_or(0, |i| i + 1)).unwrap_or_default(); + let units = all.iter().map(|c| u16::from_le_bytes(*c)); + if all.len() <= MAX_NAME { + let units: Vec = units.collect(); + return Some(String::from_utf16_lossy(&units)); + } + push(warn, Warning::TooDeep); + // FNV-1a over the code units. + let hash = units.clone().fold(0xcbf2_9ce4_8422_2325_u64, |h, u| (h ^ u64::from(u)).wrapping_mul(0x0100_0000_01b3)); + let kept: Vec = units.take(MAX_NAME).collect(); + Some(format!("{} {hash:016x}", String::from_utf16_lossy(&kept))) +} + +/// The color of the property list of a tagged uniform fill (R11) or outline (R12): its color +/// record, named by the library name it carries. +pub(crate) fn property_color(b: &[u8], p: &Profile, warn: &mut Vec) -> Option { + let mut r = Rd::new(b); + let (mut found, mut name) = (None, None); + while r.left() >= 5 { + let kind = r.u8()?; + let len = r.u32()? as usize; + if kind == 0 { + break; + } + let body = r.bytes(len)?; + let mut br = Rd::new(body); + match kind { + 1 => found = color(&mut br, p, warn), + 8 => name = br.skip(16).and_then(|_| counted_utf16(&mut br, warn)), + 3 => name = name.or_else(|| counted_utf16(&mut br, warn)), + _ => {} + } + } + match (found?, name.filter(|n| !n.is_empty())) { + // A library color with its name: the record's sRGB has the tint applied already. + (Color::Rgb(rgb), Some(name)) => { + let tint = b_tint(b).unwrap_or(1.0); + Some(Color::Spot { name, tint, look: Some(untinted(rgb, tint)) }) + } + (c, _) => Some(c), + } +} + +/// The tint byte of the first color property of a property list (model 21 keeps it last). +fn b_tint(b: &[u8]) -> Option { + let mut r = Rd::new(b); + while r.left() >= 5 { + let kind = r.u8()?; + let len = r.u32()? as usize; + let body = r.bytes(len)?; + if kind == 1 { + let mut c = Rd::new(body); + return (c.u16()? == 21).then(|| f32::from(*body.get(11).unwrap_or(&100)) / 100.0).map(|t| t.clamp(0.0, 1.0)); + } + } + None +} + +/// The full-strength color behind sRGB `rgb` shown at `tint` (a tint mixes toward white). +fn untinted(rgb: [f32; 3], tint: f32) -> [f32; 3] { + if tint <= 0.0 { + return rgb; + } + rgb.map(|v| (1.0 - (1.0 - v) / tint).clamp(0.0, 1.0)) +} + +/// A fill record: its id, and its color (`None`: no fill). Fills of other kinds read as none with +/// a warning (R11). +pub(crate) fn fill(b: &[u8], p: &Profile, warn: &mut Vec) -> Option<(u32, Option)> { + let mut r = Rd::new(b); + let id = r.u32()?; + let body = if p.tagged { tagged_body(&mut r)? } else { r.bytes(r.left())? }; + let mut r = Rd::new(body); + let kind = r.u16()?; + let color = match kind { + 0 => None, + 1 if p.tagged => { + if r.u32()? != TAG_1300 { + push(warn, Warning::Damaged); + return Some((id, None)); + } + // A uniform fill whose color can't be read is damage, not a fill of none. + let len = r.u32()? as usize; + Some(property_color(r.bytes(len.min(r.left()))?, p, warn)?) + } + 1 => { + r.skip(2)?; + Some(color(&mut r, p, warn)?) + } + _ => { + push(warn, Warning::UnsupportedFills); + None + } + }; + Some((id, color)) +} + +/// The body of the record tagged 1300 that follows tagged records of later layouts (R11). +fn tagged_body<'a>(r: &mut Rd<'a>) -> Option<&'a [u8]> { + for _ in 0..=MAX_SKIPPED { + let (tag, len) = (r.u32()?, r.u32()? as usize); + let body = r.bytes(len.min(r.left()))?; + if tag == TAG_1300 { + return Some(body); + } + } + None +} + +/// An outline record: its id and the outline (`None`: no outline) (R12, R13). +pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec) -> Option<(u32, Option)> { + let mut r = Rd::new(b); + let id = r.u32()?; + // A library color named in a record of type 2, with the warnings its read gave. + let mut named = None; + if p.tagged { + let mut found = false; + for _ in 0..MAX_OUTLINE_RECORDS { + let (rec, len) = (r.u32()?, r.u32()? as usize); + if rec == 1 { + found = true; + break; + } + let body = r.bytes(len)?; + // Type 2 holds the outline's color as a property list, as a uniform fill does (R12). + // Only a library color with its name is taken from it; any other color comes from + // the fixed field below. + if rec == 2 { + let mut w = Vec::new(); + if let Some(c @ Color::Spot { look: Some(_), .. }) = property_color(body, p, &mut w) { + named = Some((c, w)); + } + } + } + if !found { + return None; + } + } + let (line_type, cap, join) = (r.u16()?, r.u16()?, r.u16()?); + r.skip(p.outl_after_join)?; + let width = coord(&mut r, p)?.abs(); + let _stretch = r.u16()?; + r.skip(p.outl_after_stretch)?; + let _nib = angle(&mut r, p)?; + r.skip(p.outl_after_angle)?; + let color = match named { + Some((named, w)) => { + color(&mut r, p, &mut Vec::new())?; + for x in w { + push(warn, x); + } + named + } + None => color(&mut r, p, warn)?, + }; + r.skip(p.outl_after_color)?; + let count = usize::from(r.u16()?); + let first_dash = r.pos(); + let fits = r.left() / 2; + if count > fits { + push(warn, Warning::Damaged); + } + // At most 65,535; the read's dash limit is applied where shapes use them. + let dashes: Vec = (0..count.min(fits)).filter_map(|_| r.u16().map(f64::from)).collect(); + if let Some(after) = p.marker_after_dash { + let mut m = Rd::at(b, first_dash + after); + if matches!((m.u32(), m.u32()), (Some(s), Some(e)) if s != 0 || e != 0) { + push(warn, Warning::Arrowheads); + } + } + // Bit 0 of the line type: no outline (R13). + if line_type & 1 != 0 { + return Some((id, None)); + } + let cap = match cap { + 1 => Cap::Round, + 2 => Cap::Square, + _ => Cap::Butt, + }; + let join = match join { + 1 => Join::Round, + 2 => Join::Bevel, + _ => Join::Miter, + }; + // Bit 2 of the line type marks the outline dashed; without it the dashes stored are not drawn + // (R48). + let dashes = if line_type & 4 != 0 && dashes.iter().any(|d| *d > 0.0) { dashes } else { Vec::new() }; + // Bit 4 of the line type: behind the fill (R49). + let behind_fill = line_type & 0x10 != 0; + // Bit 5 of the line type: scaled with the shape (R50). + let scale_with = line_type & 0x20 != 0; + Some((id, Some(Outline { width, color, cap, join, dashes, behind_fill, scale_with }))) +} + +/// The opacity and blend of argument 8000 from version 13 (R47): records of a u32 version, a u32 +/// length and a body. A body of version 1300 that is [`UNIFORM_LEN`] bytes long is a uniform +/// transparency: an f64 at byte 61 and the merge mode at byte 77. VectorCraft reads the f64 as the +/// transparency in percent, 0 opaque and 100 clear. `None` for any other argument, such as a lens, +/// and for a value out of range or a merge mode without a VectorCraft blend mode. +pub(crate) fn transparency(b: &[u8]) -> Option<(f32, Blend)> { + let mut r = Rd::new(b); + while r.left() >= 8 { + let (since, len) = (r.u32()?, r.u32()? as usize); + let body = r.bytes(len)?; + if since != TAG_1300 { + continue; + } + if body.len() != UNIFORM_LEN { + return None; + } + let value = Rd::at(body, 61).f64()?; + if !(0.0..=100.0).contains(&value) { + return None; + } + return Some(((1.0 - value / 100.0) as f32, blend(*body.get(77)?)?)); + } + None +} + +/// The length of a uniform transparency's record body (R47). +const UNIFORM_LEN: usize = 117; + +/// The blend mode of a transparency's merge mode byte (R47); `None` for the modes VectorCraft has +/// no blend mode for. +fn blend(mode: u8) -> Option { + Some(match mode { + 0 => Blend::Normal, + 9 => Blend::Multiply, + 11 => Blend::Lighten, + 12 => Blend::Darken, + 14 => Blend::Color, + 15 => Blend::Hue, + 16 => Blend::Saturation, + 17 => Blend::Luminosity, + 24 => Blend::Difference, + 28 => Blend::Screen, + 29 => Blend::Overlay, + 30 => Blend::SoftLight, + 31 => Blend::HardLight, + 33 => Blend::ColorDodge, + 34 => Blend::ColorBurn, + 36 => Blend::Exclusion, + _ => return None, + }) +} + +/// A name argument (R9): Windows-1252 up to a NUL before version 12, UTF-16LE from it. A name +/// longer than [`MAX_NAME`] bytes or UTF-16 units keeps its first ones (without half of a +/// surrogate pair) and a hash of the whole name, with a warning, as a library color's name does. +pub(crate) fn name(b: &[u8], p: &Profile, warn: &mut Vec) -> String { + if p.utf16_names { + let units = b.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).take_while(|u| *u != 0); + let (mut kept, hash) = capped(units, warn); + if hash.is_some() && kept.last().is_some_and(|u| (0xD800..0xDC00).contains(u)) { + kept.pop(); + } + with_hash(String::from_utf16_lossy(&kept), hash) + } else { + let bytes = b.iter().copied().take_while(|c| *c != 0); + let (kept, hash) = capped(bytes, warn); + with_hash(kept.into_iter().map(windows_1252).collect(), hash) + } +} + +/// The first [`MAX_NAME`] of `units`, and when there are more, an FNV-1a hash of them all, with a +/// warning. +fn capped>(units: impl Iterator + Clone, warn: &mut Vec) -> (Vec, Option) { + if units.clone().nth(MAX_NAME).is_none() { + return (units.collect(), None); + } + push(warn, Warning::TooDeep); + let hash = units.clone().fold(0xcbf2_9ce4_8422_2325_u64, |h, u| (h ^ u.into()).wrapping_mul(0x0100_0000_01b3)); + (units.take(MAX_NAME).collect(), Some(hash)) +} + +/// `name`, followed by `hash` in hexadecimal when there is one. +fn with_hash(name: String, hash: Option) -> String { + match hash { + Some(h) => format!("{name} {h:016x}"), + None => name, + } +} + +/// The characters Windows-1252 puts at 0x80 to 0x9F (U+FFFD where it has none); the other bytes +/// are Latin-1. +const CP1252_HIGH: [char; 32] = [ + '€', '\u{FFFD}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{FFFD}', 'Ž', '\u{FFFD}', '\u{FFFD}', '‘', '’', '“', '”', '•', '–', + '—', '˜', '™', 'š', '›', 'œ', '\u{FFFD}', 'ž', 'Ÿ', +]; + +fn windows_1252(c: u8) -> char { + match c { + 0x80..=0x9F => CP1252_HIGH.get(usize::from(c - 0x80)).copied().unwrap_or('\u{FFFD}'), + _ => char::from(c), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// An outline that names an arrowhead says so with a warning, in each version whose arrowhead + /// ids have a known place: 22 bytes after the first dash in versions 6 to 12, 20 from 13. + #[test] + fn arrowheads_are_named_from_version_6() { + let pen = crate::synth::Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }; + let color = [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100]; + for (version, place) in [ + (500, None), + (600, Some(22)), + (700, Some(22)), + (800, Some(22)), + (900, Some(22)), + (1000, Some(22)), + (1100, Some(22)), + (1200, Some(22)), + (1300, Some(20)), + (1700, Some(20)), + ] { + let p = crate::layout::for_version(version).unwrap(); + let plain = crate::synth::V(version).outline(7, pen, &color, &[]); + // The record ends with 32 bytes after its dashes, and this one has none. + let first_dash = plain.len() - 32; + let mut w = vec![]; + assert!(outline(&plain, &p, &mut w).is_some_and(|(id, o)| id == 7 && o.is_some()), "{version}"); + assert!(w.is_empty(), "{version}: {w:?}"); + let Some(place) = place else { continue }; + let mut arrow = plain.clone(); + arrow[first_dash + place..first_dash + place + 4].copy_from_slice(&9u32.to_le_bytes()); + let mut w = vec![]; + assert!(outline(&arrow, &p, &mut w).is_some(), "{version}"); + assert_eq!(w, vec![Warning::Arrowheads], "{version}"); + } + } + + #[test] + fn single_byte_names_read_as_windows_1252() { + let p = crate::layout::for_version(1100).unwrap(); + assert_eq!(name(b"Caf\xe9 \x80\x96\0junk", &p, &mut vec![]), "Café €–"); + let p = crate::layout::for_version(1200).unwrap(); + assert_eq!(name(&[0x41, 0, 0x42, 0, 0, 0, 0x43, 0], &p, &mut vec![]), "AB"); + } + + /// A layer name longer than [`MAX_NAME`] bytes or UTF-16 units keeps its first ones and a hash + /// of the whole name, with a warning, in both encodings. A cut never keeps half of a surrogate + /// pair. + #[test] + fn long_layer_names_are_cut_with_a_hash() { + for version in [1100, 1200] { + let p = crate::layout::for_version(version).unwrap(); + let bytes = + |s: &str| if p.utf16_names { s.encode_utf16().flat_map(u16::to_le_bytes).collect::>() } else { s.as_bytes().to_vec() }; + let mut w = vec![]; + let a = name(&bytes(&"N".repeat(100_000)), &p, &mut w); + let b = name(&bytes(&format!("{}M", "N".repeat(99_999))), &p, &mut vec![]); + assert_ne!(a, b, "{version}"); + assert!(a.starts_with(&"N".repeat(MAX_NAME)) && a.chars().count() == MAX_NAME + 17, "{version}: {}", a.len()); + assert_eq!(w, vec![Warning::TooDeep], "{version}"); + let mut w = vec![]; + assert_eq!(name(&bytes(&"N".repeat(MAX_NAME)), &p, &mut w), "N".repeat(MAX_NAME), "{version}"); + assert!(w.is_empty(), "{version}"); + } + let p = crate::layout::for_version(1200).unwrap(); + let emoji: Vec = format!("N{}", "\u{1F600}".repeat(200)).encode_utf16().flat_map(u16::to_le_bytes).collect(); + let cut = name(&emoji, &p, &mut vec![]); + assert!(!cut.contains('\u{FFFD}'), "{cut}"); + assert_eq!(cut.chars().filter(|c| *c == '\u{1F600}').count(), (MAX_NAME - 1) / 2); + } + + #[test] + fn colors_read_in_their_models() { + let p = crate::layout::for_version(500).unwrap(); + let rec = |model: u16, v: [u8; 4]| { + let mut b = model.to_le_bytes().to_vec(); + b.extend([0; 6]); + b.extend(v); + let mut w = vec![]; + (color(&mut Rd::new(&b), &p, &mut w), w) + }; + assert_eq!(rec(2, [100, 50, 0, 10]).0, Some(Color::Cmyk([1.0, 0.5, 0.0, 0.1]))); + assert_eq!(rec(5, [255, 0, 0, 0]).0, Some(Color::Rgb([0.0, 0.0, 1.0]))); + assert_eq!(rec(9, [255, 0, 0, 0]).0, Some(Color::Gray(0.0))); + assert_eq!(rec(25, [7, 0, 40, 0]).0, Some(Color::Spot { name: "Spot 0:7".into(), tint: 0.4, look: None })); + // The same number in another library is another color. + let mut other = 25u16.to_le_bytes().to_vec(); + other.extend(3u16.to_le_bytes()); + other.extend([0; 4]); + other.extend([7, 0, 40, 0]); + assert_eq!(color(&mut Rd::new(&other), &p, &mut vec![]), Some(Color::Spot { name: "Spot 3:7".into(), tint: 0.4, look: None })); + let (c, w) = rec(6, [1, 2, 3, 4]); + assert_eq!((c, w), (Some(Color::Rgb([0.0; 3])), vec![Warning::UnknownColors])); + } + + #[test] + fn colors_of_versions_3_and_4_read_models_0_and_1() { + let read = |version: u16, model: u8, v: [u16; 4]| { + let p = crate::layout::for_version(version).unwrap(); + let b: Vec = if version < 400 { + std::iter::once(model).chain(v.map(|x| x as u8)).collect() + } else { + u16::from(model).to_le_bytes().into_iter().chain(v.iter().flat_map(|x| x.to_le_bytes())).chain([0, 0]).collect() + }; + let mut r = Rd::new(&b); + let mut w = vec![]; + let c = color(&mut r, &p, &mut w); + assert_eq!(r.left(), 0, "{version}"); + (c, w) + }; + for version in [300, 400] { + // Model 1 is CMYK in percent, not a library color as from version 5. + assert_eq!(read(version, 1, [0, 100, 50, 10]).0, Some(Color::Cmyk([0.0, 1.0, 0.5, 0.1])), "{version}"); + assert_eq!(read(version, 2, [0, 100, 50, 10]).0, Some(Color::Cmyk([0.0, 1.0, 0.5, 0.1])), "{version}"); + } + // Model 0: an ink number and a tint. Version 3 stores each as a u16 in its four bytes. + assert_eq!(read(300, 0, [0, 0, 60, 0]).0, Some(Color::Gray(0.6))); + assert_eq!(read(300, 0, [1, 0, 60, 0]).0, Some(Color::Gray(0.0))); + assert_eq!(read(300, 0, [44, 1, 60, 0]), (Some(Color::Spot { name: "Spot 0:300".into(), tint: 0.6, look: None }), vec![Warning::SpotLooks])); + assert_eq!(read(400, 0, [0, 60, 0, 0]).0, Some(Color::Gray(0.6))); + assert_eq!(read(400, 0, [1, 60, 0, 0]).0, Some(Color::Gray(0.0))); + assert_eq!(read(400, 0, [300, 60, 0, 0]), (Some(Color::Spot { name: "Spot 0:300".into(), tint: 0.6, look: None }), vec![Warning::SpotLooks])); + } + + #[test] + fn a_fixed_point_matrix_reads_its_factors_and_offsets() { + let raw: Vec = [65536i32, -32768, 1000, 131072, 16384, -500].iter().flat_map(|v| v.to_le_bytes()).collect(); + let m = fixed_matrix(&mut Rd::new(&raw), 0.5).unwrap(); + assert_eq!(m, Matrix([1.0, 2.0, -0.5, 0.25, 500.0, -250.0])); + assert!(fixed_matrix(&mut Rd::new(&raw[..23]), 0.5).is_none()); + } + + #[test] + fn long_names_that_start_alike_stay_apart() { + let read = |name: &str| { + let mut b = (name.encode_utf16().count() as u32).to_le_bytes().to_vec(); + b.extend(name.encode_utf16().flat_map(u16::to_le_bytes)); + let mut w = vec![]; + (counted_utf16(&mut Rd::new(&b), &mut w).unwrap(), w) + }; + let (a, w) = read(&"N".repeat(300)); + let (b, _) = read(&format!("{}M", "N".repeat(299))); + assert_ne!(a, b); + assert!(a.starts_with(&"N".repeat(MAX_NAME)) && a.chars().count() == MAX_NAME + 17, "{a}"); + assert_eq!(w, vec![Warning::TooDeep]); + assert_eq!(read("Sky Blue"), ("Sky Blue".to_string(), vec![])); + // Padding doesn't count toward the length or the name. + let (padded, w) = read(&format!("{}\0\0", "N".repeat(MAX_NAME - 1))); + assert_eq!((padded, w), ("N".repeat(MAX_NAME - 1), vec![])); + } + + #[test] + fn a_tint_mixes_toward_white_and_comes_off_again() { + let shown = [0.6, 0.8, 1.0]; + let base = untinted(shown, 0.5); + assert!((base[0] - 0.2).abs() < 1e-6 && (base[1] - 0.6).abs() < 1e-6 && base[2] == 1.0); + } +} diff --git a/crates/cdr/src/riff.rs b/crates/cdr/src/riff.rs new file mode 100644 index 0000000000..3f041b4c37 --- /dev/null +++ b/crates/cdr/src/riff.rs @@ -0,0 +1,465 @@ +//! The chunk index: one flat table of every chunk, a list's children contiguous, built without +//! recursion. Payloads are not copied: an entry names a range of the RIFF stream, of the bytes +//! inflated from `LIST cmpr`, or of a package's data stream (layouts R1 to R4, R27). + +use std::cell::Cell; +use std::collections::BTreeMap; +use std::io::Read as _; + +use crate::bytes::{Rd, u32_at}; +use crate::layout; +use crate::limits::Budget; +use crate::package::Streams; +use crate::{Error, Warning}; + +pub(crate) const LIST: [u8; 4] = *b"LIST"; +const CMPR: [u8; 4] = *b"cmpr"; +const CPNG: [u8; 4] = *b"CPng"; +/// What follows `CPng` before the zlib stream (R3). +const CPNG_HEAD: [u8; 4] = [1, 0, 4, 0]; +/// The size of a redirect record, and the stream number of one that holds its body (R27). +const REDIRECT: usize = 16; +const INLINE: u32 = u32::MAX; + +/// One chunk: 28 bytes. `start` and `len` give the payload (after a list's form type) in its +/// source: 0 is the RIFF stream followed by the inflated bytes, `s + 1` is data stream `s`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Chunk { + pub(crate) id: [u8; 4], + /// A list's form type; zeros for other chunks. + pub(crate) form: [u8; 4], + src: u32, + start: u32, + len: u32, + first: u32, + count: u32, +} + +impl Chunk { + pub(crate) fn is_list(&self, form: &[u8; 4]) -> bool { + self.id == LIST && &self.form == form + } +} + +/// Every chunk of a file, and the bytes they point into. +pub(crate) struct Index<'a> { + input: &'a [u8], + inflated: Vec, + chunks: Vec, + /// The version the form type names: hundreds, as `vrsn` stores it (0 when the `vrsn` chunk + /// decides). + pub(crate) form_version: u16, + /// A version 16+ package's data streams; chunks of 16 bytes are redirect records then. + streams: Option>, + /// Bytes that inflating may still produce. + left: Cell, + /// The bytes redirected lists have taken: (package member, start) to end. + lists: Cell>, + /// The bytes other redirected chunks have taken, the same way. + leaves: Cell>, + /// Bytes that redirects to bytes another chunk already took may still read. + shared_left: Cell, + /// The first `vrsn` chunk among the file's own chunks, once seen, and the version it names + /// (`None` when it can't be read) (R2). + vrsn: Option>, +} + +/// A list still to be split into its children. +struct Pending { + entry: usize, + src: u32, + /// Its children's bytes. + start: usize, + end: usize, + /// The size pool of a compressed list's stream (`start..end` in source 0). + pool: Option<(usize, usize)>, + depth: usize, +} + +/// What reading one chunk header gives. +enum Read { + Chunk(Chunk), + /// A redirect record whose body can't be found: the chunk is left out, its list read on. + Lost, + /// A redirect record into a data stream past a limit: the chunk is left out without the + /// damage warning. + PastLimit, + /// A redirect record to bytes another chunk took, past the shared-bytes limit: the chunk is + /// left out with the limit warning. + SharedPastLimit, +} + +/// The version the RIFF form type names (R1): `CDR5`..`CDR9`, `CDRA` (10) to `CDRH` (17) with `I` +/// unused, then `J` (18) on; `CDR ` is version 3. Some files use a lower-case `cdr`, which names +/// the same versions except that `cdr8` is the 8.01 variant. Templates of version 21 have the form +/// type `CDTQ`; for `CDT` the `vrsn` chunk names the version, so this gives 0 (R28). +pub(crate) fn form_version(form: [u8; 4]) -> Option { + let [a, b, c, v] = form; + match (&[a, b, c], v) { + (b"cdr", b'8') => Some(801), + (b"CDR" | b"cdr", b' ') => Some(300), + (b"CDR" | b"cdr", b'1'..=b'9') => Some(100 * u16::from(v - b'0')), + (b"CDR" | b"cdr", b'A'..=b'H') => Some(100 * u16::from(v - b'A' + 10)), + (b"CDR" | b"cdr", b'J'..=b'W') => Some(100 * u16::from(v - b'J' + 18)), + (b"CDT", b'A'..=b'Z') => Some(0), + _ => None, + } +} + +/// Does `bytes` start like a RIFF `.cdr` drawing (not the `CDRX` exchange variant)? +pub(crate) fn is_cdr_riff(bytes: &[u8]) -> bool { + bytes.get(..4) == Some(b"RIFF") && bytes.get(8..12).and_then(|f| f.try_into().ok()).and_then(form_version).is_some() +} + +impl<'a> Index<'a> { + pub(crate) fn build(input: &'a [u8], streams: Option>, budget: &mut Budget, warn: &mut Vec) -> Result { + if input.len() > budget.limits.input { + return Err(Error::Limit("input size")); + } + let mut r = Rd::new(input); + if r.fourcc() != Some(*b"RIFF") { + return Err(Error::NotCdr); + } + let declared = r.u32().ok_or(Error::NotCdr)? as usize; + let form = r.fourcc().ok_or(Error::NotCdr)?; + let version = form_version(form).ok_or(Error::NotCdr)?; + // A file cut short keeps what it holds: its last chunk is truncated with a warning. A + // length that ends inside the form type is damage too, and the chunks after it are read. + let end = match declared.checked_add(8) { + Some(e) if (12..=input.len()).contains(&e) => e, + _ => { + push(warn, Warning::Damaged); + input.len() + } + }; + let left = Cell::new(budget.inflate_left()); + let mut ix = Index { + input, + inflated: Vec::new(), + chunks: Vec::new(), + form_version: version, + streams, + left, + lists: Cell::default(), + leaves: Cell::default(), + shared_left: Cell::new(budget.limits.member), + vrsn: None, + }; + ix.chunks.push(Chunk { id: *b"RIFF", form, src: 0, start: 12, len: 0, first: 0, count: 0 }); + let mut queue = vec![Pending { entry: 0, src: 0, start: 12, end, pool: None, depth: 0 }]; + while let Some(p) = queue.pop() { + ix.split(p, &mut queue, budget, warn)?; + } + Ok(ix) + } + + /// The bytes `start..end` of source `src`, or `None` when the range crosses its end. A data + /// stream is read on first use. + fn span(&self, src: u32, start: usize, end: usize) -> Option<&[u8]> { + if src > 0 { + let s = self.streams.as_ref()?; + return s.get(src as usize - 1, &self.left)?.get(start..end); + } + let n = self.input.len(); + if end <= n { + self.input.get(start..end) + } else if start >= n { + self.inflated.get(start - n..end - n) + } else { + None + } + } + + pub(crate) fn data(&self, c: &Chunk) -> &[u8] { + let start = c.start as usize; + match self.span(c.src, start, start + c.len as usize) { + Some(b) => b, + None => { + if let Some(s) = &self.streams + && !self.past_limit(c.src) + { + s.note_damage(); + } + &[] + } + } + } + + /// Was source `src` a data stream left out because it is past a limit? Its chunks are then + /// left out with that warning alone. + fn past_limit(&self, src: u32) -> bool { + src > 0 && self.streams.as_ref().is_some_and(|s| s.past_limit(src as usize - 1)) + } + + pub(crate) fn children(&self, c: &Chunk) -> &[Chunk] { + let first = c.first as usize; + self.chunks.get(first..first + c.count as usize).unwrap_or_default() + } + + pub(crate) fn root(&self) -> Option<&Chunk> { + self.chunks.first() + } + + /// The version: the `vrsn` chunk's when it names one from 3 to 27, else the form type's (R1, + /// R2). A template's form type names no version, so its `vrsn` chunk decides whatever it names + /// (R28). Letters count differently from the version 24 update on (R1), so when both name a + /// version after 27 the `vrsn` chunk's is the one refused. The `cdr8` form type alone makes a + /// file the 8.01 variant, whatever its `vrsn` chunk names (R1). + pub(crate) fn version(&self) -> u16 { + match self.vrsn.flatten() { + _ if self.form_version == 801 => 801, + Some(v) if (layout::OLDEST_RIFF..=layout::NEWEST).contains(&v) => v, + Some(v) if self.form_version == 0 => v, + Some(v) if v > layout::NEWEST && self.form_version > layout::NEWEST => v, + _ => self.form_version, + } + } + + /// The warnings for data streams that were left out. + pub(crate) fn stream_warnings(&self, warn: &mut Vec) { + if let Some(s) = &self.streams { + s.warnings(warn); + } + } + + /// Split list `p` into its children, appended to the table together; their lists are queued. + fn split(&mut self, p: Pending, queue: &mut Vec, budget: &mut Budget, warn: &mut Vec) -> Result<(), Error> { + let first = self.chunks.len(); + let mut at = p.start; + let mut lists = Vec::new(); + while at < p.end { + let Some((read, next, cut)) = self.read_chunk(p.src, at, p.end, p.pool) else { + push(warn, Warning::Damaged); + break; + }; + if cut { + push(warn, Warning::Damaged); + } + at = next; + // A redirect record whose body can't be found counts as well, so that lists redirected + // to again and again can't repeat such records past the limit. + budget.take_chunk()?; + let chunk = match read { + Read::Chunk(chunk) => chunk, + Read::Lost => { + push(warn, Warning::Damaged); + continue; + } + Read::PastLimit => continue, + Read::SharedPastLimit => { + push(warn, Warning::TooDeep); + continue; + } + }; + if p.entry == 0 && chunk.id == *b"vrsn" && self.vrsn.is_none() { + let at = chunk.start as usize; + self.vrsn = Some(self.span(chunk.src, at, at + chunk.len as usize).and_then(|b| Rd::new(b).u16())); + } + if chunk.id == LIST { + lists.push(self.chunks.len()); + } + self.chunks.push(chunk); + } + let count = (self.chunks.len() - first) as u32; + if let Some(parent) = self.chunks.get_mut(p.entry) { + parent.first = first as u32; + parent.count = count; + } + for i in lists { + let Some(c) = self.chunks.get(i).copied() else { continue }; + // From version 7 a `LIST stlt` holds the style tables, not chunks (R4); its body is read + // whole (R45). Before version 7 it holds chunks. The file's own chunks, its `vrsn` + // among them, are all read before this. + if c.form == *b"stlt" && self.version() >= 700 { + continue; + } + if p.depth + 1 > budget.limits.depth { + push(warn, Warning::TooDeep); + continue; + } + let (start, end) = (c.start as usize, c.start as usize + c.len as usize); + if c.form == CMPR && p.pool.is_none() { + match self.inflate_cmpr(c.src, start, end) { + Ok((s, e, pool)) => queue.push(Pending { entry: i, src: 0, start: s, end: e, pool: Some(pool), depth: p.depth + 1 }), + Err(Error::Limit(what)) => return Err(Error::Limit(what)), + Err(_) => push(warn, Warning::Damaged), + } + } else { + queue.push(Pending { entry: i, src: c.src, start, end, pool: p.pool, depth: p.depth + 1 }); + } + } + Ok(()) + } + + /// The chunk at `at` (before `end`) of source `src`, and where the next one starts. In a + /// compressed stream the size field is an index into the size pool (R3); in a version 16+ + /// package a chunk of 16 bytes outside one is a redirect record (R27). The flag is set for a + /// list cut short at `end`. + fn read_chunk(&self, src: u32, at: usize, end: usize, pool: Option<(usize, usize)>) -> Option<(Read, usize, bool)> { + let head = self.span(src, at, at.checked_add(8)?.min(end))?; + let id: [u8; 4] = head.get(..4)?.try_into().ok()?; + let raw = u32_at(head, 4)? as usize; + let size = match pool { + None => raw, + Some((ps, pe)) => { + let off = raw.checked_mul(4)?.checked_add(ps)?; + (off.checked_add(4)? <= pe).then_some(())?; + u32_at(self.span(0, off, off + 4)?, 0)? as usize + } + }; + let body = at + 8; + // A list cut short by the end of its parent keeps the bytes it has, so the children + // before the cut are read; the caller warns that it is damaged. Other chunks are lost. + let (size, cut) = match body.checked_add(size) { + Some(e) if e <= end => (size, false), + _ if id == LIST => (end.checked_sub(body)?, true), + _ => return None, + }; + let next = (body + size + (size & 1)).min(end); + if cut { + return Some((self.chunk(id, src, body, size).map_or(Read::Lost, Read::Chunk), next, true)); + } + if self.streams.is_some() && pool.is_none() && size == REDIRECT { + let read = match self.redirect(id, src, body) { + Some(read) => read, + None if self.redirect_past_limit(src, body) => Read::PastLimit, + None => Read::Lost, + }; + return Some((read, next, false)); + } + Some((Read::Chunk(self.chunk(id, src, body, size)?), next, false)) + } + + /// Chunk `id` whose body is `len` bytes at `body` of source `src`; a list's body starts with + /// its form type. + fn chunk(&self, id: [u8; 4], src: u32, body: usize, len: usize) -> Option { + let (form, start) = if id == LIST { + let f: [u8; 4] = self.span(src, body, body.checked_add(4).filter(|_| len >= 4)?)?.try_into().ok()?; + (f, body + 4) + } else { + ([0; 4], body) + }; + let len = len - (start - body); + Some(Chunk { id, form, src, start: u32::try_from(start).ok()?, len: u32::try_from(len).ok()?, first: 0, count: 0 }) + } + + /// The chunk the redirect record at `body` of `src` stands for (R27): stream, length, offset + /// and a reserved u32. Stream `0xFFFFFFFF` holds at most 8 bytes in the record itself, after + /// the length. The body is not read again as a redirect record. `None` when the body can't + /// be found. + /// + /// A redirected list whose bytes overlap those of an earlier redirected list, in any stream of + /// the same package member, is left out, so that no list is split twice. Other chunks may + /// share bytes: each one after the first to read them takes their length from the + /// shared-bytes limit (the member limit), so that many redirects to one body can't decode it + /// without end. + fn redirect(&self, id: [u8; 4], src: u32, body: usize) -> Option { + let mut r = Rd::new(self.span(src, body, body + REDIRECT)?); + let stream = r.u32()?; + let len = r.u32()? as usize; + if stream == INLINE { + return (len <= 8).then(|| self.chunk(id, src, body + 8, len).map(Read::Chunk))?; + } + let off = r.u32()? as usize; + let streams = self.streams.as_ref()?; + let size = streams.size(stream as usize)?; + let end = off.checked_add(len).filter(|&e| e <= size)?; + let member = streams.member_of(stream as usize)?; + if id == LIST { + if !claim(&self.lists, member, off, end) { + return None; + } + } else if !claim(&self.leaves, member, off, end) { + let left = self.shared_left.get(); + if len > left { + return Some(Read::SharedPastLimit); + } + self.shared_left.set(left - len); + } + // Only a list's form type is read now; other bodies are read when the mapping asks. + self.chunk(id, stream.checked_add(1)?, off, len).map(Read::Chunk) + } + + /// Does the redirect record at `body` of `src` point into a data stream past a limit? + fn redirect_past_limit(&self, src: u32, body: usize) -> bool { + let stream = self.span(src, body, body + 4).and_then(|b| u32_at(b, 0)); + stream.is_some_and(|s| s != INLINE && self.past_limit(s.saturating_add(1))) + } + + /// Inflate the two blocks of a `LIST cmpr` body at `start..end` of `src` (R3) → the chunk + /// stream and the size pool, as ranges of source 0. + fn inflate_cmpr(&mut self, src: u32, start: usize, end: usize) -> Result<(usize, usize, (usize, usize)), Error> { + let body = self.span(src, start, end).ok_or(Error::Damaged("compressed list"))?; + let mut r = Rd::new(body); + let c1 = r.u32().ok_or(Error::Damaged("compressed list"))? as usize; + r.skip(4).ok_or(Error::Damaged("compressed list"))?; + let c2 = r.u32().ok_or(Error::Damaged("compressed list"))? as usize; + let block = |at: usize, len: usize| -> Result<&[u8], Error> { + let b = body.get(at..at.checked_add(len).ok_or(Error::Damaged("compressed list"))?).ok_or(Error::Damaged("compressed list"))?; + let mut h = Rd::new(b); + if h.fourcc() != Some(CPNG) || h.fourcc() != Some(CPNG_HEAD) { + return Err(Error::Damaged("compressed block")); + } + Ok(b.get(8..).unwrap_or_default()) + }; + let second_at = c1.checked_add(16).ok_or(Error::Damaged("compressed list"))?; + let (first, second) = (block(16, c1)?.to_vec(), block(second_at, c2)?.to_vec()); + let base = self.input.len(); + let stream = self.inflate(&first)?; + let pool = self.inflate(&second)?; + Ok((base + stream.0, base + stream.1, (base + pool.0, base + pool.1))) + } + + /// Inflate zlib `data` onto the end of the inflated bytes, within what is left → its range + /// there. + fn inflate(&mut self, data: &[u8]) -> Result<(usize, usize), Error> { + let at = self.inflated.len(); + let left = self.left.get(); + let reader = flate2::read::ZlibDecoder::new(data); + // One byte past what is left tells a stream that is too long from one that just fits. + let got = match reader.take((left as u64).saturating_add(1)).read_to_end(&mut self.inflated) { + Ok(n) => n, + Err(_) => { + // What a stream inflated before it failed counts toward the limit too, so that + // streams that fail late can't inflate past it again and again. + let produced = self.inflated.len().saturating_sub(at); + self.left.set(left.saturating_sub(produced)); + self.inflated.truncate(at); + return Err(Error::Damaged("compressed block")); + } + }; + if got > left { + self.inflated.truncate(at); + return Err(Error::Limit("inflated size")); + } + self.left.set(left - got); + if self.input.len().saturating_add(self.inflated.len()) > u32::MAX as usize { + return Err(Error::Limit("inflated size")); + } + Ok((at, at + got)) + } +} + +/// Take bytes `start..end` of package member `member` in `claimed`, or `false` when an earlier +/// redirect there took any of them. Empty ranges take nothing. +fn claim(claimed: &Cell>, member: usize, start: usize, end: usize) -> bool { + if start == end { + return true; + } + let mut taken = claimed.take(); + let before = taken.range(..=(member, start)).next_back().is_some_and(|(&(m, _), &e)| m == member && e > start); + let after = taken.range((member, start)..).next().is_some_and(|(&(m, s), _)| m == member && s < end); + let free = !before && !after; + if free { + taken.insert((member, start), end); + } + claimed.set(taken); + free +} + +/// Add `w` to the warnings once. +pub(crate) fn push(warn: &mut Vec, w: Warning) { + if !warn.contains(&w) { + warn.push(w); + } +} diff --git a/crates/cdr/src/styles.rs b/crates/cdr/src/styles.rs new file mode 100644 index 0000000000..e4022563c2 --- /dev/null +++ b/crates/cdr/src/styles.rs @@ -0,0 +1,258 @@ +//! The style table in a `LIST stlt` of versions 7 to 15 (R45): the fill and outline records that a +//! style gives the objects that name it and have no fill or outline argument of their own. + +use std::collections::{HashMap, HashSet}; + +use crate::Error; +use crate::bytes::{Rd, u32_at}; +use crate::limits::Budget; + +/// One style: its parent, and the fill and outline table entries it names (0: none). +#[derive(Clone, Copy)] +struct Style { + parent: u32, + fill: u32, + outline: u32, +} + +/// The styles of a drawing: for each style id, the fill and outline records it gives, its +/// parents' included. +#[derive(Default)] +pub(crate) struct Styles { + fills: HashMap, + outlines: HashMap, +} + +impl Styles { + /// The style table in body `b` of a `LIST stlt` of `version` (R45), or `None` when it doesn't + /// parse to its end. Its fill and outline entries and its styles count toward the chunks a + /// read takes. + pub(crate) fn read(b: &[u8], version: u16, budget: &mut Budget) -> Result, Error> { + let mut limit = None; + let styles = parse(b, version, &mut |n| match budget.take_chunks(n) { + Ok(()) => true, + Err(e) => { + limit = Some(e); + false + } + }); + match limit { + Some(e) => Err(e), + None => Ok(styles), + } + } + + /// The fill record that style `id` gives. + pub(crate) fn fill(&self, id: u32) -> Option { + self.fills.get(&id).copied() + } + + /// The outline record that style `id` gives. + pub(crate) fn outline(&self, id: u32) -> Option { + self.outlines.get(&id).copied() + } +} + +/// The style table in `b`. `take` is asked for each count of entries or styles before they are +/// read; a `false` stops the read. +fn parse(b: &[u8], version: u16, take: &mut dyn FnMut(usize) -> bool) -> Option { + let mut r = Rd::new(b); + let count = r.u32()? as usize; + if count == 0 { + return (r.left() == 0).then(Styles::default); + } + // Fill entries carry 48 more bytes from version 13. + let fills = table(&mut r, if version >= 1300 { 60 } else { 12 }, take)?; + let outlines = table(&mut r, 12, take)?; + // The text style tables: fonts, alignments, spacings, two tables of fixed records, bullets, + // indents, hyphenation and drop caps, and from version 8.01 one more. + skip_table(&mut r, if version >= 1000 { 60 } else { 44 })?; + skip_table(&mut r, 12)?; + skip_table(&mut r, 52)?; + skip_table(&mut r, 152)?; + skip_table(&mut r, 784)?; + let bullets = r.u32()?; + for _ in 0..bullets { + bullet(&mut r, version)?; + } + skip_table(&mut r, 28)?; + skip_table(&mut r, if version >= 1300 { 36 } else { 32 })?; + skip_table(&mut r, 28)?; + if version >= 801 { + skip_table(&mut r, 12)?; + } + // Each style is at least 32 bytes. + if count > r.left() / 32 || !take(count) { + return None; + } + let mut styles = HashMap::new(); + for _ in 0..count { + let (id, s) = style(&mut r, version)?; + styles.entry(id).or_insert(s); + } + if r.left() != 0 { + return None; + } + let mut work = 0; + Some(Styles { fills: resolve(&styles, &fills, |s| s.fill, &mut work), outlines: resolve(&styles, &outlines, |s| s.outline, &mut work) }) +} + +/// For each style, the record of `table` that its own entry names, or the nearest parent's where +/// its entry is 0. Each style is resolved once, and each path forgets only the styles on it, so a +/// chain of any length takes time in proportion to the styles; a chain that comes back to a style +/// on it, or reaches a style that isn't there, gives no record. `work` counts the styles visited +/// and forgotten. +fn resolve(styles: &HashMap, table: &HashMap, entry: impl Fn(&Style) -> u32, work: &mut usize) -> HashMap { + // `None`: resolved to no record. + let mut done: HashMap> = HashMap::new(); + let mut path = Vec::new(); + let mut on_path = HashSet::new(); + for &start in styles.keys() { + let mut id = start; + let found = loop { + *work += 1; + if let Some(&known) = done.get(&id) { + break known; + } + let Some(s) = styles.get(&id) else { break None }; + // Back at a style on this path: a cycle. + if !on_path.insert(id) { + break None; + } + path.push(id); + match entry(s) { + 0 => id = s.parent, + e => break table.get(&e).copied(), + } + }; + for id in path.drain(..) { + *work += 1; + on_path.remove(&id); + done.insert(id, found); + } + } + done.into_iter().filter_map(|(id, r)| Some((id, r?))).collect() +} + +/// A table of a u32 count and entries of `size` bytes, each a table id, 4 bytes and a record id. +fn table(r: &mut Rd, size: usize, take: &mut dyn FnMut(usize) -> bool) -> Option> { + let n = r.u32()? as usize; + if n > r.left() / size || !take(n) { + return None; + } + let mut out = HashMap::new(); + for _ in 0..n { + let e = r.bytes(size)?; + out.entry(u32_at(e, 0)?).or_insert(u32_at(e, 8)?); + } + Some(out) +} + +/// A table of a u32 count and entries of `size` bytes, passed over. +fn skip_table(r: &mut Rd, size: usize) -> Option<()> { + let n = r.u32()? as usize; + r.skip(n.checked_mul(size)?) +} + +/// A bullet record, passed over: its length depends on a u32 inside it. +fn bullet(r: &mut Rd, version: u16) -> Option<()> { + r.skip(40)?; + if version >= 1300 { + if version >= 1400 { + r.skip(4)?; + } + let more = r.u32()?; + return r.skip(if more != 0 { 68 } else { 12 }); + } + r.skip(if version >= 1000 { 28 } else { 20 })?; + let more = r.u32()?; + if more != 0 { + r.skip(8)?; + } + r.skip(8) +} + +/// A style record: its kind (u32), id, parent, 8 bytes, a name length and the name (bytes before +/// version 12, UTF-16 units from it), the fill and outline entries, then the entries of text +/// styles (kinds 2 and 3). +fn style(r: &mut Rd, version: u16) -> Option<(u32, Style)> { + let kind = r.u32()?; + let (id, parent) = (r.u32()?, r.u32()?); + r.skip(8)?; + let len = r.u32()? as usize; + r.skip(len.checked_mul(if version >= 1200 { 2 } else { 1 })?)?; + let (fill, outline) = (r.u32()?, r.u32()?); + if kind > 1 { + r.skip(if version >= 801 { 20 } else { 16 })?; + } + if kind > 2 { + r.skip(20)?; + } + Some((id, Style { parent, fill, outline })) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Limits; + use crate::synth::{self, V}; + + fn read(b: &[u8], version: u16) -> Option { + Styles::read(b, version, &mut Budget::new(Limits::default())).unwrap() + } + + #[test] + fn styles_that_name_each_other_as_parents_end() { + let looped = [synth::Style { id: 0x10, parent: 0x11, fill: 0, outline: 0 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }]; + let s = read(&synth::stlt_body(V(700), &[(0x100, 1)], &[], &looped, false), 700).unwrap(); + assert_eq!((s.fill(0x10), s.outline(0x11), s.fill(0x12)), (None, None, None)); + } + + #[test] + fn a_long_chain_of_parents_reaches_the_style_that_names_an_entry() { + let mut chain = vec![synth::Style { id: 1, parent: 0, fill: 0x100, outline: 0 }]; + chain.extend((2..=500).map(|id| synth::Style { id, parent: id - 1, fill: 0, outline: 0 })); + let s = read(&synth::stlt_body(V(1100), &[(0x100, 7)], &[], &chain, false), 1100).unwrap(); + assert_eq!((s.fill(500), s.fill(250), s.outline(500)), (Some(7), Some(7), None)); + } + + /// A loop of 2,000 styles, which every walk into it follows around, leaves the walks of 20,000 + /// other styles no more work than the styles they visit. + #[test] + fn one_long_walk_does_not_slow_the_walks_after_it() { + let mut styles: HashMap = (1..=2000).map(|id| (id, Style { parent: id % 2000 + 1, fill: 0, outline: 0 })).collect(); + styles.extend((10_001..=30_000).map(|id| (id, Style { parent: 0, fill: 0x100, outline: 0 }))); + let table = HashMap::from([(0x100, 7)]); + let mut work = 0; + let fills = resolve(&styles, &table, |s| s.fill, &mut work); + assert_eq!((fills.get(&1), fills.get(&10_001), fills.len()), (None, Some(&7), 20_000)); + assert!(work <= 4 * styles.len(), "{work}"); + } + + #[test] + fn an_entry_missing_from_its_table_names_no_record() { + let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x101, outline: 0x200 }]; + let s = read(&synth::stlt_body(V(1300), &[(0x100, 1)], &[(0x200, 2)], &styles, false), 1300).unwrap(); + assert_eq!((s.fill(0x10), s.outline(0x10)), (None, Some(2))); + } + + #[test] + fn counts_past_the_body_do_not_parse() { + let mut b = synth::stlt_body(V(900), &[], &[], &[], false); + b[..4].copy_from_slice(&u32::MAX.to_le_bytes()); + assert!(read(&b, 900).is_none()); + let empty = 0u32.to_le_bytes(); + assert!(read(&empty, 900).is_some()); + assert!(read(&[], 900).is_none()); + } + + #[test] + fn entries_and_styles_count_toward_the_chunk_limit() { + let styles: Vec<_> = (1..=10).map(|id| synth::Style { id, parent: 0, fill: 0x100, outline: 0 }).collect(); + let b = synth::stlt_body(V(1000), &[(0x100, 1)], &[], &styles, false); + let mut budget = Budget::new(Limits { chunks: 10, ..Limits::default() }); + assert_eq!(Styles::read(&b, 1000, &mut budget).err(), Some(Error::Limit("chunk count"))); + let mut budget = Budget::new(Limits { chunks: 11, ..Limits::default() }); + assert!(Styles::read(&b, 1000, &mut budget).is_ok_and(|s| s.is_some())); + } +} diff --git a/crates/cdr/src/synth.rs b/crates/cdr/src/synth.rs new file mode 100644 index 0000000000..e109d8bf1d --- /dev/null +++ b/crates/cdr/src/synth.rs @@ -0,0 +1,1083 @@ +//! Synthetic drawings for tests and fuzz seeds, built from the layouts in `PROVENANCE.md`. Not a +//! `.cdr` writer: nothing checks that other programs open these files. + +use std::io::Write as _; + +/// A chunk or a list, before it is laid out. +#[derive(Clone, Debug)] +pub enum Node { + Chunk([u8; 4], Vec), + List([u8; 4], Vec), +} + +pub fn chunk(id: &[u8; 4], data: Vec) -> Node { + Node::Chunk(*id, data) +} + +pub fn list(form: &[u8; 4], children: Vec) -> Node { + Node::List(*form, children) +} + +fn put(out: &mut Vec, id: &[u8; 4], size: u32, body: &[u8], len: usize) { + out.extend(id); + out.extend(size.to_le_bytes()); + out.extend(body); + if len % 2 == 1 { + out.push(0); + } +} + +/// `n` laid out with real sizes. +pub fn plain(n: &Node) -> Vec { + let mut out = Vec::new(); + match n { + Node::Chunk(id, data) => put(&mut out, id, data.len() as u32, data, data.len()), + Node::List(form, kids) => { + let mut body = form.to_vec(); + body.extend(kids.iter().flat_map(plain)); + put(&mut out, b"LIST", body.len() as u32, &body, body.len()); + } + } + out +} + +/// `n` laid out for a compressed stream: each size field is an index into `pool`. +fn pooled(n: &Node, pool: &mut Vec) -> Vec { + let mut out = Vec::new(); + let (id, body) = match n { + Node::Chunk(id, data) => (*id, data.clone()), + Node::List(form, kids) => { + let mut body = form.to_vec(); + for k in kids { + body.extend(pooled(k, pool)); + } + (*b"LIST", body) + } + }; + let index = pool.len() as u32; + pool.push(body.len() as u32); + put(&mut out, &id, index, &body, body.len()); + out +} + +fn zlib(data: &[u8]) -> Vec { + let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + let _ = e.write_all(data); + e.finish().unwrap_or_default() +} + +/// A `LIST cmpr` holding `children` (R3). +pub fn cmpr(children: &[Node]) -> Node { + let mut pool = Vec::new(); + let stream: Vec = children.iter().flat_map(|c| pooled(c, &mut pool)).collect(); + let sizes: Vec = pool.iter().flat_map(|s| s.to_le_bytes()).collect(); + let block = |raw: &[u8]| { + let mut b = b"CPng".to_vec(); + b.extend([1, 0, 4, 0]); + b.extend(zlib(raw)); + b + }; + let (b1, b2) = (block(&stream), block(&sizes)); + let mut body = Vec::new(); + for (c, u) in [(b1.len(), stream.len()), (b2.len(), sizes.len())] { + body.extend((c as u32).to_le_bytes()); + body.extend((u as u32).to_le_bytes()); + } + body.extend(b1); + body.extend(b2); + Node::Chunk(*b"LIST", [b"cmpr".to_vec(), body].concat()) +} + +/// The form type letter of `version` (hundreds) (R1). +pub fn form(version: u16) -> [u8; 4] { + let n = (version / 100) as u8; + let c = match n { + // Version 3 has a space where later versions have their character. + 3 => b' ', + 0..=9 => b'0' + n, + 10..=17 => b'A' + n - 10, + _ => b'J' + n - 18, + }; + [b'C', b'D', b'R', c] +} + +/// A RIFF file of `version` holding `children`. +pub fn riff(version: u16, children: &[Node]) -> Vec { + let mut body = form(version).to_vec(); + for c in children { + body.extend(match c { + // A prebuilt `LIST cmpr` carries its own form type. + Node::Chunk(id, data) if id == b"LIST" => { + let mut o = Vec::new(); + put(&mut o, id, data.len() as u32, data, data.len()); + o + } + _ => plain(c), + }); + } + let mut out = b"RIFF".to_vec(); + out.extend((body.len() as u32).to_le_bytes()); + out.extend(body); + out +} + +/// Field writers for one version. +#[derive(Clone, Copy, Debug)] +pub struct V(pub u16); + +impl V { + pub fn short(self) -> bool { + self.0 < 600 + } + + pub fn word(self, v: usize) -> Vec { + if self.short() { (v as u16).to_le_bytes().to_vec() } else { (v as u32).to_le_bytes().to_vec() } + } + + /// Rectangle coordinates of `w` × `h` points with corners of `radius` points: coordinates + /// before version 15 (R15), from 15 f64 sizes and radii as shares of half the shorter side + /// (R29). + pub fn rect(self, w: f64, h: f64, radius: f64) -> Vec { + if self.0 < 1500 { + let n = if self.0 >= 900 { 4 } else { 1 }; + let mut out = [self.coord(w), self.coord(h)].concat(); + for _ in 0..n { + out.extend(self.coord(radius)); + } + return out; + } + let units = |pt: f64| pt / 72.0 * 254_000.0; + let mut out = Vec::new(); + for v in [units(w), units(h), 1.0, 1.0] { + out.extend(v.to_le_bytes()); + } + out.extend([0; 8]); + let share = radius / (w.abs().min(h.abs()) / 2.0); + for k in 0..4 { + if k > 0 { + out.extend([0; 16]); + } + out.extend(share.to_le_bytes()); + } + out + } + + /// A length in points as a coordinate. + pub fn coord(self, pt: f64) -> Vec { + if self.short() { + ((pt / 72.0 * 1000.0).round() as i16).to_le_bytes().to_vec() + } else { + ((pt / 72.0 * 254_000.0).round() as i32).to_le_bytes().to_vec() + } + } + + pub fn angle(self, deg: f64) -> Vec { + if self.short() { ((deg * 10.0).round() as i16).to_le_bytes().to_vec() } else { ((deg * 1_000_000.0).round() as i32).to_le_bytes().to_vec() } + } + + /// A `loda` record of object type `kind` (R6): header, arguments, offsets, then the types in + /// reverse. + pub fn loda(self, kind: u32, args: &[(u32, Vec)]) -> Vec { + let w = if self.short() { 2 } else { 4 }; + let head = 5 * w; + let mut body: Vec = Vec::new(); + let mut offsets = Vec::new(); + for (_, a) in args { + offsets.push(head + body.len()); + body.extend(a); + } + offsets.push(head + body.len()); + let offsets_at = head + body.len(); + let types_at = offsets_at + offsets.len() * w; + let total = types_at + args.len() * w; + let mut out = Vec::new(); + for f in [total, args.len(), offsets_at, types_at, kind as usize] { + out.extend(self.word(f)); + } + out.extend(body); + for o in offsets { + out.extend(self.word(o)); + } + for (t, _) in args.iter().rev() { + out.extend(self.word(*t as usize)); + } + out + } + + /// A `trfd` of `matrices` `[a, b, c, d, e, f]` with offsets in points (R8); before version 5 + /// each matrix is in fixed point (R37). + pub fn trfd(self, matrices: &[[f64; 6]]) -> Vec { + let w = if self.short() { 2 } else { 4 }; + let head = 3 * w; + let table = head; + let mut entries = Vec::new(); + let mut offsets = Vec::new(); + // The table holds one offset more than the entries: the record's end (R51). + let first = table + (matrices.len() + 1) * w; + for m in matrices { + offsets.push(first + entries.len()); + if self.0 >= 1300 { + entries.extend([0; 8]); + } + entries.extend(8u16.to_le_bytes()); + if !self.short() { + entries.extend([0; 6]); + } + if self.0 < 500 { + entries.extend(fixed_matrix(m)); + continue; + } + let unit = if self.short() { 1000.0 / 72.0 } else { 254_000.0 / 72.0 }; + let [a, b, c, d, e, f] = *m; + for v in [a, c, e * unit, b, d, f * unit] { + entries.extend(v.to_le_bytes()); + } + } + offsets.push(first + entries.len()); + let mut out = Vec::new(); + for f in [first + entries.len(), matrices.len(), table] { + out.extend(self.word(f)); + } + for o in offsets { + out.extend(self.word(o)); + } + out.extend(entries); + out + } + + /// A curve's point list (R16). + pub fn points(self, pts: &[(f64, f64, u8)]) -> Vec { + let mut out = (pts.len() as u32).to_le_bytes().to_vec(); + for (x, y, _) in pts { + out.extend(self.coord(*x)); + out.extend(self.coord(*y)); + } + out.extend(pts.iter().map(|p| p.2)); + out + } + + /// A uniform fill record (R11) of 12-byte color `color`. + pub fn fill(self, id: u32, color: &[u8; 12]) -> Vec { + let mut out = id.to_le_bytes().to_vec(); + if self.0 >= 1300 { + let mut props = vec![1]; + props.extend(12u32.to_le_bytes()); + props.extend(color); + props.extend([0, 0, 0, 0, 0]); + let mut solid = 1300u32.to_le_bytes().to_vec(); + solid.extend((props.len() as u32).to_le_bytes()); + solid.extend(props); + let mut body = 1u16.to_le_bytes().to_vec(); + body.extend(solid); + out.extend(1300u32.to_le_bytes()); + out.extend((body.len() as u32).to_le_bytes()); + out.extend(body); + } else { + out.extend(1u16.to_le_bytes()); + out.extend([0, 0]); + out.extend(color); + } + out + } + + /// An outline record (R12) of `pen`, `color` and `dashes`. + pub fn outline(self, id: u32, pen: Pen, color: &[u8; 12], dashes: &[u16]) -> Vec { + let Pen { line_type, width, cap, join } = pen; + let mut out = id.to_le_bytes().to_vec(); + if self.0 >= 1300 { + out.extend(1u32.to_le_bytes()); + out.extend(0u32.to_le_bytes()); + } + for f in [line_type, cap, join] { + out.extend(f.to_le_bytes()); + } + let v = self.0; + out.extend(vec![0; if (600..1300).contains(&v) { 2 } else { 0 }]); + out.extend(self.coord(width)); + out.extend(100u16.to_le_bytes()); + out.extend(vec![0; if self.short() { 0 } else { 2 }]); + out.extend(self.angle(0.0)); + out.extend(vec![ + 0; + if v >= 1300 { + 46 + } else if self.short() { + 0 + } else { + 52 + } + ]); + out.extend(color); + out.extend(vec![0; if self.short() { 10 } else { 16 }]); + out.extend((dashes.len() as u16).to_le_bytes()); + for d in dashes { + out.extend(d.to_le_bytes()); + } + out.extend([0; 32]); + out + } +} + +/// An outline's line type (bit 0: none), width in points, cap and join. +#[derive(Clone, Copy, Debug)] +pub struct Pen { + pub line_type: u16, + pub width: f64, + pub cap: u16, + pub join: u16, +} + +/// A 12-byte color record (R14) of `model` and its four value bytes. +pub fn color(model: u16, v: [u8; 4]) -> [u8; 12] { + let mut c = [0; 12]; + c[..2].copy_from_slice(&model.to_le_bytes()); + c[8..].copy_from_slice(&v); + c +} + +/// A version 4 color (R36): `model` and its four values as u16, then 2 bytes. +pub fn color4(model: u16, v: [u16; 4]) -> [u8; 12] { + let mut c = [0; 12]; + c[..2].copy_from_slice(&model.to_le_bytes()); + for (k, x) in v.into_iter().enumerate() { + c[2 + 2 * k..4 + 2 * k].copy_from_slice(&x.to_le_bytes()); + } + c +} + +/// A color of versions 1 to 3 (R36): `model` and its four value bytes. +pub fn color3(model: u8, v: [u8; 4]) -> [u8; 5] { + [model, v[0], v[1], v[2], v[3]] +} + +/// A matrix `[a, b, c, d, e, f]` with offsets in points as six i32 `a c tx b d ty`: the factors in +/// 16.16 fixed point, the offsets in 1/1000 inch (R37). +fn fixed_matrix(m: &[f64; 6]) -> Vec { + let [a, b, c, d, e, f] = *m; + let fixed = |v: f64| (v * 65536.0).round() as i32; + let units = |pt: f64| (pt / 72.0 * 1000.0).round() as i32; + [fixed(a), fixed(c), units(e), fixed(b), fixed(d), units(f)].iter().flat_map(|v| v.to_le_bytes()).collect() +} + +/// The transforms argument (100) of a version 3 object or group (R33): one matrix entry for each +/// of `matrices` `[a, b, c, d, e, f]` with offsets in points, applied in the order given. +pub fn transforms3(matrices: &[[f64; 6]]) -> Vec { + let first = 4 + 10 * matrices.len(); + let mut out = vec![0, 0]; + out.extend((matrices.len() as u16).to_le_bytes()); + for i in 0..matrices.len() { + out.extend(0x8cu16.to_le_bytes()); + out.extend([0; 4]); + out.extend(((first + 24 * i) as u16).to_le_bytes()); + out.extend([0; 2]); + } + out.extend(matrices.iter().flat_map(fixed_matrix)); + out +} + +/// The fill argument (20) of a version 3 object (R34): the type byte, then `color` for a uniform +/// fill (type 1). +pub fn fill3(kind: u8, color: &[u8]) -> Vec { + let mut out = vec![kind]; + out.extend(color); + out +} + +/// The outline argument (10) of a version 3 object (R35) of `pen`, `color` and `dashes`; bit 0 of +/// its flags is set unless the pen's line type says no outline. +pub fn outline3(pen: Pen, color: [u8; 5], dashes: &[u8]) -> Vec { + let v = V(300); + let mut out = vec![u8::from(pen.line_type & 1 == 0)]; + out.extend(v.coord(pen.width)); + out.extend(100u16.to_le_bytes()); + out.extend(v.angle(0.0)); + out.extend(color); + out.extend([0; 7]); + out.push(dashes.len() as u8); + let mut area = dashes.to_vec(); + area.resize(10, 0); + out.extend(area); + out.extend(pen.join.to_le_bytes()); + out.extend(pen.cap.to_le_bytes()); + out.extend([0; 8]); + out +} + +/// A version 3 group (R33): its own `lobj` with the transforms that place `objects`, then the +/// objects. +pub fn group3(matrices: &[[f64; 6]], objects: Vec) -> Node { + let mut kids = vec![chunk(b"flgs", vec![0, 0, 0, 0x10]), chunk(b"lobj", V(300).loda(0, &[(100, transforms3(matrices))]))]; + kids.extend(objects); + list(b"grp ", kids) +} + +/// An object list: flags, then a `lgob` list with the `loda` and an optional transform in a `trfl` +/// list (R22). A version 3 object is a `lobj` whose type counts from 0 (R32) and whose transform is +/// its argument 100 (R33). +pub fn object(v: V, kind: u32, args: &[(u32, Vec)], matrix: Option<[f64; 6]>) -> Node { + if v.0 < 400 { + let kind = if (1..=5).contains(&kind) { kind - 1 } else { kind }; + let mut args = args.to_vec(); + args.extend(matrix.map(|m| (100, transforms3(&[m])))); + return list(b"obj ", vec![chunk(b"flgs", vec![0, 0, 0, 0x08]), chunk(b"lobj", v.loda(kind, &args))]); + } + let mut own = vec![chunk(b"loda", v.loda(kind, args))]; + if let Some(m) = matrix { + own.push(list(b"trfl", vec![chunk(b"trfd", v.trfd(&[m]))])); + } + list(b"obj ", vec![chunk(b"flgs", vec![0, 0, 0, 0x08]), list(b"lgob", own)]) +} + +/// A layer list of `kind` flags named `name` holding `objects`, its `loda` in a `lgob` list (R22), +/// with the object type that layers of such flags have in sample files (R19). +pub fn layer(v: V, flags: [u8; 4], name: &str, objects: Vec) -> Node { + let kind = match flags { + [b0, ..] if (b0 & 0x0f == 0x0a || b0 & 0x0f == 0x02) && b0 & 0x10 != 0 => 11, + [b0, ..] if b0 & 0x0f == 0x0a || b0 & 0x0f == 0x02 => 12, + [b0, _, b2, _] if b0 & 0x0f == 0x08 && b2 != 0 => 17, + [0, 1, 1, _] => 17, + _ => 0, + }; + // Version 3 counts its types from 0, one less (R32). + let kind = if v.0 < 400 && kind > 0 { kind - 1 } else { kind }; + layer_of_type(v, flags, kind, name, objects) +} + +/// A layer list as [`layer`] writes it, with the object type `kind` in its `loda`. +pub fn layer_of_type(v: V, flags: [u8; 4], kind: u32, name: &str, objects: Vec) -> Node { + let name: Vec = + if v.0 >= 1200 { name.encode_utf16().chain([0]).flat_map(|u| u.to_le_bytes()).collect() } else { name.bytes().chain([0]).collect() }; + let mut kids = vec![chunk(b"flgs", flags.to_vec()), list(b"lgob", vec![chunk(b"loda", v.loda(kind, &[(1000, name)]))])]; + kids.extend(objects); + list(b"layr", kids) +} + +/// A page list: flags (byte 2 set for the master page), then its layers in a `gobj` list (R22). +pub fn page(master: bool, layers: Vec) -> Node { + list(b"page", vec![chunk(b"flgs", vec![0, 0, u8::from(master), 0x90]), list(b"gobj", layers)]) +} + +/// The `mcfg` chunk of `version` with a page of `w` × `h` points (R10); in version 3, 2 bytes and +/// the page's top left and bottom right corners (R38). +pub fn mcfg(v: V, w: f64, h: f64) -> Node { + if v.0 < 400 { + let mut b = vec![0; 2]; + b.extend([v.coord(-w / 2.0), v.coord(h / 2.0), v.coord(w / 2.0), v.coord(-h / 2.0)].concat()); + b.extend([0; 16]); + return chunk(b"mcfg", b); + } + let skip = if v.0 >= 1300 { + 12 + } else if v.0 >= 900 { + 4 + } else if (600..700).contains(&v.0) { + 28 + } else { + 0 + }; + let mut b = vec![0; skip]; + b.extend(v.coord(w)); + b.extend(v.coord(h)); + b.extend([0; 16]); + chunk(b"mcfg", b) +} + +/// A style of a [`stlt_body`]: its id, its parent's id, and its fill and outline table entries. +#[derive(Clone, Copy, Debug)] +pub struct Style { + pub id: u32, + pub parent: u32, + pub fill: u32, + pub outline: u32, +} + +/// The body of a `LIST stlt` of `v` (R45): the style count, the fill table (`(entry, fild id)`) and +/// the outline table (`(entry, outl id)`), the text style tables (each with one record when +/// `text`), then `styles` as styles of kind 1, and when `text` a style of kind 2 and one of kind 3. +pub fn stlt_body(v: V, fills: &[(u32, u32)], outlines: &[(u32, u32)], styles: &[Style], text: bool) -> Vec { + let version = v.0; + let u32s = |vals: &[u32]| -> Vec { vals.iter().flat_map(|x| x.to_le_bytes()).collect() }; + let count = styles.len() + if text { 2 } else { 0 }; + let mut b = u32s(&[count as u32]); + // A table without styles holds nothing else. + if count == 0 { + return b; + } + for (table, size) in [(fills, if version >= 1300 { 60 } else { 12 }), (outlines, 12)] { + b.extend(u32s(&[table.len() as u32])); + for (entry, record) in table { + let mut e = u32s(&[*entry, 0, *record]); + e.resize(size, 0); + b.extend(e); + } + } + let n = u32::from(text); + let fixed = |size: usize| -> Vec { + let mut t = n.to_le_bytes().to_vec(); + t.extend(vec![0x5a; size * n as usize]); + t + }; + // Fonts, alignments, spacings and two tables of fixed records. + for size in [if version >= 1000 { 60 } else { 44 }, 12, 52, 152, 784] { + b.extend(fixed(size)); + } + // One bullet, whose u32 inside asks for the longer form. + b.extend(n.to_le_bytes()); + if text { + b.extend([0x5a; 40]); + if version >= 1300 { + if version >= 1400 { + b.extend([0x5a; 4]); + } + b.extend(u32s(&[1])); + b.extend([0x5a; 68]); + } else { + b.extend(vec![0x5a; if version >= 1000 { 28 } else { 20 }]); + b.extend(u32s(&[1])); + b.extend([0x5a; 16]); + } + } + // Indents, hyphenation, drop caps, and from version 8.01 one more table. + for size in [28, if version >= 1300 { 36 } else { 32 }, 28] { + b.extend(fixed(size)); + } + if version >= 801 { + b.extend(fixed(12)); + } + let text_styles = [(2, Style { id: 0x7f02, parent: 0, fill: 0, outline: 0 }), (3, Style { id: 0x7f03, parent: 0x7f02, fill: 0, outline: 0 })]; + let all = styles.iter().map(|s| (1u32, *s)).chain(text_styles.into_iter().filter(|_| text)); + for (kind, s) in all { + b.extend(u32s(&[kind, s.id, s.parent, 1, 1])); + if version >= 1200 { + b.extend(u32s(&[7])); + b.extend("Graphic".encode_utf16().flat_map(u16::to_le_bytes)); + } else { + b.extend(u32s(&[8])); + b.extend(b"Graphic\0"); + } + b.extend(u32s(&[s.fill, s.outline])); + if kind > 1 { + b.extend(vec![0; if version >= 801 { 20 } else { 16 }]); + } + if kind > 2 { + b.extend([0; 20]); + } + } + b +} + +/// A `LIST stlt` of [`stlt_body`]. +pub fn stlt(v: V, fills: &[(u32, u32)], outlines: &[(u32, u32)], styles: &[Style], text: bool) -> Node { + Node::Chunk(*b"LIST", [b"stlt".to_vec(), stlt_body(v, fills, outlines, styles, text)].concat()) +} + +/// A `LIST clpt` of clipped groups (R46): each a `LIST grp ` with its `spnd` id, then its objects. +pub fn clpt(groups: Vec<(u32, Vec)>) -> Node { + let groups = groups + .into_iter() + .map(|(id, objects)| { + let mut kids = vec![chunk(b"spnd", id.to_le_bytes().to_vec())]; + kids.extend(objects); + list(b"grp ", kids) + }) + .collect(); + list(b"clpt", groups) +} + +/// The container argument (8005) naming clipped group `id` (R46), laid out as sample files lay it +/// out. +pub fn container(id: u32) -> (u32, Vec) { + (8005, [id, 1, 0, 1].iter().flat_map(|v| v.to_le_bytes()).collect()) +} + +/// The argument 8000 of a uniform transparency from version 13 (R47): one record of version 1300 +/// whose 117-byte body holds `percent` at byte 61 and `merge` at byte 77. +pub fn transparency(percent: f64, merge: u8) -> (u32, Vec) { + let mut body = vec![0; 117]; + body[61..69].copy_from_slice(&percent.to_le_bytes()); + body[77] = merge; + let mut out = 1300u32.to_le_bytes().to_vec(); + out.extend((body.len() as u32).to_le_bytes()); + out.extend(body); + (8000, out) +} + +/// A property list (R11, R12) of 12-byte color `color` and, when `name` is given, a type 8 +/// property with that library name. +pub fn properties(color: &[u8; 12], name: Option<&str>) -> Vec { + let mut out = vec![1]; + out.extend(12u32.to_le_bytes()); + out.extend(color); + if let Some(name) = name { + let mut body = vec![0; 16]; + body.extend((name.encode_utf16().count() as u32).to_le_bytes()); + body.extend(name.encode_utf16().flat_map(u16::to_le_bytes)); + out.push(8); + out.extend((body.len() as u32).to_le_bytes()); + out.extend(body); + } + out.extend([0, 0, 0, 0, 0]); + out +} + +/// `n` (an object, group or layer list) with its `flgs` chunk replaced by `flags` (R19). +pub fn flagged(n: Node, flags: [u8; 4]) -> Node { + match n { + Node::List(form, kids) => { + let kids = kids + .into_iter() + .map(|k| if matches!(&k, Node::Chunk(id, _) if id == b"flgs") { chunk(b"flgs", flags.to_vec()) } else { k }) + .collect(); + Node::List(form, kids) + } + chunk => chunk, + } +} + +/// A RIFF drawing of `version` (7 to 13) with a style table, a clipping container and a lens: a rectangle +/// that takes its fill and outline from its style, a container that clips two rectangles, one +/// with an outline behind the fill, a rectangle with a lens, a hidden and locked rectangle with a +/// winding flag and a uniform transparency, and a hidden group whose rectangle's outline names a +/// library color from version 13; compressed when `compress`. Before version 7, the [`sample`]. +pub fn feature_sample(version: u16, compress: bool) -> Vec { + if version < 700 { + return sample(version, false); + } + let v = V(version); + let black = color(2, [0, 0, 0, 100]); + let rect = |w: f64, extra: Vec<(u32, Vec)>, at: f64| { + let mut args = vec![(30, v.rect(w, w, 0.0))]; + args.extend(extra); + object(v, 1, &args, Some([1.0, 0.0, 0.0, 1.0, at, at])) + }; + let style = (200, 0x10u32.to_le_bytes().to_vec()); + let clipped = + vec![rect(30.0, vec![style.clone()], 10.0), rect(30.0, vec![(10, 3u32.to_le_bytes().to_vec()), (20, 1u32.to_le_bytes().to_vec())], -10.0)]; + // From version 13 outline 4 names a library color in a record of type 2 (R12). + let mut named = v.outline(4, Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }, &color(25, [7, 0, 100, 0]), &[]); + if version >= 1300 { + let props = properties(&color(5, [0, 0, 255, 0]), Some("Sky Blue")); + let mut record = 2u32.to_le_bytes().to_vec(); + record.extend((props.len() as u32).to_le_bytes()); + record.extend(props); + named.splice(4..4, record); + } + let doc = list( + b"doc ", + vec![ + mcfg(v, 612.0, 792.0), + list(b"filt", vec![chunk(b"fild", v.fill(1, &color(5, [0, 0, 255, 0])))]), + list( + b"otlt", + vec![ + chunk(b"outl", v.outline(2, Pen { line_type: 4, width: 2.0, cap: 1, join: 1 }, &black, &[3, 1])), + chunk(b"outl", v.outline(3, Pen { line_type: 0x12, width: 4.0, cap: 0, join: 0 }, &black, &[])), + chunk(b"outl", named), + ], + ), + stlt(v, &[(0x100, 1)], &[(0x200, 2)], &[Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }], true), + clpt(vec![(7, clipped)]), + ], + ); + let objects = vec![ + rect(20.0, vec![style.clone()], 0.0), + rect(40.0, vec![style.clone(), container(7)], 50.0), + rect(20.0, vec![style.clone(), (8000, vec![1, 0, 0, 0])], -50.0), + // Hidden and locked, filled nonzero, 25% transparent with merge mode 9 (R19, R47, R52). + flagged(rect(10.0, vec![style.clone(), (14001, vec![1, 0, 0, 0]), transparency(25.0, 9)], 80.0), [0x10, 1, 0, 0x08]), + list(b"grp ", vec![chunk(b"flgs", vec![0, 1, 0, 0x10]), rect(10.0, vec![(10, 4u32.to_le_bytes().to_vec())], -80.0)]), + ]; + let page = page(false, vec![layer(v, [0, 0, 0, 0x98], "Art", objects)]); + let mut body = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())]; + if compress { + body.push(cmpr(&[doc, page])); + } else { + body.extend([doc, page]); + } + riff(version, &body) +} + +/// A file of `version` holding `content` as the program of that version saves it: a RIFF file +/// before 14, then a package (R25, R26). +pub fn file_of(version: u16, content: Vec) -> Vec { + let mut body = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())]; + body.extend(content); + match version { + ..1400 => riff(version, &body), + 1400..1600 => package14(riff(version, &body), false), + _ => package16(version, &body, false, &[]), + } +} + +/// The document list and pages of the [`sample`] of `version`. +pub fn sample_content(version: u16) -> Vec { + let v = V(version); + // Before version 5 the sample's colors are CMYK in percent, model 1 (R36). + let (red, black) = + if version < 500 { (color4(1, [0, 100, 100, 0]), color4(1, [0, 0, 0, 100])) } else { (color(5, [0, 0, 255, 0]), color(2, [0, 0, 0, 100])) }; + let (round, none) = (Pen { line_type: 0, width: 2.0, cap: 1, join: 1 }, Pen { line_type: 1, width: 1.0, cap: 0, join: 0 }); + let mut settings = vec![mcfg(v, 612.0, 792.0)]; + // Version 3 keeps fills and outlines in the objects (R34, R35). + if version >= 400 { + settings.push(list(b"filt", vec![chunk(if version >= 700 { b"fild" } else { b"fill" }, v.fill(1, &red))])); + settings.push(list(b"otlt", vec![chunk(b"outl", v.outline(2, round, &black, &[])), chunk(b"outl", v.outline(3, none, &black, &[]))])); + } + let doc = list(b"doc ", settings); + // Fill 1 is red and 0 none; outline 2 is 2 pt with round caps and joins, 3 none. + let style = |fill: u32, outline: u32| { + if version >= 400 { + return vec![(20, fill.to_le_bytes().to_vec()), (10, outline.to_le_bytes().to_vec())]; + } + let fill = if fill == 1 { fill3(1, &color3(1, [0, 100, 100, 0])) } else { fill3(0, &[]) }; + vec![(20, fill), (10, outline3(if outline == 2 { round } else { none }, color3(1, [0, 0, 0, 100]), &[]))] + }; + let mut rect_args = style(1, 2); + rect_args.push((30, v.rect(100.0, 50.0, 5.0))); + let mut ellipse_args = style(1, 3); + ellipse_args.push((30, [v.coord(40.0), v.coord(-40.0), v.angle(0.0), v.angle(0.0), v.word(0)].concat())); + let mut curve_args = style(0, 2); + curve_args.push((30, v.points(&[(0.0, 0.0, 0x08), (50.0, 0.0, 0x40), (50.0, 20.0, 0xC0), (20.0, 50.0, 0xC0), (0.0, 50.0, 0x88)]))); + let mut arc_args = style(0, 2); + arc_args.push((30, [v.coord(30.0), v.coord(30.0), v.angle(0.0), v.angle(90.0), v.word(1)].concat())); + let side = POLYGON_SIDE; + let mut poly_args = style(1, 2); + poly_args.push((30, v.points(&[(0.0, side, 0x0C), (side * 0.587, side * 0.809, 0x44), (side * 0.951, side * 0.309, 0x44)]))); + let mut poly = if version >= 1300 { vec![] } else { vec![0; 4] }; + poly.extend(5u32.to_le_bytes()); + poly.extend([0; 8]); + if version >= 1300 { + poly.extend([0; 4]); + } + poly.extend(0.05f64.to_le_bytes()); + poly.extend(0.05f64.to_le_bytes()); + poly.extend([v.coord(0.0), v.coord(0.0)].concat()); + poly_args.push((11000, poly)); + let art = layer( + v, + [0, 0, 0, 0x98], + "Art", + vec![ + object(v, 1, &rect_args, Some([1.0, 0.0, 0.0, 1.0, -100.0, 100.0])), + object(v, 2, &ellipse_args, Some([1.0, 0.0, 0.0, 1.0, 50.0, -50.0])), + object(v, 3, &curve_args, None), + list(b"grp ", vec![chunk(b"flgs", vec![0, 0, 0, 0x10]), object(v, 0x14, &poly_args, None), object(v, 2, &arc_args, None)]), + object(v, 4, &[(30, [v.coord(0.0), v.coord(0.0)].concat())], None), + ], + ); + let mut guide = vec![0; 12]; + guide.extend((90_000_000i32).to_le_bytes()); + guide.extend([v.coord(36.0), v.coord(0.0), v.coord(36.0), v.coord(100.0), v.coord(36.0), v.coord(0.0)].concat()); + let guides = layer(v, [0x0a, 0, 1, 0x98], "Guides", vec![object(v, 0x16, &[(16000, guide)], None)]); + let desktop = + layer(v, [0x08, 0, 1, 0x98], "Desktop", vec![object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0))], Some([1.0, 0.0, 0.0, 1.0, 400.0, 0.0]))]); + let pages = vec![page(true, vec![guides, desktop]), page(false, vec![art])]; + std::iter::once(doc).chain(pages).collect() +} + +/// A drawing of `version` with one page of each kind of object this reader reads, a text object +/// it doesn't, a master page with a guideline and a desktop object; compressed (version 7 on) +/// when `compress`. +pub fn sample(version: u16, compress: bool) -> Vec { + let content = sample_content(version); + let mut body = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())]; + if compress { + body.push(cmpr(&content)); + } else { + body.extend(content); + } + riff(version, &body) +} + +/// The sample of `version` as the program of that version saves it: a RIFF file before 14, then +/// a package (R25, R26); `compress` compresses the RIFF stream before 16 and deflates the package +/// members. +pub fn sample_file(version: u16, compress: bool) -> Vec { + match version { + ..1400 => sample(version, compress), + 1400..1600 => package14(sample(version, compress), compress), + _ => { + // The full version chunk comes first from 16; the reader doesn't use it. + let fver: Vec = [u32::from(version), 1, 0, u32::from(version / 100)].iter().flat_map(|v| v.to_le_bytes()).collect(); + let mut body = vec![chunk(b"fver", fver), chunk(b"vrsn", version.to_le_bytes().to_vec())]; + body.extend(sample_content(version)); + package16(version, &body, compress, &[]) + } + } +} + +/// One member of a synthetic ZIP archive. +#[derive(Clone, Debug)] +pub struct Member { + pub name: String, + pub data: Vec, + pub deflate: bool, +} + +fn deflate(data: &[u8]) -> Vec { + let mut e = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default()); + let _ = e.write_all(data); + e.finish().unwrap_or_default() +} + +/// A ZIP archive of `members`, stored or deflated, with `comment` after the end record (R24). +pub fn zip(members: &[Member], comment: &[u8]) -> Vec { + let (mut out, mut dir) = (Vec::new(), Vec::new()); + for m in members { + let packed = if m.deflate { deflate(&m.data) } else { m.data.clone() }; + let method: u16 = if m.deflate { 8 } else { 0 }; + // Version needed, flags, method, time, date, CRC-32, packed and full sizes, name length. + let mut common = Vec::new(); + common.extend(20u16.to_le_bytes()); + common.extend(0u16.to_le_bytes()); + common.extend(method.to_le_bytes()); + common.extend([0; 4]); + common.extend(crc32fast::hash(&m.data).to_le_bytes()); + common.extend((packed.len() as u32).to_le_bytes()); + common.extend((m.data.len() as u32).to_le_bytes()); + common.extend((m.name.len() as u16).to_le_bytes()); + let at = out.len() as u32; + out.extend(0x0403_4b50u32.to_le_bytes()); + out.extend(&common); + out.extend(0u16.to_le_bytes()); + out.extend(m.name.as_bytes()); + out.extend(&packed); + dir.extend(0x0201_4b50u32.to_le_bytes()); + dir.extend(20u16.to_le_bytes()); + dir.extend(&common); + // Extra and comment lengths, disk, internal and external attributes, header offset. + dir.extend([0; 12]); + dir.extend(at.to_le_bytes()); + dir.extend(m.name.as_bytes()); + } + let dir_at = out.len() as u32; + let n = members.len() as u16; + out.extend(&dir); + out.extend(0x0605_4b50u32.to_le_bytes()); + out.extend([0; 4]); + out.extend(n.to_le_bytes()); + out.extend(n.to_le_bytes()); + out.extend((dir.len() as u32).to_le_bytes()); + out.extend(dir_at.to_le_bytes()); + out.extend((comment.len() as u16).to_le_bytes()); + out.extend(comment); + out +} + +/// A version 14 or 15 package: the RIFF file `riff` as `content/riffData.cdr` (R25). +pub fn package14(riff: Vec, deflate: bool) -> Vec { + zip(&[Member { name: "content/riffData.cdr".into(), data: riff, deflate }], b"") +} + +/// A version 16+ package of a drawing of `version` holding `children` (R26, R27): the chunk tree +/// in `content/root.dat`, each chunk body of more than 8 bytes moved to a data stream (the +/// document's and other chunks' to `data1.dat`, each page's to `page.dat`, each other list's +/// to a stream named after its form type) behind a redirect record, and shorter bodies kept in +/// theirs. Lists stay in the tree. `extra` members are added to the archive. +pub fn package16(version: u16, children: &[Node], deflate: bool, extra: &[Member]) -> Vec { + package16_with(version, children, deflate, extra, &[]) +} + +/// [`package16`], moving the lists whose form types are in `moved_lists` whole into their stream. +pub fn package16_with(version: u16, children: &[Node], deflate: bool, extra: &[Member], moved_lists: &[[u8; 4]]) -> Vec { + let mut members = package16_members(version, children, deflate, moved_lists); + members.extend(extra.iter().cloned()); + zip(&members, b"") +} + +/// The members of a [`package16_with`] archive. +pub fn package16_members(version: u16, children: &[Node], deflate: bool, moved_lists: &[[u8; 4]]) -> Vec { + let mut streams: Vec<(String, Vec)> = vec![("data1.dat".into(), Vec::new())]; + let mut body = form(version).to_vec(); + for c in children { + let s = match c { + Node::List(f, _) if *f != *b"doc " => { + let name = if *f == *b"page" { format!("page{}", streams.len()) } else { String::from_utf8_lossy(f).trim().to_string() }; + streams.push((format!("{name}.dat"), Vec::new())); + streams.len() - 1 + } + _ => 0, + }; + body.extend(redirected(c, s, &mut streams, moved_lists)); + } + let mut root = b"RIFF".to_vec(); + root.extend((body.len() as u32).to_le_bytes()); + root.extend(body); + let list: Vec = streams.iter().map(|(n, _)| n.clone()).collect(); + let mut members = vec![ + Member { name: "content/root.dat".into(), data: root, deflate }, + Member { name: "content/dataFileList.dat".into(), data: list.join("\n").into_bytes(), deflate }, + ]; + members.extend(streams.into_iter().map(|(n, data)| Member { name: format!("content/data/{n}"), data, deflate })); + members +} + +/// `n` laid out for `root.dat`, its bodies moved into stream `s`. +fn redirected(n: &Node, s: usize, streams: &mut [(String, Vec)], moved_lists: &[[u8; 4]]) -> Vec { + let mut out = Vec::new(); + match n { + Node::List(f, kids) if !moved_lists.contains(f) => { + let mut body = f.to_vec(); + body.extend(kids.iter().flat_map(|k| redirected(k, s, streams, moved_lists))); + put(&mut out, b"LIST", body.len() as u32, &body, body.len()); + } + _ => { + // A moved list's children are laid out in the stream by the same rule. + let (id, data) = match n { + Node::Chunk(id, data) => (*id, data.clone()), + Node::List(f, kids) => { + let mut body = f.to_vec(); + for k in kids { + body.extend(redirected(k, s, streams, moved_lists)); + } + (*b"LIST", body) + } + }; + let mut rec = Vec::new(); + if data.len() <= 8 && id != *b"LIST" { + rec.extend(u32::MAX.to_le_bytes()); + rec.extend((data.len() as u32).to_le_bytes()); + rec.extend(&data); + rec.resize(16, 0); + } else { + let Some((_, stream)) = streams.get_mut(s) else { return out }; + rec.extend((s as u32).to_le_bytes()); + rec.extend((data.len() as u32).to_le_bytes()); + rec.extend((stream.len() as u32).to_le_bytes()); + rec.extend(0u32.to_le_bytes()); + stream.extend(&data); + } + put(&mut out, &id, 16, &rec, 16); + } + } + out +} + +/// The radius the base curve of a polygon lies on, 1000 mm, in points (R18). +pub const POLYGON_SIDE: f64 = 1000.0 / 25.4 * 72.0; + +/// The shape of a drawn object in a file of version 1 or 2 (R43, R44), sizes in points. +#[derive(Clone, Debug)] +pub enum WlShape { + Rect { + w: f64, + h: f64, + radius: f64, + }, + /// The two angle fields are written as given. + Ellipse { + w: f64, + h: f64, + angles: (i16, i16), + }, + /// Points with their type bytes, as [`V::points`] takes them. + Curve(Vec<(f64, f64, u8)>), + Text, +} + +/// A drawn object's record of a version 1 file (R42, R43, R44): `shape` placed by `matrix` +/// `[a, b, c, d, e, f]` with offsets in points, a uniform fill of `fill` and an outline of a width +/// in points and a color. The record's point holds the matrix's x offset and its `ty` the y +/// offset. [`wl_file`] moves the fill and the shape to their places in a version 2 file. +pub fn wl_object(shape: WlShape, matrix: [f64; 6], fill: Option<[u8; 5]>, outline: Option<(f64, [u8; 5])>) -> Vec { + let v = V(300); + let (kind, body): (u8, Vec) = match shape { + WlShape::Rect { w, h, radius } => (0, [v.coord(w), v.coord(h), v.coord(radius), vec![0; 2]].concat()), + WlShape::Ellipse { w, h, angles } => (1, [v.coord(w), v.coord(h), angles.0.to_le_bytes().to_vec(), angles.1.to_le_bytes().to_vec()].concat()), + WlShape::Curve(points) => (2, v.points(&points)), + WlShape::Text => (3, vec![0; 30]), + }; + let mut r = vec![0u8; (114 + body.len()).max(118)]; + r[..4].copy_from_slice(&WL_RECORD_START); + r[26] = 0x40; + r[27] = 0x20; + let size = (r.len() - 32) as u16; + r[28..30].copy_from_slice(&size.to_le_bytes()); + let [a, b, c, d, e, f] = matrix; + r[32..34].copy_from_slice(&v.coord(e)); + let fixed = |x: f64| ((x * 65536.0).round() as i32).to_le_bytes(); + // a, b, tx, c, d, ty: x' = a x + b y + tx, y' = c x + d y + ty. + for (k, x) in [a, c, 0.0, b, d, f / 72.0 * 1000.0].into_iter().enumerate() { + r[36 + 4 * k..40 + 4 * k].copy_from_slice(&fixed(x)); + } + r[60] = kind; + if let Some((width, color)) = outline { + r[67] = 1; + r[68..70].copy_from_slice(&v.coord(width)); + r[74..79].copy_from_slice(&color); + } + if let Some(color) = fill { + r[94] = 1; + r[95..100].copy_from_slice(&color); + } + r[114..114 + body.len()].copy_from_slice(&body); + r +} + +/// The u32 that starts every record of a version 1 or 2 file (R42). +const WL_RECORD_START: [u8; 4] = 24u32.to_le_bytes(); + +/// A group or layer record of a version 1 or 2 file (R42): 28 bytes. +pub fn wl_group() -> Vec { + let mut r = vec![0u8; 28]; + r[..4].copy_from_slice(&WL_RECORD_START); + r[26] = 1; + r[27] = 0x60; + r +} + +/// A drawn object's record of a version 1 file laid out as in a version 2 file (R43): 11 more bytes +/// before the fill and 11 more before the shape. Group records stay as they are. +fn wl_v2_record(rec: &[u8]) -> Vec { + if rec.get(26).is_none_or(|flags| flags & 0x40 == 0) || rec.len() < 114 { + return rec.to_vec(); + } + let mut out = [&rec[..94], &[0; 11], &rec[94..114], &[0; 11], &rec[114..]].concat(); + let size = (out.len() - 32) as u16; + out[28..30].copy_from_slice(&size.to_le_bytes()); + out +} + +/// A file of version 1 or 2 (R40, R41): the header with `marker` (`e` for version 1, `l` or `m` +/// for version 2), a page of `page` points, the `records` and an empty font table. A version 1 +/// file's settings start after the header; a version 2 file's start further on, where a picture +/// lies in the files of that version, and its drawn objects are laid out as [`wl_v2_record`] says. +pub fn wl_file(marker: u8, page: (f64, f64), records: &[Vec]) -> Vec { + let v = V(300); + let settings = if marker == b'e' { 28u32 } else { 40 }; + let start = 64u32; + let mut out = vec![0u8; start as usize]; + out[..4].copy_from_slice(&[b'W', b'L', marker, 0]); + let (w, h) = page; + let page_box = settings as usize + 2; + out[page_box..page_box + 8].copy_from_slice(&[v.coord(-w / 2.0), v.coord(h / 2.0), v.coord(w / 2.0), v.coord(-h / 2.0)].concat()); + for r in records { + if marker == b'e' { + out.extend(r); + } else { + out.extend(wl_v2_record(r)); + } + } + let end = out.len() as u32; + out.extend([0; 2]); + let trailer = out.len() as u32; + for (k, offset) in [settings, start, end, trailer, trailer - 2].into_iter().enumerate() { + out[4 + 4 * k..8 + 4 * k].copy_from_slice(&offset.to_le_bytes()); + } + out +} + +/// A drawing of version 1 or 2 with a group record and one of each kind of object: a rounded +/// rectangle with a fill and an outline, an ellipse, a closed curve and a text object, front to +/// back. +pub fn wl_sample(marker: u8) -> Vec { + let (red, black) = (color3(1, [0, 100, 100, 0]), color3(1, [0, 0, 0, 100])); + let curve = vec![(0.0, 0.0, 0x08), (50.0, 0.0, 0x40), (50.0, 20.0, 0xC0), (20.0, 50.0, 0xC0), (0.0, 50.0, 0x88)]; + let records = [ + wl_object(WlShape::Rect { w: 100.0, h: 50.0, radius: 5.0 }, [1.0, 0.0, 0.0, 1.0, -100.0, 100.0], Some(red), Some((2.0, black))), + wl_group(), + wl_object(WlShape::Ellipse { w: 40.0, h: -40.0, angles: (0, 0) }, [1.0, 0.0, 0.0, 1.0, 50.0, -50.0], Some(red), None), + wl_object(WlShape::Curve(curve), [2.0, 0.0, 0.0, 2.0, 0.0, 0.0], None, Some((2.0, black))), + wl_object(WlShape::Text, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some(black), None), + ]; + wl_file(marker, (612.0, 792.0), &records) +} diff --git a/crates/cdr/src/synth_cmx.rs b/crates/cdr/src/synth_cmx.rs new file mode 100644 index 0000000000..c70fd8545c --- /dev/null +++ b/crates/cdr/src/synth_cmx.rs @@ -0,0 +1,287 @@ +//! Synthetic `.cmx` files for tests and fuzz seeds, built from the layouts in `PROVENANCE.md` (R53 +//! to R63). Not a `.cmx` writer: nothing checks that other programs open these files. + +/// A chunk: its id, a u32 size, the body and a pad byte after an odd body (R53). +pub fn chunk(id: &[u8; 4], body: &[u8]) -> Vec { + let mut out = id.to_vec(); + out.extend((body.len() as u32).to_le_bytes()); + out.extend(body); + if body.len() % 2 == 1 { + out.push(0); + } + out +} + +/// A `LIST` chunk of form `form`. +pub fn list(form: &[u8; 4], children: &[Vec]) -> Vec { + let mut body = form.to_vec(); + body.extend(children.concat()); + chunk(b"LIST", &body) +} + +/// The RIFF form `CMX1` around `children`. +pub fn riff(children: &[Vec]) -> Vec { + let mut body = b"CMX1".to_vec(); + body.extend(children.concat()); + chunk(b"RIFF", &body) +} + +/// The header (R54): `coord` is the coordinate size digit (`b'4'` or `b'2'`) and `meters` the size +/// of a coordinate unit. The header string and the system name, which the reader doesn't read, +/// are left as zeros. +pub fn cont(coord: u8, meters: f64) -> Vec { + let mut c = vec![0u8; 180]; + c[48] = b'2'; + c[52] = coord; + c[54] = b'2'; + c[64..72].copy_from_slice(&meters.to_le_bytes()); + chunk(b"cont", &c) +} + +/// A field: its tag, a u16 length counting the 3 header bytes, then `data` (R55). +pub fn field(tag: u8, data: &[u8]) -> Vec { + let mut f = vec![tag]; + f.extend(((data.len() + 3) as u16).to_le_bytes()); + f.extend(data); + f +} + +/// A field list: the fields, then 0xff (R55). +pub fn fields(fields: &[Vec]) -> Vec { + let mut l = fields.concat(); + l.push(0xff); + l +} + +/// A table chunk: a u16 count, then the entries (field lists) (R55). +pub fn table(id: &[u8; 4], entries: &[Vec]) -> Vec { + let mut d = (entries.len() as u16).to_le_bytes().to_vec(); + d.extend(entries.concat()); + chunk(id, &d) +} + +/// A color entry in the older form: the model and palette bytes in field 1, the values in field 2 +/// (R56). +pub fn color(model: u8, values: &[u8]) -> Vec { + fields(&[field(1, &[model, 5]), field(2, values)]) +} + +/// A color entry with a property list in field 10 whose color record (part 1) holds `model` and +/// the four value bytes `v` (R56). +pub fn color_record(model: u16, v: [u8; 4]) -> Vec { + color_record_named(model, v, None) +} + +/// A color entry as [`color_record`], with a name part (part 3: a u32 count and UTF-16 units) +/// after the color when `name` is given (R56). +pub fn color_record_named(model: u16, v: [u8; 4], name: Option<&str>) -> Vec { + let mut part = vec![1u8]; + part.extend(12u32.to_le_bytes()); + part.extend(model.to_le_bytes()); + part.extend(5u16.to_le_bytes()); + part.extend([0; 4]); + part.extend(v); + if let Some(name) = name { + let units: Vec = name.encode_utf16().collect(); + part.push(3); + part.extend((4 + 2 * units.len() as u32).to_le_bytes()); + part.extend((units.len() as u32).to_le_bytes()); + part.extend(units.iter().flat_map(|u| u.to_le_bytes())); + } + let mut rec = (part.len() as u32).to_le_bytes().to_vec(); + rec.extend(part); + fields(&[field(10, &rec)]) +} + +/// A pen entry (R57): the width in coordinate units, an aspect of 100 and no angle, with the +/// identity matrix. +pub fn pen(width: u32) -> Vec { + let mut d = width.to_le_bytes().to_vec(); + d.extend(100u16.to_le_bytes()); + d.extend(0i32.to_le_bytes()); + d.extend(1u16.to_le_bytes()); + fields(&[field(1, &d)]) +} + +/// A line type entry (R57): its flags and the caps (low 4 bits) and join (high 4 bits). +pub fn line_type(flags: u8, caps_join: u8) -> Vec { + fields(&[field(1, &[flags, caps_join])]) +} + +/// A dash pattern entry (R57): the lengths in outline widths. +pub fn dashes(lengths: &[u16]) -> Vec { + let mut d = (lengths.len() as u16).to_le_bytes().to_vec(); + d.extend(lengths.iter().flat_map(|l| l.to_le_bytes())); + fields(&[field(1, &d)]) +} + +/// An outline entry (R58): 1-based indexes of the line type, screen, color, arrowhead pair, pen and +/// dash pattern. +pub fn outline(parts: [u16; 6]) -> Vec { + fields(&[field(1, &parts.iter().flat_map(|p| p.to_le_bytes()).collect::>())]) +} + +/// The arrowhead pairs chunk (R59): a u16 count, then start and end (u16 each). +pub fn arrowheads(pairs: &[(u16, u16)]) -> Vec { + let mut d = (pairs.len() as u16).to_le_bytes().to_vec(); + for (s, e) in pairs { + d.extend(s.to_le_bytes()); + d.extend(e.to_le_bytes()); + } + chunk(b"rota", &d) +} + +/// An instruction in the short form: a u16 size counting the whole instruction, the code, the +/// body (R60). +pub fn instr(code: i16, body: &[u8]) -> Vec { + let mut i = ((body.len() + 4) as u16).to_le_bytes().to_vec(); + i.extend(code.to_le_bytes()); + i.extend(body); + i +} + +/// An instruction in the long form: 0xFFFF, a u32 size counting the whole instruction, the code, +/// the body (R60). +pub fn long_instr(code: i16, body: &[u8]) -> Vec { + let mut i = 0xFFFFu16.to_le_bytes().to_vec(); + i.extend(((body.len() + 8) as u32).to_le_bytes()); + i.extend(code.to_le_bytes()); + i.extend(body); + i +} + +/// Begin a page (R61), with its width and height in coordinate units in field 4 when given. +pub fn begin_page(size: Option<(u32, u32)>) -> Vec { + let mut f = vec![field(1, &[1, 0, 0, 0, 0, 0])]; + if let Some((w, h)) = size { + let mut d = w.to_le_bytes().to_vec(); + d.extend(h.to_le_bytes()); + f.push(field(4, &d)); + } + instr(9, &fields(&f)) +} + +/// Begin a page (R61) without a size of its own, with the drawing's left, top, right and bottom +/// edges in field 1. +pub fn begin_page_in_bounds(left: i32, top: i32, right: i32, bottom: i32) -> Vec { + let mut d = vec![1, 0, 0, 0, 0, 0]; + for v in [left, top, right, bottom] { + d.extend(v.to_le_bytes()); + } + instr(9, &fields(&[field(1, &d)])) +} + +/// Begin a layer (R62) named in 8-bit characters in field 1 from byte 12, and in UTF-16 in +/// field 4 when `wide` is given. +pub fn begin_layer(name: &str, wide: Option<&str>) -> Vec { + let mut d = vec![1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + d.extend((name.len() as u16).to_le_bytes()); + d.extend(name.bytes()); + let mut f = vec![field(1, &d)]; + if let Some(w) = wide { + let units: Vec = w.encode_utf16().collect(); + let mut d = (units.len() as u32).to_le_bytes().to_vec(); + d.extend(units.iter().flat_map(|u| u.to_le_bytes())); + f.push(field(4, &d)); + } + instr(11, &fields(&f)) +} + +pub fn end_layer() -> Vec { + instr(12, &[]) +} + +pub fn end_page() -> Vec { + instr(10, &[]) +} + +pub fn begin_group() -> Vec { + instr(13, &fields(&[field(1, &[0; 26])])) +} + +pub fn end_group() -> Vec { + instr(14, &[]) +} + +/// Rendering attributes (R63): a uniform fill of color `fill` and the outline `outline` (1-based +/// indexes; `None` leaves the part out of the mask), and `lens` sets the lens bit. +pub fn attrs(fill: Option, outline: Option, lens: bool) -> Vec { + let mask = u8::from(fill.is_some()) | (u8::from(outline.is_some()) << 1) | (u8::from(lens) << 2); + let mut a = vec![mask]; + if let Some(c) = fill { + let mut v = 1u16.to_le_bytes().to_vec(); + let mut uniform = c.to_le_bytes().to_vec(); + uniform.extend(0u16.to_le_bytes()); + v.extend(fields(&[field(1, &uniform)])); + a.extend(fields(&[field(1, &v)])); + } + if let Some(o) = outline { + a.extend(fields(&[field(1, &o.to_le_bytes())])); + } + a +} + +/// Rendering attributes with a fill of type `kind` and no settings of its own. +pub fn attrs_fill_type(kind: u16) -> Vec { + let mut a = vec![1u8]; + a.extend(fields(&[field(1, &kind.to_le_bytes())])); + a +} + +/// A curve (R62): `attrs`, then a u16 count, the points (i32 x, y) and their type bytes. +pub fn curve(attrs: &[u8], points: &[(i32, i32)], types: &[u8]) -> Vec { + let mut g = (points.len() as u16).to_le_bytes().to_vec(); + for (x, y) in points { + g.extend(x.to_le_bytes()); + g.extend(y.to_le_bytes()); + } + g.extend(types); + instr(67, &fields(&[field(1, attrs), field(2, &g), field(3, &[0; 16])])) +} + +/// A closed square of side `side` with its lower left corner at (`x`, `y`). +pub fn square(attrs: &[u8], x: i32, y: i32, side: i32) -> Vec { + curve(attrs, &[(x, y), (x + side, y), (x + side, y + side), (x, y + side), (x, y)], &[0x0c, 0x44, 0x44, 0x44, 0x48]) +} + +/// A `page` chunk of `instructions`. +pub fn page(instructions: &[Vec]) -> Vec { + chunk(b"page", &instructions.concat()) +} + +/// The tables of [`sample`]: colors red (RGB), black (CMYK in percent) and blue (a color record, +/// blue, green, red); pens of 0.5 mm and 1 mm; line types solid with round caps and joins, none, +/// and dashed behind the fill; one dash pattern; three outlines; one empty arrowhead pair. +pub fn tables() -> Vec> { + vec![ + table(b"rclr", &[color(5, &[255, 0, 0]), color(2, &[0, 0, 0, 100]), color_record(5, [255, 0, 0, 0])]), + table(b"rpen", &[pen(5_000), pen(10_000)]), + table(b"rott", &[line_type(2, 0x11), line_type(1, 0), line_type(2 | 4 | 8, 0x02)]), + table(b"rdot", &[dashes(&[3, 1])]), + table(b"rotl", &[outline([1, 1, 2, 1, 1, 1]), outline([2, 1, 2, 1, 1, 1]), outline([3, 1, 3, 1, 2, 1])]), + arrowheads(&[(0, 0)]), + ] +} + +/// One page of 210 x 297 mm with two layers: "Art" holds a red square outlined in black, then a +/// group of a square with no outline and a blue one with the dashed outline; "Top" holds a black +/// square drawn last. Units are 0.1 µm. +pub fn sample() -> Vec { + let p = page(&[ + begin_page(Some((2_100_000, 2_970_000))), + begin_layer("Art", None), + square(&attrs(Some(1), Some(1), false), -500_000, -500_000, 1_000_000), + begin_group(), + square(&attrs(Some(2), Some(2), false), 0, 0, 100_000), + square(&attrs(Some(3), Some(3), false), 200_000, 0, 100_000), + end_group(), + end_layer(), + begin_layer("Top", Some("Top")), + square(&attrs(Some(2), None, false), 0, 0, 10_000), + end_layer(), + end_page(), + ]); + let mut children = vec![cont(b'4', 1e-7), p]; + children.extend(tables()); + riff(&children) +} diff --git a/crates/cdr/src/wl.rs b/crates/cdr/src/wl.rs new file mode 100644 index 0000000000..bae22ba5a0 --- /dev/null +++ b/crates/cdr/src/wl.rs @@ -0,0 +1,358 @@ +//! Drawings of versions 1 and 2: the file before RIFF, which starts with `WL` (R40 to R44). A +//! header of offsets, the settings with the page's box, then one flat list of records: 28 bytes +//! for a group or a layer, and a longer record for each drawn object, which holds its matrix, fill, +//! outline and shape. The reader maps the rectangles, ellipses and curves onto one page with one +//! layer and keeps no groups. + +use crate::bytes::{Rd, u32_at}; +use crate::geometry; +use crate::layout::{self, Profile}; +use crate::limits::Budget; +use crate::model::{Cap, Drawing, Flags, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Shape}; +use crate::records::{self, coord, fixed}; +use crate::riff::push; +use crate::{Error, Warning}; + +/// The header: the signature, a marker byte, a zero and five u32 offsets (R40). +const HEADER: usize = 28; +/// The marker bytes read after `WL` (R40): `e` for version 1, `l` and `m` for version 2. +const MARKERS: [u8; 3] = *b"elm"; +/// Where the page's box lies after the start of the settings (R41). +const PAGE_BOX: usize = 2; +/// The bytes of a group or layer record (R42). +const GROUP: usize = 28; +/// The u32 that starts every record (R42). +const RECORD_START: u32 = 24; +/// The flag bit, in byte 26, of a drawn object (R42). +const DRAWN: u8 = 0x40; +/// The bytes after a drawn object's body size (R42). +const AFTER_BODY: usize = 32; +/// Where a drawn object's fields lie (R43, R44). +const POINT: usize = 32; +const KIND: usize = 60; +const OUTLINED: usize = 67; +const OUTLINE_WIDTH: usize = 68; +const OUTLINE_COLOR: usize = 74; + +/// Where a drawn object's fill and shape lie, which differs between the markers (R43, R44). +#[derive(Clone, Copy)] +struct Fields { + fill_kind: usize, + shape: usize, +} + +impl Fields { + fn of(marker: u8) -> Self { + if marker == b'e' { Fields { fill_kind: 94, shape: 114 } } else { Fields { fill_kind: 105, shape: 136 } } + } + + /// The least a drawn object takes: its fixed fields and the 4 bytes of a shape's size. + fn least(self) -> usize { + self.shape + 4 + } +} +/// Object types (R43). +const RECTANGLE: u8 = 0; +const ELLIPSE: u8 = 1; +const CURVE: u8 = 2; +const TEXT: u8 = 3; + +/// Where the settings start, and where the records start and end, when `b` has a `WL` header +/// whose offsets fit the file. +fn header(b: &[u8]) -> Option<(usize, usize, usize)> { + if b.get(..2)? != b"WL" || !MARKERS.contains(b.get(2)?) || *b.get(3)? != 0 { + return None; + } + let (settings, start, end) = (u32_at(b, 4)? as usize, u32_at(b, 8)? as usize, u32_at(b, 12)? as usize); + (settings >= HEADER && settings <= start && start <= end && end <= b.len()).then_some((settings, start, end)) +} + +/// Does `b` start like a drawing of version 1 or 2? The two letters alone are not enough: the +/// marker byte, the zero after it and the record offsets must fit too. +pub(crate) fn is_wl(b: &[u8]) -> bool { + header(b).is_some() +} + +pub(crate) fn drawing(b: &[u8], budget: &mut Budget) -> Result { + let (settings, start, end) = header(b).ok_or(Error::NotCdr)?; + let marker = b.get(2).copied().ok_or(Error::NotCdr)?; + let fields = Fields::of(marker); + // Lengths are i16 in 1/1000 inch, as in version 3 (R5). + let p = layout::for_version(layout::OLDEST_RIFF).ok_or(Error::NotCdr)?; + let mut warn = Vec::new(); + let mut objects = Vec::new(); + let mut at = start; + // Every step takes at least a group record's bytes, so the file's size bounds the steps. + while end - at >= GROUP { + budget.take_chunk()?; + // A record that doesn't start as records do is past one whose length isn't known. + if u32_at(b, at) != Some(RECORD_START) { + break; + } + if b.get(at + 26).is_none_or(|flags| flags & DRAWN == 0) { + at += GROUP; + continue; + } + // A drawn object of another type than rectangle, ellipse, curve and text doesn't say its + // length in the same way, so the records after it can't be found. + if b.get(at + KIND).is_none_or(|kind| *kind > TEXT) { + push(&mut warn, Warning::UnsupportedObjects); + at = end; + break; + } + let len = Rd::at(b, at + 28).u16().map_or(0, |body| usize::from(body) + AFTER_BODY); + let Some(rec) = b.get(at..at + len).filter(|_| len >= fields.least() && at + len <= end) else { + push(&mut warn, Warning::Damaged); + at = end; + break; + }; + at += len; + if !budget.take_object() { + push(&mut warn, Warning::TooDeep); + at = end; + break; + } + objects.extend(object(rec, fields, &p, budget, &mut warn)); + } + if at != end { + push(&mut warn, Warning::Damaged); + } + let version = if marker == b'e' { 100 } else { 200 }; + let layer = Layer { name: String::new(), kind: LayerKind::Drawing, flags: Flags::default(), objects, guides: Vec::new() }; + let pages = vec![Page { size: None, layers: vec![layer] }]; + Ok(Drawing { version, page_size: page_box(b, settings, &p), pages, master: Vec::new(), guides: Vec::new(), warnings: warn }) +} + +/// The page's size from its box (R41): left, top, right and bottom around the page's centre. +fn page_box(b: &[u8], settings: usize, p: &Profile) -> Option<(f64, f64)> { + let mut r = Rd::at(b, settings + PAGE_BOX); + let (left, top, right, bottom) = (coord(&mut r, p)?, coord(&mut r, p)?, coord(&mut r, p)?, coord(&mut r, p)?); + let (w, h) = ((right - left).abs(), (top - bottom).abs()); + (w > 0.0 && h > 0.0).then_some((w, h)) +} + +/// One drawn object's record (R43, R44): a shape, or `None` with a warning for text, for an object +/// of another type and for a shape that can't be read. +fn object(rec: &[u8], fields: Fields, p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option { + // A curve left out at the coordinate limit is not damage. + budget.coordinates_refused(); + let read = shape(rec, fields, p, budget, warn); + if read.is_none() && !budget.coordinates_refused() { + push(warn, Warning::Damaged); + } + read?.map(|s| Object::Shape(Box::new(s))) +} + +/// The shape of a record. The outer `None` is a record that can't be read; the inner one an object +/// the reader leaves out, with its warning. +fn shape(rec: &[u8], fields: Fields, p: &Profile, budget: &mut Budget, warn: &mut Vec) -> Option> { + let k = p.unit(); + let mut r = Rd::at(rec, POINT); + let (x, y) = (f64::from(r.i16()?), f64::from(r.i16()?)); + // x' = a x + b y + tx + x of the point, y' = c x + d y + ty + y of the point. + let (a, b, tx, c, d, ty) = (fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?); + let matrix = Matrix([a, c, b, d, (tx + x) * k, (ty + y) * k]); + let body = rec.get(fields.shape..)?; + let geometry = match *rec.get(KIND)? { + RECTANGLE => rect(body, p)?, + ELLIPSE => { + let mut s = Rd::new(body); + let (w, h) = (coord(&mut s, p)?, coord(&mut s, p)?); + // Two angles follow. No source confirms how they make an arc, so an ellipse whose + // angles differ is left out; one whose angles are missing is damage. + let (from, to) = (s.i16()?, s.i16()?); + if from != to { + push(warn, Warning::UnsupportedObjects); + return Some(None); + } + Geometry::Ellipse { w, h } + } + CURVE => Geometry::Path(geometry::point_list(body, p, budget, warn)?), + _ => { + push(warn, Warning::UnsupportedObjects); + return Some(None); + } + }; + let color_at = |at: usize, warn: &mut Vec| Some(records::color5(rec.get(at..at + 5)?.try_into().ok()?, warn)); + let fill = match *rec.get(fields.fill_kind)? { + 0 => None, + 1 => Some(color_at(fields.fill_kind + 1, warn)?), + _ => { + push(warn, Warning::UnsupportedFills); + None + } + }; + let outline = if *rec.get(OUTLINED)? != 0 { + let width = f64::from(Rd::at(rec, OUTLINE_WIDTH).u16()?) * k; + Some(Outline { + width, + color: color_at(OUTLINE_COLOR, warn)?, + cap: Cap::Butt, + join: Join::Miter, + dashes: Vec::new(), + behind_fill: false, + scale_with: false, + }) + } else { + None + }; + Some(Some(Shape::new(geometry, matrix, fill, outline))) +} + +/// A rectangle (R44): its width and height, then a corner radius, which is kept when it is at most +/// half the shorter side. +fn rect(body: &[u8], p: &Profile) -> Option { + let mut r = Rd::new(body); + let (w, h) = (coord(&mut r, p)?, coord(&mut r, p)?); + let radius = coord(&mut r, p).filter(|v| *v > 0.0 && *v <= w.abs().min(h.abs()) / 2.0).unwrap_or(0.0); + Some(Geometry::Rect { w, h, radii: [radius; 4] }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Limits; + use crate::model::Color; + use crate::synth::{self, WlShape}; + + fn read(b: &[u8]) -> Result { + drawing(b, &mut Budget::new(Limits::default())) + } + + #[test] + fn the_header_is_taken_only_when_its_offsets_fit() { + let file = synth::wl_file(b'e', (612.0, 792.0), &[synth::wl_group()]); + assert!(is_wl(&file)); + // The two letters, a marker and a zero are not enough. + assert!(!is_wl(b"WLe\0")); + assert!(!is_wl(b"WLe\0 and then some text that is long enough to hold offsets")); + let with = |at: usize, v: u32| { + let mut f = file.clone(); + f[at..at + 4].copy_from_slice(&v.to_le_bytes()); + f + }; + // Records that start inside the header, start after their end, or end past the file. + assert!(!is_wl(&with(8, 27))); + assert!(!is_wl(&with(8, file.len() as u32))); + assert!(!is_wl(&with(12, file.len() as u32 + 1))); + // Settings that start inside the header or after the records. + assert!(!is_wl(&with(4, 27))); + assert!(!is_wl(&with(4, 65))); + let mut other = file.clone(); + other[2] = b'x'; + assert!(!is_wl(&other)); + // No sample shows the marker `d`, so it is not taken. + other[2] = b'd'; + assert!(!is_wl(&other)); + for marker in *b"lm" { + assert!(is_wl(&synth::wl_file(marker, (612.0, 792.0), &[synth::wl_group()]))); + } + other[2] = b'e'; + other[3] = 1; + assert!(!is_wl(&other)); + } + + #[test] + fn a_version_2_file_keeps_its_page_box_fill_and_shape_where_that_version_puts_them() { + let (red, black) = ([1, 0, 100, 100, 0], [1, 0, 0, 0, 100]); + let rect = synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 9.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some(red), Some((2.0, black))); + for marker in *b"elm" { + let file = synth::wl_file(marker, (720.0, 504.0), std::slice::from_ref(&rect)); + // Version 2 files start their settings after a picture, not after the header. + assert_eq!(u32_at(&file, 4) == Some(28), marker == b'e'); + let d = read(&file).unwrap(); + let near = |a: f64, b: f64| (a - b).abs() < 0.02; + assert_eq!((d.version, d.warnings.clone()), (if marker == b'e' { 100 } else { 200 }, vec![])); + assert!(d.page_size.is_some_and(|(w, h)| near(w, 720.0) && near(h, 504.0)), "{:?}", d.page_size); + let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!("group") }; + assert!( + matches!(s.geometry, Geometry::Rect { w, h, radii } if near(w, 72.0) && near(h, 36.0) && near(radii[0], 9.0)), + "{}", + marker as char + ); + assert_eq!(s.fill, Some(Color::Cmyk([0.0, 1.0, 1.0, 0.0])), "{}", marker as char); + assert!(s.outline.as_ref().is_some_and(|o| near(o.width, 2.0) && o.color == Color::Cmyk([0.0, 0.0, 0.0, 1.0])), "{}", marker as char); + } + } + + #[test] + fn a_drawn_object_is_marked_by_its_flag_bit() { + let rect = synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], None, None); + let mut file = synth::wl_file(b'l', (612.0, 792.0), &[rect]); + // Files with the marker `l` set another flag bit beside it. + file[64 + 26] = 0xc0; + let d = read(&file).unwrap(); + assert_eq!((d.pages[0].layers[0].objects.len(), d.warnings), (1, vec![])); + } + + #[test] + fn the_walk_stops_where_records_can_no_longer_be_found() { + let unit = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + let rect = || synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, unit, None, None); + // An object of another type doesn't give its length in the same way. + let mut other = rect(); + other[KIND] = 0xff; + let d = read(&synth::wl_file(b'm', (612.0, 792.0), &[rect(), other, rect()])).unwrap(); + assert_eq!((d.pages[0].layers[0].objects.len(), d.warnings), (1, vec![Warning::UnsupportedObjects])); + // A record that doesn't start as records do. + let mut lost = rect(); + lost[0] = 0x84; + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[rect(), lost, rect()])).unwrap(); + assert_eq!((d.pages[0].layers[0].objects.len(), d.warnings), (1, vec![Warning::Damaged])); + } + + #[test] + fn a_rectangle_keeps_a_radius_of_at_most_half_its_shorter_side() { + let p = layout::for_version(300).unwrap(); + let body = |radius: i16| [1000i16, 500, radius].iter().flat_map(|v| v.to_le_bytes()).collect::>(); + let radius_of = |b: &[u8]| match rect(b, &p) { + Some(Geometry::Rect { w, h, radii }) if (w - 72.0).abs() < 1e-9 && (h - 36.0).abs() < 1e-9 => radii[0], + other => panic!("{other:?}"), + }; + assert!((radius_of(&body(200)) - 14.4).abs() < 1e-9); + for radius in [300, -5, 0] { + assert_eq!(radius_of(&body(radius)), 0.0, "{radius}"); + } + // A record that ends after the size has square corners. + assert_eq!(radius_of(&body(200)[..4]), 0.0); + assert_eq!(rect(&body(200)[..3], &p), None); + } + + #[test] + fn a_record_shorter_than_its_fields_ends_the_walk_as_damage() { + let rect = synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some([1, 0, 0, 0, 100]), None); + let mut short = rect.clone(); + // A body size that leaves less than the fixed fields. + short[28..30].copy_from_slice(&((Fields::of(b'e').least() - AFTER_BODY - 1) as u16).to_le_bytes()); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[rect.clone(), short, rect])).unwrap(); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); + assert_eq!(d.warnings, vec![Warning::Damaged]); + } + + #[test] + fn an_ellipse_without_its_angles_is_damage() { + let ellipse = + synth::wl_object(WlShape::Ellipse { w: 72.0, h: 36.0, angles: (0, 0) }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some([1, 0, 0, 0, 100]), None); + let mut cut = ellipse.clone(); + // A body size that ends the record after the ellipse's width and height. + cut[28..30].copy_from_slice(&((Fields::of(b'e').least() - AFTER_BODY) as u16).to_le_bytes()); + cut.truncate(Fields::of(b'e').least()); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[ellipse, cut])).unwrap(); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); + assert_eq!(d.warnings, vec![Warning::Damaged]); + } + + #[test] + fn fill_types_other_than_uniform_and_unknown_inks_are_named() { + let mut textured = + synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some([0, 9, 0, 50, 0]), None); + let d = read(&synth::wl_file(b'm', (612.0, 792.0), std::slice::from_ref(&textured))).unwrap(); + let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!("group") }; + assert_eq!(s.fill, Some(Color::Spot { name: "Spot 0:9".into(), tint: 0.5, look: None })); + assert_eq!((d.version, d.warnings), (200, vec![Warning::SpotLooks])); + textured[Fields::of(b'e').fill_kind] = 5; + let d = read(&synth::wl_file(b'm', (612.0, 792.0), &[textured])).unwrap(); + let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!("group") }; + assert_eq!((s.fill.clone(), d.warnings), (None, vec![Warning::UnsupportedFills])); + } +} diff --git a/crates/cdr/src/zip.rs b/crates/cdr/src/zip.rs new file mode 100644 index 0000000000..67994192a0 --- /dev/null +++ b/crates/cdr/src/zip.rs @@ -0,0 +1,308 @@ +//! The ZIP archives of `.cdr` drawings from version 14 on (R24): the central directory, then stored +//! and deflated members read on request. Archives that span disks, ZIP64 archives and encrypted +//! members are refused; so are directories whose members overlap or repeat a name. + +use std::borrow::Cow; +use std::io::Read as _; + +use crate::Error; +use crate::bytes::Rd; + +/// End of central directory record: signature and fixed length. +const END: u32 = 0x0605_4b50; +const END_LEN: usize = 22; +/// The longest archive comment, which the end record may be followed by. +const MAX_COMMENT: usize = 0xFFFF; +/// ZIP64 end of central directory locator, 20 bytes before the end record when present. +const ZIP64_LOCATOR: u32 = 0x0706_4b50; +/// Central directory header: signature and fixed length. +const CENTRAL: u32 = 0x0201_4b50; +const CENTRAL_LEN: usize = 46; +/// Local file header: signature and fixed length. +const LOCAL: u32 = 0x0403_4b50; +const LOCAL_LEN: usize = 30; +/// General purpose flag bit 0: the member is encrypted. +const ENCRYPTED: u16 = 1; +const STORED: u16 = 0; +const DEFLATED: u16 = 8; +/// What members packed by another method are refused as. +const OTHER_METHODS: &str = "package compression methods other than storing and deflate"; + +/// One member, as the central directory and its local header give it. +#[derive(Clone, Copy, Debug)] +struct Entry<'a> { + name: &'a [u8], + flags: u16, + method: u16, + crc: u32, + packed: usize, + size: usize, + /// Where its local header starts and where its packed bytes start. + header: usize, + data: usize, +} + +/// An archive's directory over its bytes. +#[derive(Debug)] +pub(crate) struct Archive<'a> { + bytes: &'a [u8], + entries: Vec>, + /// The entries in name order, for lookups. + by_name: Vec, +} + +/// Does `bytes` start with a local file header? +pub(crate) fn is_zip(bytes: &[u8]) -> bool { + bytes.starts_with(b"PK\x03\x04") +} + +impl<'a> Archive<'a> { + /// The directory of `bytes`, holding at most `max_entries` members. + pub(crate) fn open(bytes: &'a [u8], max_entries: usize) -> Result { + let end = find_end(bytes).ok_or(Error::Damaged("package directory"))?; + if end >= 20 && Rd::at(bytes, end - 20).u32() == Some(ZIP64_LOCATOR) { + return Err(Error::Unsupported("ZIP64 packages")); + } + let mut r = Rd::at(bytes, end + 4); + let dir = || Error::Damaged("package directory"); + let (disk, dir_disk) = (r.u16().ok_or_else(dir)?, r.u16().ok_or_else(dir)?); + let (on_disk, total) = (r.u16().ok_or_else(dir)?, r.u16().ok_or_else(dir)?); + let (dir_len, dir_at) = (r.u32().ok_or_else(dir)?, r.u32().ok_or_else(dir)?); + if total == u16::MAX || dir_len == u32::MAX || dir_at == u32::MAX { + return Err(Error::Unsupported("ZIP64 packages")); + } + if disk != 0 || dir_disk != 0 || on_disk != total { + return Err(Error::Unsupported("packages split across files")); + } + let total = usize::from(total); + if total > max_entries { + return Err(Error::Limit("package member count")); + } + let (dir_at, dir_len) = (dir_at as usize, dir_len as usize); + let dir_end = dir_at.checked_add(dir_len).filter(|&e| e <= end).ok_or_else(dir)?; + let mut r = Rd::at(bytes, dir_at); + let mut entries = Vec::with_capacity(total); + for _ in 0..total { + let e = central_entry(bytes, &mut r, dir_end)?; + entries.push(e); + } + // Each member's bytes end before the next member's header and before the directory. + let mut order: Vec<&Entry> = entries.iter().collect(); + order.sort_unstable_by_key(|e| e.header); + for (i, e) in order.iter().enumerate() { + let stop = order.get(i + 1).map_or(dir_at, |n| n.header); + if e.data.checked_add(e.packed).is_none_or(|x| x > stop) { + return Err(Error::Damaged("package members overlap")); + } + } + let mut by_name: Vec = (0..entries.len()).collect(); + by_name.sort_unstable_by_key(|&i| entries.get(i).map(|e| e.name)); + let name = |i: &usize| entries.get(*i).map(|e| e.name); + if by_name.windows(2).any(|w| name(&w[0]) == name(&w[1])) { + return Err(Error::Damaged("package member named twice")); + } + Ok(Archive { bytes, entries, by_name }) + } + + /// The member named `name`. + pub(crate) fn find(&self, name: &[u8]) -> Option { + let at = self.by_name.binary_search_by(|&i| self.entries.get(i).map(|e| e.name).cmp(&Some(name))).ok()?; + self.by_name.get(at).copied() + } + + /// The size member `i`'s directory entry gives. + pub(crate) fn size(&self, i: usize) -> usize { + self.entries.get(i).map_or(0, |e| e.size) + } + + /// How many members the archive holds. + pub(crate) fn count(&self) -> usize { + self.entries.len() + } + + /// The bytes reading member `i` may inflate: its stated size when it is deflated, else 0. + pub(crate) fn inflate_cost(&self, i: usize) -> usize { + self.entries.get(i).filter(|e| e.method == DEFLATED).map_or(0, |e| e.size) + } + + /// An error when member `i` is encrypted or packed by a method other than storing or deflate. + pub(crate) fn check(&self, i: usize) -> Result<(), Error> { + let e = self.entries.get(i).ok_or(Error::Damaged("package member"))?; + if e.flags & ENCRYPTED != 0 { + return Err(Error::Unsupported("encrypted packages")); + } + if e.method != STORED && e.method != DEFLATED { + return Err(Error::Unsupported(OTHER_METHODS)); + } + Ok(()) + } + + /// Member `i`'s bytes when they come to at most `limit`, and a deflated member's when they + /// also come to at most `inflate_left`. A stored member is borrowed; a deflated one inflates to + /// at most its stated size plus one byte, so a member that inflates past what it states stops + /// there. The length and CRC-32 must match the directory's. + pub(crate) fn read(&self, i: usize, limit: usize, inflate_left: usize) -> Result, Error> { + self.check(i)?; + let e = self.entries.get(i).ok_or(Error::Damaged("package member"))?; + if e.size > limit { + return Err(Error::Limit("package member size")); + } + if e.method == DEFLATED && e.size > inflate_left { + return Err(Error::Limit("inflated size")); + } + let packed = self.bytes.get(e.data..e.data + e.packed).ok_or(Error::Damaged("package member"))?; + let out: Cow<'a, [u8]> = match e.method { + STORED if e.packed == e.size => Cow::Borrowed(packed), + STORED => return Err(Error::Damaged("package member")), + DEFLATED => { + let mut out = Vec::new(); + let got = flate2::read::DeflateDecoder::new(packed) + .take(e.size as u64 + 1) + .read_to_end(&mut out) + .map_err(|_| Error::Damaged("package member"))?; + if got != e.size { + return Err(Error::Damaged("package member")); + } + Cow::Owned(out) + } + _ => return Err(Error::Unsupported(OTHER_METHODS)), + }; + if crc32fast::hash(&out) != e.crc { + return Err(Error::Damaged("package member")); + } + Ok(out) + } +} + +/// Where the end of central directory record starts: searched back from the end over at most the +/// longest comment, among the records whose comment reaches exactly to the end the first that +/// names members in a directory before it, else the first. A comment or a member may hold bytes +/// that look like an empty archive's end record. +fn find_end(bytes: &[u8]) -> Option { + let last = bytes.len().checked_sub(END_LEN)?; + let first = last.saturating_sub(MAX_COMMENT); + let mut found = None; + for at in (first..=last).rev() { + let mut r = Rd::at(bytes, at); + if r.u32() != Some(END) || r.skip(6).is_none() { + continue; + } + let (total, dir_len, dir_at, comment) = (r.u16(), r.u32(), r.u32(), r.u16()); + if !comment.is_some_and(|c| at + END_LEN + usize::from(c) == bytes.len()) { + continue; + } + let names_members = total.is_some_and(|t| t > 0) + && dir_len.zip(dir_at).is_some_and(|(len, dir)| { + (dir as usize).checked_add(len as usize).is_some_and(|e| e <= at) && Rd::at(bytes, dir as usize).u32() == Some(CENTRAL) + }); + if names_members { + return Some(at); + } + found = found.or(Some(at)); + } + found +} + +/// The central directory entry at `r` (before `dir_end`) and its local header. +fn central_entry<'a>(bytes: &'a [u8], r: &mut Rd<'a>, dir_end: usize) -> Result, Error> { + let dir = || Error::Damaged("package directory"); + if r.pos().checked_add(CENTRAL_LEN).is_none_or(|e| e > dir_end) || r.u32() != Some(CENTRAL) { + return Err(dir()); + } + r.skip(4).ok_or_else(dir)?; + let flags = r.u16().ok_or_else(dir)?; + let method = r.u16().ok_or_else(dir)?; + r.skip(4).ok_or_else(dir)?; + let crc = r.u32().ok_or_else(dir)?; + let (packed, size) = (r.u32().ok_or_else(dir)?, r.u32().ok_or_else(dir)?); + let name_len = usize::from(r.u16().ok_or_else(dir)?); + let extra_len = usize::from(r.u16().ok_or_else(dir)?); + let comment_len = usize::from(r.u16().ok_or_else(dir)?); + let disk = r.u16().ok_or_else(dir)?; + r.skip(6).ok_or_else(dir)?; + let header = r.u32().ok_or_else(dir)?; + if packed == u32::MAX || size == u32::MAX || header == u32::MAX { + return Err(Error::Unsupported("ZIP64 packages")); + } + if disk != 0 { + return Err(Error::Unsupported("packages split across files")); + } + let name = r.bytes(name_len).ok_or_else(dir)?; + r.skip(extra_len).and_then(|()| r.skip(comment_len)).ok_or_else(dir)?; + if r.pos() > dir_end { + return Err(dir()); + } + // The local header repeats the name; its own extra field may differ in length. + let header = header as usize; + let mut l = Rd::at(bytes, header); + let local = || Error::Damaged("package member header"); + if l.u32() != Some(LOCAL) { + return Err(local()); + } + // The signature, 22 bytes, then the name and extra field lengths. + l.skip(LOCAL_LEN - 8).ok_or_else(local)?; + let (local_name, local_extra) = (usize::from(l.u16().ok_or_else(local)?), usize::from(l.u16().ok_or_else(local)?)); + if l.bytes(local_name) != Some(name) { + return Err(local()); + } + l.skip(local_extra).ok_or_else(local)?; + Ok(Entry { name, flags, method, crc, packed: packed as usize, size: size as usize, header, data: l.pos() }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::synth::{Member, zip}; + + fn stored(name: &str, data: &[u8]) -> Member { + Member { name: name.into(), data: data.to_vec(), deflate: false } + } + + #[test] + fn stored_and_deflated_members_read_back() { + let bytes = zip(&[stored("a", b"hello"), Member { name: "b".into(), data: vec![7; 5000], deflate: true }], b""); + let a = Archive::open(&bytes, 10).unwrap(); + assert!(matches!(a.read(a.find(b"a").unwrap(), 100, 100).unwrap(), Cow::Borrowed(b"hello"))); + assert_eq!(a.read(a.find(b"b").unwrap(), 5000, 5000).unwrap().as_ref(), &[7; 5000][..]); + assert_eq!(a.read(a.find(b"b").unwrap(), 4999, 5000), Err(Error::Limit("package member size"))); + assert_eq!(a.find(b"c"), None); + // What is left to inflate holds back deflated members only. + assert_eq!(a.read(a.find(b"b").unwrap(), 5000, 4999), Err(Error::Limit("inflated size"))); + assert!(a.read(a.find(b"a").unwrap(), 100, 0).is_ok()); + } + + #[test] + fn the_end_record_is_found_behind_a_comment() { + let bytes = zip(&[stored("a", b"x")], &[b'c'; 300]); + assert!(Archive::open(&bytes, 10).is_ok()); + // A comment longer than the record says leaves no end record to find. + let mut cut = bytes.clone(); + cut.push(0); + assert_eq!(Archive::open(&cut, 10).unwrap_err(), Error::Damaged("package directory")); + // A comment that ends in bytes like an empty archive's end record: the record that names + // members in a directory is the archive's. + let mut fake = END.to_le_bytes().to_vec(); + fake.resize(END_LEN, 0); + let bytes = zip(&[stored("a", b"x")], &fake); + let a = Archive::open(&bytes, 10).unwrap(); + assert_eq!(a.count(), 1); + } + + #[test] + fn a_member_whose_crc_or_length_is_wrong_is_damage() { + let bytes = zip(&[Member { name: "a".into(), data: vec![1; 64], deflate: true }], b""); + let a = Archive::open(&bytes, 10).unwrap(); + // The directory's CRC-32 sits 16 bytes into its entry. + let dir_at = bytes.windows(4).position(|w| w == CENTRAL.to_le_bytes()).unwrap(); + let mut bad = bytes.clone(); + bad[dir_at + 16] ^= 1; + let b = Archive::open(&bad, 10).unwrap(); + assert_eq!(b.read(0, 1000, 1000).unwrap_err(), Error::Damaged("package member")); + // A stated size one short: the inflate runs past it. + let mut short = bytes.clone(); + short[dir_at + 24] -= 1; + let s = Archive::open(&short, 10).unwrap(); + assert_eq!(s.read(0, 1000, 1000).unwrap_err(), Error::Damaged("package member")); + assert!(a.read(0, 1000, 1000).is_ok()); + } +} diff --git a/crates/cdr/tests/it/bench.rs b/crates/cdr/tests/it/bench.rs new file mode 100644 index 0000000000..6ec024423a --- /dev/null +++ b/crates/cdr/tests/it/bench.rs @@ -0,0 +1,65 @@ +//! Read time of a large synthetic drawing. Run with +//! `cargo test --release -p vectorcraft-cdr --test it bench -- --ignored --nocapture`. + +use vectorcraft_cdr::synth::{self, V, chunk, list}; +use vectorcraft_cdr::{Limits, read}; + +/// A version 13 drawing of `n` curves of 22 points each, filled and outlined, compressed when +/// `compress`. +fn many_curves(n: usize, compress: bool) -> Vec { + let v = V(1300); + let red = synth::color(5, [0, 0, 255, 0]); + let black = synth::color(2, [0, 0, 0, 100]); + let styles = list( + b"doc ", + vec![ + synth::mcfg(v, 612.0, 792.0), + list(b"filt", vec![chunk(b"fild", v.fill(1, &red))]), + list(b"otlt", vec![chunk(b"outl", v.outline(2, synth::Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }, &black, &[]))]), + ], + ); + let objects: Vec<_> = (0..n) + .map(|i| { + let o = (i % 500) as f64; + // A move, then curves of two control points and an end point each. + let kind = |k: i32| { + if k == 0 { + 0x08 + } else if k % 3 == 0 { + 0x80 + } else { + 0xC0 + } + }; + let pts: Vec<(f64, f64, u8)> = (0..22).map(|k| (o + f64::from(k), o + f64::from(k % 5), kind(k))).collect(); + let args = vec![(20, 1u32.to_le_bytes().to_vec()), (10, 2u32.to_le_bytes().to_vec()), (30, v.points(&pts))]; + synth::object(v, 3, &args, Some([1.0, 0.0, 0.0, 1.0, o, -o])) + }) + .collect(); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "Art", objects)]); + let body = vec![styles, page]; + let mut kids = vec![chunk(b"vrsn", 1300u16.to_le_bytes().to_vec())]; + if compress { + kids.push(synth::cmpr(&body)); + } else { + kids.extend(body); + } + synth::riff(1300, &kids) +} + +#[test] +#[ignore = "manual timing probe; wall-clock performance depends on machine load"] +fn read_a_large_drawing() { + for compress in [false, true] { + let file = many_curves(50_000, compress); + let mut times = Vec::new(); + for _ in 0..5 { + let t = std::time::Instant::now(); + let d = read(&file, Limits::default()).unwrap(); + times.push(t.elapsed().as_secs_f64() * 1000.0); + assert_eq!(d.pages.len(), 1); + } + times.sort_by(f64::total_cmp); + println!("compress={compress} bytes={} median_ms={:.1} min_ms={:.1}", file.len(), times[2], times[0]); + } +} diff --git a/crates/cdr/tests/it/cmx.rs b/crates/cdr/tests/it/cmx.rs new file mode 100644 index 0000000000..381eaddfcb --- /dev/null +++ b/crates/cdr/tests/it/cmx.rs @@ -0,0 +1,568 @@ +//! Reading synthetic `.cmx` files built from the layouts in `PROVENANCE.md` (R53 to R63), and +//! hostile ones. + +use proptest::prelude::*; +use vectorcraft_cdr::model::{Cap, Color, Geometry, Join, Object, Shape}; +use vectorcraft_cdr::synth_cmx::*; +use vectorcraft_cdr::{Error, Limits, Warning, is_cdr, is_cmx, read_cmx}; + +fn shape(o: &Object) -> &Shape { + match o { + Object::Shape(s) => s, + other => panic!("not a shape: {other:?}"), + } +} + +/// The (x, y) bounds of a shape's path. +fn bounds(s: &Shape) -> (f64, f64, f64, f64) { + let Geometry::Path(p) = &s.geometry else { panic!("not a path") }; + let mut b = (f64::MAX, f64::MAX, f64::MIN, f64::MIN); + for sp in &p.subpaths { + for pt in std::iter::once(sp.start).chain(sp.segments.iter().map(|s| match s { + vectorcraft_cdr::model::Segment::Line(p) | vectorcraft_cdr::model::Segment::Cubic(_, _, p) => *p, + })) { + b = (b.0.min(pt.x), b.1.min(pt.y), b.2.max(pt.x), b.3.max(pt.y)); + } + } + b +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 +} + +/// The file with `children` after a 32-bit header and the sample tables. +fn file(pages: &[Vec]) -> Vec { + let mut children = vec![cont(b'4', 1e-7)]; + children.extend(pages.iter().cloned()); + children.extend(tables()); + riff(&children) +} + +#[test] +fn a_cmx_file_is_told_from_a_cdr_drawing() { + let f = sample(); + assert!(is_cmx(&f) && !is_cdr(&f)); + let mut rifx = f.clone(); + rifx[..4].copy_from_slice(b"RIFX"); + assert!(is_cmx(&rifx)); + assert!(!is_cmx(b"RIFF\0\0\0\0CDR9")); + assert_eq!(read_cmx(b"RIFF\0\0\0\0CDR9", Limits::default()), Err(Error::NotCmx)); +} + +#[test] +fn pages_layers_groups_and_curves() { + let d = read_cmx(&sample(), Limits::default()).unwrap(); + assert_eq!(d.version, 0); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + let page = &d.pages[0]; + // 2,100,000 units of 0.1 µm are 210 mm. + let (w, h) = page.size.unwrap(); + assert!(near(w, 210.0 / 25.4 * 72.0) && near(h, 297.0 / 25.4 * 72.0), "{w} {h}"); + // The layer drawn last is in front: the model lists layers front to back. + let names: Vec<&str> = page.layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["Top", "Art"]); + let art = &page.layers[1].objects; + assert_eq!(art.len(), 2); + // The group, drawn after the red square, is in front of it. + let Object::Group { objects: kids, .. } = &art[0] else { panic!("{:?}", art[0]) }; + assert_eq!(kids.len(), 2); + let red = shape(&art[1]); + assert_eq!(red.fill, Some(Color::Rgb([1.0, 0.0, 0.0]))); + // 1,000,000 units are 100 mm; the square's corner is 50 mm left of and below the center. + let mm = 72.0 / 25.4; + let b = bounds(red); + assert!(near(b.0, -50.0 * mm) && near(b.1, -50.0 * mm) && near(b.2, 50.0 * mm) && near(b.3, 50.0 * mm), "{b:?}"); + let Geometry::Path(p) = &red.geometry else { panic!() }; + assert!(p.subpaths.len() == 1 && p.subpaths[0].closed && p.subpaths[0].segments.len() == 4); + let o = red.outline.as_ref().unwrap(); + assert!(near(o.width, 0.5 * mm)); + assert_eq!((o.color.clone(), o.cap, o.join), (Color::Cmyk([0.0, 0.0, 0.0, 1.0]), Cap::Round, Join::Round)); + assert!(o.dashes.is_empty() && !o.behind_fill && !o.scale_with); + // Line type 1 draws no outline. + let blue = shape(&kids[0]); + let black = shape(&kids[1]); + assert!(black.outline.is_none()); + assert_eq!(black.fill, Some(Color::Cmyk([0.0, 0.0, 0.0, 1.0]))); + // The color record's values are blue, green and red. + assert_eq!(blue.fill, Some(Color::Rgb([0.0, 0.0, 1.0]))); + let o = blue.outline.as_ref().unwrap(); + assert!(near(o.width, 1.0 * mm)); + assert_eq!((o.dashes.clone(), o.behind_fill, o.cap, o.join), (vec![3.0, 1.0], true, Cap::Square, Join::Miter)); + assert_eq!(page.layers[0].name, "Top"); +} + +#[test] +fn layer_names_and_layers_without_objects() { + let p = page(&[ + begin_page(None), + begin_layer("Ebene 1", Some("Слой 1")), + square(&attrs(Some(1), None, false), 0, 0, 1000), + end_layer(), + begin_layer("Gitter", None), + end_layer(), + begin_layer("Caf\u{e9}", None), + square(&attrs(Some(1), None, false), 0, 0, 1000), + end_layer(), + end_page(), + ]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let page = &d.pages[0]; + assert_eq!(page.size, None); + // The empty layer is left out, and the UTF-16 name wins over the 8-bit one. + let names: Vec<&str> = page.layers.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["Caf\u{c3}\u{a9}", "Слой 1"]); +} + +#[test] +fn objects_before_any_layer_get_one() { + let p = page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + assert_eq!(d.pages[0].layers.len(), 1); + // The layer is left unnamed, as a `.cdr` drawing's is; the importer names it by its place. + assert_eq!(d.pages[0].layers[0].name, ""); +} + +#[test] +fn a_page_without_a_size_takes_the_drawings_bounds() { + // A square of 100 mm whose bounds lie off the file's origin, above and to the right. + let p = page(&[ + begin_page_in_bounds(1_000_000, 3_000_000, 2_000_000, 2_000_000), + begin_layer("L", None), + square(&attrs(Some(1), None, false), 1_000_000, 2_000_000, 1_000_000), + end_layer(), + end_page(), + ]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let page = &d.pages[0]; + let side = 100.0 / 25.4 * 72.0; + let (w, h) = page.size.unwrap(); + assert!(near(w, side) && near(h, side), "{w} x {h}"); + // The page is centered on the bounds, so the square fills it. + let (x0, y0, x1, y1) = bounds(shape(&page.layers[0].objects[0])); + assert!(near(x0, -side / 2.0) && near(x1, side / 2.0) && near(y0, -side / 2.0) && near(y1, side / 2.0), "{x0} {y0} {x1} {y1}"); +} + +#[test] +fn curves_and_open_groups() { + let c = + curve(&attrs(None, Some(1), false), &[(0, 0), (100, 0), (100, 100), (0, 100), (200, 200), (300, 200)], &[0x00, 0xc0, 0xc0, 0x84, 0x00, 0x44]); + // A group the layer leaves open closes with it. + let p = page(&[begin_page(None), begin_layer("L", None), begin_group(), c, end_layer()]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + let objects = &d.pages[0].layers[0].objects; + let Object::Group { objects: kids, .. } = &objects[0] else { panic!("{objects:?}") }; + let s = shape(&kids[0]); + assert!(s.fill.is_none()); + let Geometry::Path(p) = &s.geometry else { panic!() }; + assert_eq!(p.subpaths.len(), 2); + assert!(matches!(p.subpaths[0].segments[..], [vectorcraft_cdr::model::Segment::Cubic(..)])); + assert!(!p.subpaths[1].closed); +} + +#[test] +fn a_curve_without_its_points_is_reported() { + let p = page(&[begin_page(None), begin_layer("L", None), instr(67, &fields(&[field(1, &attrs(Some(1), None, false))])), end_layer()]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); +} + +#[test] +fn a_layer_name_too_short_to_read_in_utf_16_reads_in_8_bit() { + let mut d = vec![1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0]; + d.extend(b"Art"); + let layer = instr(11, &fields(&[field(1, &d), field(4, &[3, 0])])); + let p = page(&[begin_page(None), layer, square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + assert_eq!(d.pages[0].layers[0].name, "Art"); +} + +#[test] +fn what_is_not_read_is_reported() { + let other = |code: i16| instr(code, &fields(&[field(1, &[0; 8])])); + let p = page(&[ + begin_page(None), + begin_layer("L", None), + other(66), + other(68), + other(20), + other(88), + square(&attrs_fill_type(2), 0, 0, 1000), + square(&attrs(Some(1), None, true), 0, 0, 1000), + end_layer(), + ]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + for w in [Warning::UnsupportedObjects, Warning::UnsupportedFills, Warning::Lenses] { + assert!(d.warnings.contains(&w), "{w:?}: {:?}", d.warnings); + } + // A fill of another type leaves the curve unfilled; the curve is still read. + let objects = &d.pages[0].layers[0].objects; + assert_eq!(objects.len(), 2); + assert!(shape(&objects[1]).fill.is_none()); +} + +#[test] +fn colors_of_other_models_and_missing_entries() { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[ + begin_page(None), + begin_layer("L", None), + square(&attrs(Some(1), None, false), 0, 0, 1000), + square(&attrs(Some(9), None, false), 0, 0, 1000), + square(&attrs(Some(2), None, false), 0, 0, 1000), + ])); + children.push(table(b"rclr", &[color(7, &[1, 2, 3, 4]), color(3, &[255, 0, 0, 255])])); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::UnknownColors) && d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + let objects = &d.pages[0].layers[0].objects; + assert_eq!(shape(&objects[0]).fill, Some(Color::Cmyk([1.0, 0.0, 0.0, 1.0]))); + assert_eq!(shape(&objects[1]).fill, Some(Color::Rgb([0.0; 3]))); +} + +#[test] +fn gray_cmy_and_rgb_colors_of_the_older_fields() { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[ + begin_page(None), + begin_layer("L", None), + square(&attrs(Some(1), None, false), 0, 0, 1000), + square(&attrs(Some(2), None, false), 0, 0, 1000), + square(&attrs(Some(3), None, false), 0, 0, 1000), + ])); + children.push(table(b"rclr", &[color(9, &[51]), color(4, &[255, 0, 51]), color(5, &[255, 0, 0])])); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + let objects = &d.pages[0].layers[0].objects; + // The model holds objects front to back: the RGB square, the CMY one, then the gray one. + assert_eq!(shape(&objects[0]).fill, Some(Color::Rgb([1.0, 0.0, 0.0]))); + match (shape(&objects[1]).fill.clone(), shape(&objects[2]).fill.clone()) { + (Some(Color::Cmyk([c, m, y, k])), Some(Color::Gray(g))) => { + assert!((c - 1.0).abs() < 1e-6 && m == 0.0 && (y - 0.2).abs() < 1e-6 && k == 0.0, "{c} {m} {y} {k}"); + assert!((g - 0.8).abs() < 1e-6, "{g}"); + } + other => panic!("{other:?}"), + } +} + +#[test] +fn outline_arrowheads_are_reported() { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(None, Some(1), false), 0, 0, 1000)])); + children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rota"))); + children.push(arrowheads(&[(0, 2)])); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.warnings, vec![Warning::Arrowheads]); +} + +#[test] +fn a_long_instruction_and_a_jump_over_image_bytes() { + // The jump's target counts from the start of the file: header, `cont`, then the page body. + let before = riff(&[cont(b'4', 1e-7), page(&[])]).len() - 8; + let head = [begin_page(None), begin_layer("L", None)].concat(); + let jump_len = 4 + 1 + 3 + 4; + let image = vec![0xEEu8; 37]; + let target = (before + 8 + head.len() + jump_len + image.len()) as u32; + let jump = instr(111, &fields(&[field(1, &target.to_le_bytes())])); + assert_eq!(jump.len(), jump_len); + let body = [ + head, + jump, + image, + long_instr(67, &curve(&attrs(Some(1), None, false), &[(0, 0), (10, 0), (10, 10)], &[0x0c, 0x44, 0x48])[4..]), + end_layer(), + ] + .concat(); + let mut children = vec![cont(b'4', 1e-7), chunk(b"page", &body)]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + // The images jumped over are not read, and the warning says so. + assert_eq!(d.warnings, [Warning::UnsupportedObjects]); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn bytes_after_a_chunk_that_runs_short_are_passed_over() { + let stray = vec![0x10, 0x00, 0x16, 0x00, 0x01, 0x0b, 0x00, 0x01, 0, 0, 0, 0, 0, 0, 0, 0xff]; + let mut children = vec![cont(b'4', 1e-7), stray, list(b"pgls", &[page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)])])]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn other_byte_orders_and_coordinate_sizes_are_refused() { + let mut f = sample(); + f[..4].copy_from_slice(b"RIFX"); + assert_eq!(read_cmx(&f, Limits::default()), Err(Error::Unsupported("big-endian CMX files"))); + let mut children = vec![cont(b'2', 1e-3)]; + children.extend(tables()); + assert_eq!(read_cmx(&riff(&children), Limits::default()), Err(Error::Unsupported("CMX files with 16-bit coordinates"))); + assert_eq!(read_cmx(&riff(&tables()), Limits::default()), Err(Error::Damaged("CMX header"))); + assert_eq!(read_cmx(&riff(&[cont(b'9', 1e-7)]), Limits::default()), Err(Error::Damaged("CMX header"))); +} + +#[test] +fn a_header_without_a_usable_unit_reads_0_1_micrometers() { + for meters in [0.0, -1.0, f64::NAN, 2.0] { + let mut children = vec![cont(b'4', meters), page(&[begin_page(Some((2_100_000, 2_970_000)))])]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + let (w, _) = d.pages[0].size.unwrap(); + assert!(near(w, 210.0 / 25.4 * 72.0), "{meters}: {w}"); + } +} + +#[test] +fn groups_past_the_depth_limit_are_left_out() { + let mut ins = vec![begin_page(None), begin_layer("L", None)]; + for _ in 0..6 { + ins.push(begin_group()); + } + ins.push(square(&attrs(Some(1), None, false), 0, 0, 1000)); + for _ in 0..6 { + ins.push(end_group()); + } + ins.push(square(&attrs(Some(1), None, false), 0, 0, 1000)); + let d = read_cmx(&file(&[page(&ins)]), Limits { depth: 3, ..Limits::default() }).unwrap(); + assert!(d.warnings.contains(&Warning::TooDeep)); + // The square after the groups is still read, beside the three groups kept. + let objects = &d.pages[0].layers[0].objects; + assert_eq!(objects.len(), 2); + let mut depth = 0; + let mut o = &objects[1]; + while let Object::Group { objects: kids, .. } = o { + depth += 1; + match kids.first() { + Some(k) => o = k, + None => break, + } + } + assert_eq!(depth, 3); +} + +#[test] +fn counts_past_the_limits_are_bounded() { + let ins: Vec> = std::iter::once(begin_page(None)).chain((0..50).map(|_| square(&attrs(Some(1), None, false), 0, 0, 1000))).collect(); + let f = file(&[page(&ins)]); + let d = read_cmx(&f, Limits { objects: 10, ..Limits::default() }).unwrap(); + assert_eq!(d.pages[0].layers[0].objects.len(), 10); + assert!(d.warnings.contains(&Warning::TooDeep)); + let d = read_cmx(&f, Limits { coordinates: 12, ..Limits::default() }).unwrap(); + assert_eq!(d.pages[0].layers[0].objects.len(), 2); + assert_eq!(read_cmx(&f, Limits { chunks: 20, ..Limits::default() }), Err(Error::Limit("chunk count"))); + assert_eq!(read_cmx(&f, Limits { input: 10, ..Limits::default() }), Err(Error::Limit("input size"))); + let dashed = |n: u16| { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[begin_page(None), square(&attrs(None, Some(3), false), 0, 0, 1000), square(&attrs(None, Some(3), false), 0, 0, 1000)])); + children.extend(tables()); + read_cmx(&riff(&children), Limits { dashes: usize::from(n), ..Limits::default() }).unwrap() + }; + let d = dashed(3); + let o: Vec = d.pages[0].layers[0].objects.iter().map(|o| shape(o).outline.as_ref().unwrap().dashes.len()).collect(); + assert_eq!(o, [0, 2]); + assert!(d.warnings.contains(&Warning::TooDeep)); +} + +#[test] +fn a_curve_cut_short_keeps_the_points_it_holds() { + let mut c = curve(&attrs(Some(1), None, false), &[(0, 0), (10, 0), (10, 10)], &[0x0c, 0x44, 0x48]); + // Claim 9 points where 3 are stored: the field's own length still covers only 3. + let at = c.windows(2).position(|w| w == [3, 0]).unwrap(); + c[at] = 9; + let p = page(&[begin_page(None), c]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged)); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn a_curve_that_lost_type_bytes_keeps_its_first_points() { + // Three whole points and only two of their type bytes. + let mut g = 3u16.to_le_bytes().to_vec(); + for (x, y) in [(0i32, 0i32), (1_000_000, 0), (1_000_000, 1_000_000)] { + g.extend(x.to_le_bytes()); + g.extend(y.to_le_bytes()); + } + g.extend([0x0c, 0x44]); + let c = instr(67, &fields(&[field(1, &attrs(None, Some(1), false)), field(2, &g)])); + let d = read_cmx(&file(&[page(&[begin_page(None), c])]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + let Geometry::Path(p) = &shape(&d.pages[0].layers[0].objects[0]).geometry else { panic!() }; + let side = 100.0 / 25.4 * 72.0; + assert!(near(p.subpaths[0].start.x, 0.0) && near(p.subpaths[0].start.y, 0.0)); + match p.subpaths[0].segments[..] { + [vectorcraft_cdr::model::Segment::Line(e)] => assert!(near(e.x, side) && near(e.y, 0.0), "{e:?}"), + ref other => panic!("{other:?}"), + } +} + +#[test] +fn a_file_cut_short_of_its_declared_size_is_reported() { + let mut f = file(&[]); + let declared = (f.len() as u32 - 8 + 100).to_le_bytes(); + f[4..8].copy_from_slice(&declared); + let d = read_cmx(&f, Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); +} + +#[test] +fn a_page_that_ends_inside_an_instruction_is_reported() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), vec![1, 0]]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn a_chunk_64_bytes_past_stray_bytes_is_found() { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut children = vec![cont(b'4', 1e-7), [vec![1u8; 64], p].concat()]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn stray_letters_with_a_length_past_the_file_are_passed_over() { + let mut stray = b"abcd".to_vec(); + stray.extend(0xFFFF_FF00u32.to_le_bytes()); + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut children = vec![cont(b'4', 1e-7), [stray, p].concat()]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn a_dash_pattern_of_zero_lengths_draws_a_solid_line() { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(None, Some(1), false), 0, 0, 1000)])); + children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rdot") && !t.starts_with(b"rotl"))); + children.push(table(b"rdot", &[dashes(&[0, 0])])); + children.push(table(b"rotl", &[outline([3, 1, 2, 1, 1, 1])])); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + let o = shape(&d.pages[0].layers[0].objects[0]).outline.clone().unwrap(); + assert!(o.dashes.is_empty(), "{:?}", o.dashes); +} + +#[test] +fn a_curve_field_that_lost_points_is_left_out() { + // Three points claimed, two whole points stored and the third cut inside its y: the type + // bytes can't be found, so no node types are read from coordinates. + let mut g = 3u16.to_le_bytes().to_vec(); + for (x, y) in [(0i32, 0i32), (1_000_000, 0)] { + g.extend(x.to_le_bytes()); + g.extend(y.to_le_bytes()); + } + g.extend(1_000_000i32.to_le_bytes()); + g.extend([0x40, 0x42]); + let c = instr(67, &fields(&[field(1, &attrs(Some(1), None, false)), field(2, &g)])); + let d = read_cmx(&file(&[page(&[begin_page(None), begin_layer("L", None), c])]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + assert!(d.pages[0].layers.is_empty(), "{:?}", d.pages[0].layers); +} + +#[test] +fn a_chunk_whose_id_has_a_digit_is_found_after_stray_bytes() { + // Stray bytes, a chunk the reader passes over whose id ends in a digit, then the page. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 6]; + b.extend(chunk(b"inf1", &[0; 70])); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn padding_and_ids_with_impossible_lengths_are_not_taken_for_chunks() { + // After stray bytes, four spaces with a small length, or letters with a length past the list, + // come before the page: neither is taken for a chunk, so the page is found. + for filler in [b" \x08\x00\x00\x00".to_vec(), b"junk\x40\x42\x0f\x00".to_vec()] { + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut b = vec![1u8; 2]; + b.extend(filler); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); + } +} + +#[test] +fn after_stray_bytes_a_chunk_the_reader_passes_over_keeps_what_it_holds() { + // Stray bytes, then a chunk the reader passes over whose body starts with the letters of a + // page chunk, then the page: only the page is read. + let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]); + let mut inner = b"page".to_vec(); + inner.extend(4u32.to_le_bytes()); + inner.extend([0; 10]); + let mut b = vec![1u8; 2]; + b.extend(chunk(b"inf1", &inner)); + b.extend(p); + let mut children = vec![cont(b'4', 1e-7), b]; + children.extend(tables()); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert_eq!(d.pages.len(), 1); + assert_eq!(d.pages[0].layers[0].objects.len(), 1); +} + +#[test] +fn a_canvas_or_a_container_is_reported() { + for bit in [8u8, 16] { + let mut a = attrs(Some(1), None, false); + a[0] |= bit; + let p = page(&[begin_page(None), begin_layer("L", None), square(&a, 0, 0, 1000), end_layer()]); + let d = read_cmx(&file(&[p]), Limits::default()).unwrap(); + assert_eq!(d.warnings, vec![Warning::UnsupportedObjects], "{bit}"); + assert!(shape(&d.pages[0].layers[0].objects[0]).fill.is_some()); + } +} + +#[test] +fn a_library_color_with_its_name_reads_as_a_spot_color() { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000)])); + children.push(table(b"rclr", &[color_record_named(5, [0, 0, 255, 0], Some("Brick 12"))])); + let d = read_cmx(&riff(&children), Limits::default()).unwrap(); + match shape(&d.pages[0].layers[0].objects[0]).fill.clone() { + Some(Color::Spot { name, tint, look }) => { + assert_eq!((name.as_str(), tint), ("Brick 12", 1.0)); + assert!(look.is_some()); + } + other => panic!("{other:?}"), + } +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })] + + #[test] + fn never_panics_on_garbage(bytes in prop::collection::vec(any::(), 0..2048)) { + let mut b = b"RIFF\0\0\0\0CMX1".to_vec(); + b.extend(bytes); + let _ = read_cmx(&b, Limits::default()); + } + + #[test] + fn never_panics_on_mutated_samples(edits in prop::collection::vec((any::(), any::()), 1..24)) { + let mut b = sample(); + let n = b.len(); + for (at, v) in edits { + b[at % n] = v; + } + let _ = read_cmx(&b, Limits::default()); + } +} diff --git a/crates/cdr/tests/it/main.rs b/crates/cdr/tests/it/main.rs new file mode 100644 index 0000000000..4fc7dcbdc9 --- /dev/null +++ b/crates/cdr/tests/it/main.rs @@ -0,0 +1,8 @@ +//! Integration tests: one test binary for the crate, one module per area. +// Unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod bench; +mod cmx; +mod provenance; +mod read; diff --git a/crates/cdr/tests/it/provenance.rs b/crates/cdr/tests/it/provenance.rs new file mode 100644 index 0000000000..fffc006cb4 --- /dev/null +++ b/crates/cdr/tests/it/provenance.rs @@ -0,0 +1,43 @@ +//! Every layout id the code cites (`R1` ...) has a row in `PROVENANCE.md`. + +use std::collections::BTreeSet; + +/// The ids `R` in `text`. +fn ids(text: &str) -> BTreeSet { + let b = text.as_bytes(); + let mut out = BTreeSet::new(); + for (i, c) in b.iter().enumerate() { + let starts = *c == b'R' && (i == 0 || !b[i - 1].is_ascii_alphanumeric()); + if !starts { + continue; + } + let digits: String = b[i + 1..].iter().take_while(|d| d.is_ascii_digit()).map(|d| *d as char).collect(); + let ends = b.get(i + 1 + digits.len()).is_none_or(|d| !d.is_ascii_alphanumeric()); + if !digits.is_empty() && ends { + out.insert(digits.parse().unwrap()); + } + } + out +} + +#[test] +fn every_cited_layout_has_a_row() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")); + let table = std::fs::read_to_string(dir.join("PROVENANCE.md")).unwrap(); + let rows: BTreeSet = table.lines().filter_map(|l| l.strip_prefix("| R")).filter_map(|l| l.split(' ').next()?.parse().ok()).collect(); + let mut cited = BTreeSet::new(); + for entry in std::fs::read_dir(dir.join("src")).unwrap() { + let path = entry.unwrap().path(); + if path.extension().is_some_and(|e| e == "rs") { + cited.extend(ids(&std::fs::read_to_string(&path).unwrap())); + } + } + assert!(!cited.is_empty()); + let missing: Vec<_> = cited.difference(&rows).collect(); + assert!(missing.is_empty(), "cited without a PROVENANCE.md row: {missing:?}"); +} + +#[test] +fn ids_are_found_only_as_whole_words() { + assert_eq!(ids("(R1, R12) RIFF R3x xR4 R"), BTreeSet::from([1, 12])); +} diff --git a/crates/cdr/tests/it/read.rs b/crates/cdr/tests/it/read.rs new file mode 100644 index 0000000000..5c944a6c16 --- /dev/null +++ b/crates/cdr/tests/it/read.rs @@ -0,0 +1,2163 @@ +//! Reading synthetic drawings of every version the reader takes, plain and compressed, and +//! hostile files. + +use proptest::prelude::*; +use vectorcraft_cdr::model::{Blend, Cap, Color, Flags, Geometry, Join, LayerKind, Matrix, Object, Segment}; +use vectorcraft_cdr::synth::{self, V, chunk, list}; +use vectorcraft_cdr::{Error, Limits, Warning, read}; + +fn shapes(objects: &[Object]) -> Vec<&vectorcraft_cdr::model::Shape> { + let mut out = Vec::new(); + let mut stack: Vec<&Object> = objects.iter().rev().collect(); + while let Some(o) = stack.pop() { + match o { + Object::Shape(s) => out.push(&**s), + Object::Group { objects: kids, .. } => stack.extend(kids.iter().rev()), + Object::Clip { container, objects } => { + out.push(&**container); + stack.extend(objects.iter().rev()); + } + } + } + out +} + +/// The page and layers of the sample of `version`. +fn check_pages(d: &vectorcraft_cdr::Drawing, version: u16) { + assert_eq!(d.version, version); + let (w, h) = d.page_size.unwrap(); + assert!((w - 612.0).abs() < 0.1 && (h - 792.0).abs() < 0.1, "{version}: {w} {h}"); + assert_eq!(d.pages.len(), 1, "{version}"); + let art = &d.pages[0].layers[0]; + assert_eq!((art.name.as_str(), art.kind), ("Art", LayerKind::Drawing)); + assert!(matches!(art.objects[3], Object::Group { objects: ref g, .. } if g.len() == 2)); + assert!(d.warnings.contains(&Warning::UnsupportedObjects)); + // The master page: its guideline every page shows, and its desktop object. + if version >= 600 { + assert_eq!(d.guides.len(), 1); + assert!((d.guides[0].angle - 90.0).abs() < 1e-9 && (d.guides[0].at.x - 36.0).abs() < 0.01); + } + assert_eq!(d.master.len(), 1); + assert_eq!(d.master[0].kind, LayerKind::Desktop); +} + +/// The shapes of the sample of `version`: rectangle, ellipse, curve, and the group's polygon and +/// arc; the text is left out. +fn check_shapes(d: &vectorcraft_cdr::Drawing, version: u16) { + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s.len(), 5, "{version}"); + assert!(matches!(s[0].geometry, Geometry::Rect { radii, .. } if radii.iter().all(|r| (r - 5.0).abs() < 0.1))); + // The samples of versions 3 and 4 store their red as CMYK in percent. + let red = if version < 500 { Color::Cmyk([0.0, 1.0, 1.0, 0.0]) } else { Color::Rgb([1.0, 0.0, 0.0]) }; + assert_eq!(s[0].fill, Some(red), "{version}"); + let o = s[0].outline.as_ref().unwrap(); + assert!((o.width - 2.0).abs() < 0.05 && o.cap == Cap::Round, "{version}: {o:?}"); + assert!((s[0].matrix.0[4] + 100.0).abs() < 0.1 && (s[0].matrix.0[5] - 100.0).abs() < 0.1); + assert!(matches!(s[1].geometry, Geometry::Ellipse { .. }) && s[1].outline.is_none()); + assert!(matches!(&s[2].geometry, Geometry::Path(p) if p.subpaths[0].closed && matches!(p.subpaths[0].segments[1], Segment::Cubic(..)))); + assert!(s[2].fill.is_none()); + if version >= 600 { + let Geometry::Path(p) = &s[3].geometry else { panic!("polygon") }; + assert_eq!(p.subpaths[0].segments.len(), 10, "five sides of two segments"); + // 5 % of 1000 mm. + let r = p.subpaths[0].start.y; + assert!((r - 0.05 * synth::POLYGON_SIDE).abs() < 0.5, "{r}"); + } + assert!(matches!(&s[4].geometry, Geometry::Path(p) if p.subpaths[0].closed)); +} + +#[test] +fn every_version_from_5_to_13_reads_its_sample() { + for version in [500, 600, 700, 800, 900, 1000, 1100, 1200, 1300] { + for compress in [false, version >= 700] { + let d = read(&synth::sample(version, compress), Limits::default()).unwrap_or_else(|e| panic!("{version} {compress}: {e}")); + check_pages(&d, version); + check_shapes(&d, version); + } + } +} + +#[test] +fn versions_3_and_4_read_their_sample() { + for version in [300, 400] { + let file = synth::sample(version, false); + assert_eq!(&file[8..12], if version == 300 { b"CDR " } else { b"CDR4" }); + assert!(vectorcraft_cdr::is_cdr(&file)); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + assert!(!d.warnings.contains(&Warning::Damaged), "{version}: {:?}", d.warnings); + check_pages(&d, version); + check_shapes(&d, version); + let s = shapes(&d.pages[0].layers[0].objects); + let o = s[0].outline.as_ref().unwrap(); + assert_eq!((o.join, &o.color), (Join::Round, &Color::Cmyk([0.0, 0.0, 0.0, 1.0])), "{version}"); + // The ellipse 50 pt right of and below the page centre, and the curve where it was drawn. + assert!((s[1].matrix.0[4] - 50.0).abs() < 0.1 && (s[1].matrix.0[5] + 50.0).abs() < 0.1, "{version}: {:?}", s[1].matrix); + assert_eq!(s[2].matrix, Matrix::IDENTITY, "{version}"); + } + // The form type alone names version 3, and a `vrsn` chunk names it under another form type. + let mut plain = vec![]; + plain.extend(synth::sample_content(300)); + check_shapes(&read(&synth::riff(300, &plain), Limits::default()).unwrap(), 300); + let mut relabeled = synth::sample(300, false); + relabeled[11] = b'5'; + assert_eq!(read(&relabeled, Limits::default()).unwrap().version, 300); +} + +/// A version 3 drawing of one layer holding `objects`. +fn drawing3(objects: Vec) -> Vec { + let page = synth::page(false, vec![synth::layer(V(300), [0, 0, 0, 0x98], "L", objects)]); + synth::riff(300, &[chunk(b"vrsn", 300u16.to_le_bytes().to_vec()), page]) +} + +/// A version 3 rectangle of 10 × 10 pt with the transforms `matrices`. +fn rect3(matrices: &[[f64; 6]]) -> synth::Node { + let v = V(300); + let mut args = vec![(30, v.rect(10.0, 10.0, 0.0))]; + if !matrices.is_empty() { + args.push((100, synth::transforms3(matrices))); + } + synth::object(v, 1, &args, None) +} + +#[test] +fn version_3_groups_place_their_objects() { + let shift = |x: f64, y: f64| [1.0, 0.0, 0.0, 1.0, x, y]; + let double = [2.0, 0.0, 0.0, 2.0, 0.0, 0.0]; + // A rectangle moved 72 pt right, in a group that doubles sizes, in a group that moves 36 pt + // up; beside the inner group, a rectangle of the outer group alone; then one outside both. + let inner = synth::group3(&[double], vec![rect3(&[shift(72.0, 0.0)])]); + let outer = synth::group3(&[shift(0.0, 36.0)], vec![inner, rect3(&[])]); + let d = read(&drawing3(vec![outer, rect3(&[shift(7.2, 0.0)])]), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + let objects = &d.pages[0].layers[0].objects; + assert!( + matches!(&objects[0], Object::Group { objects: g, .. } if matches!(&g[0], Object::Group { objects: i, .. } if i.len() == 1) && g.len() == 2) + ); + let s = shapes(objects); + let close = |m: &Matrix, want: [f64; 6]| m.0.iter().zip(want).all(|(a, b)| (a - b).abs() < 0.01); + // Its own shift, then the inner group's scale, then the outer group's shift. + assert!(close(&s[0].matrix, [2.0, 0.0, 0.0, 2.0, 144.0, 36.0]), "{:?}", s[0].matrix); + assert!(close(&s[1].matrix, [1.0, 0.0, 0.0, 1.0, 0.0, 36.0]), "{:?}", s[1].matrix); + assert!(close(&s[2].matrix, [1.0, 0.0, 0.0, 1.0, 7.2, 0.0]), "{:?}", s[2].matrix); + // Two matrices of one object apply in file order. + let d = read(&drawing3(vec![rect3(&[shift(72.0, 0.0), double])]), Limits::default()).unwrap(); + assert!(close(&shapes(&d.pages[0].layers[0].objects)[0].matrix, [2.0, 0.0, 0.0, 2.0, 144.0, 0.0])); +} + +#[test] +fn version_3_objects_and_groups_under_an_envelope_keep_their_outlines_and_matrices() { + // A transforms argument of one envelope entry (type 0x14). + let mut envelope = vec![0, 0, 1, 0, 0x14, 0]; + envelope.resize(14 + 24, 0); + // A matrix that moves 72 pt right, then an envelope entry whose data follows the matrix's. + let matrix = synth::transforms3(&[[1.0, 0.0, 0.0, 1.0, 72.0, 0.0]]).split_off(14); + let mut shifted = vec![0, 0, 2, 0, 0x8c, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0x14, 0, 0, 0, 0, 0, 48, 0, 0, 0]; + shifted.extend(matrix); + shifted.resize(48 + 24, 0); + let v = V(300); + let bent = synth::object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0)), (100, envelope.clone())], None); + let moved = synth::object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0)), (100, shifted)], None); + let group = list(b"grp ", vec![chunk(b"lobj", v.loda(0, &[(100, envelope)])), rect3(&[])]); + let d = read(&drawing3(vec![bent, moved, group, rect3(&[])]), Limits::default()).unwrap(); + let objects = &d.pages[0].layers[0].objects; + assert_eq!(objects.len(), 4); + assert!(matches!(&objects[2], Object::Group { objects: g, .. } if g.len() == 1)); + let s = shapes(objects); + assert_eq!(s.len(), 4); + assert!(matches!(s[0].geometry, Geometry::Rect { .. }) && s[0].matrix == Matrix::IDENTITY); + assert!((s[1].matrix.0[4] - 72.0).abs() < 0.01 && s[1].matrix.0[5].abs() < 0.01, "{:?}", s[1].matrix); + assert_eq!(s[2].matrix, Matrix::IDENTITY); + assert_eq!(d.warnings, vec![Warning::Envelopes]); +} + +#[test] +fn version_3_object_types_count_from_0() { + let v = V(300); + // `lobj` records written with their stored types: 0 rectangle, 2 curve, 3 text, 4 bitmap. + let raw = |kind: u32, coords: Vec| list(b"obj ", vec![chunk(b"lobj", v.loda(kind, &[(30, coords)]))]); + let curve = v.points(&[(0.0, 0.0, 0x00), (10.0, 0.0, 0x40)]); + let ellipse = [v.coord(40.0), v.coord(20.0), v.angle(0.0), v.angle(0.0), v.word(0)].concat(); + let d = read( + &drawing3(vec![raw(0, v.rect(10.0, 10.0, 0.0)), raw(1, ellipse), raw(2, curve), raw(3, vec![0; 8]), raw(4, vec![0; 8])]), + Limits::default(), + ) + .unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s.len(), 3); + assert!(matches!(s[0].geometry, Geometry::Rect { .. }) && matches!(s[1].geometry, Geometry::Ellipse { .. })); + assert!(matches!(&s[2].geometry, Geometry::Path(p) if p.subpaths.len() == 1)); + assert_eq!(d.warnings, vec![Warning::UnsupportedObjects]); +} + +#[test] +fn version_3_fills_and_outlines_read_from_the_object() { + let v = V(300); + let styled = |fill: Vec, outline: Vec| synth::object(v, 1, &[(20, fill), (10, outline), (30, v.rect(10.0, 10.0, 0.0))], None); + let pen = |line_type: u16| synth::Pen { line_type, width: 3.0, cap: 2, join: 2 }; + let black = synth::color3(1, [0, 0, 0, 100]); + let d = read( + &drawing3(vec![ + styled(synth::fill3(1, &synth::color3(0, [0, 0, 40, 0])), synth::outline3(pen(0), black, &[3, 1])), + styled(synth::fill3(1, &synth::color3(0, [1, 0, 100, 0])), synth::outline3(pen(1), black, &[])), + styled(synth::fill3(0, &[]), synth::outline3(pen(0), synth::color3(0, [200, 0, 80, 0]), &[])), + ]), + Limits::default(), + ) + .unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + // Ink 0 is black at its tint, ink 1 white, and another number a library ink. + assert_eq!((s[0].fill.clone(), s[1].fill.clone(), s[2].fill.clone()), (Some(Color::Gray(0.4)), Some(Color::Gray(0.0)), None)); + let o = s[0].outline.as_ref().unwrap(); + assert!((o.width - 3.0).abs() < 0.05, "{}", o.width); + assert_eq!((o.cap, o.join, &o.dashes), (Cap::Square, Join::Bevel, &vec![3.0, 1.0])); + assert!(s[1].outline.is_none()); + assert_eq!(s[2].outline.as_ref().unwrap().color, Color::Spot { name: "Spot 0:200".into(), tint: 0.8, look: None }); + assert_eq!(d.warnings, vec![Warning::SpotLooks]); + // Fountain, texture and pattern fills are named and leave the shape unfilled; a fill or an + // outline cut short is damage. + for kind in [2, 4, 6, 7, 10] { + let d = read(&drawing3(vec![styled(synth::fill3(kind, &[0; 12]), synth::outline3(pen(1), black, &[]))]), Limits::default()).unwrap(); + assert_eq!(d.warnings, vec![Warning::UnsupportedFills], "{kind}"); + assert!(shapes(&d.pages[0].layers[0].objects)[0].fill.is_none()); + } + let d = read(&drawing3(vec![styled(vec![1, 1], vec![1, 0])]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(s[0].fill.is_none() && s[0].outline.is_none()); + assert_eq!(d.warnings, vec![Warning::Damaged]); +} + +#[test] +fn version_3_dashes_count_toward_the_dash_limit() { + let v = V(300); + let pen = synth::Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }; + let dashed = + || synth::object(v, 1, &[(10, synth::outline3(pen, synth::color3(1, [0, 0, 0, 100]), &[2, 2, 2])), (30, v.rect(10.0, 10.0, 0.0))], None); + let d = read(&drawing3(vec![dashed(), dashed()]), Limits { dashes: 4, ..Limits::default() }).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!((s[0].outline.as_ref().unwrap().dashes.len(), s[1].outline.as_ref().unwrap().dashes.len()), (3, 0)); + assert_eq!(d.warnings, vec![Warning::TooDeep]); +} + +#[test] +fn hostile_version_3_transforms_are_damage() { + let v = V(300); + let with = |arg: Vec| synth::object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0)), (100, arg)], None); + // A matrix whose data offset lies past the argument, and an argument cut inside its header. + let mut past = synth::transforms3(&[[1.0, 0.0, 0.0, 1.0, 5.0, 5.0]]); + past[10..12].copy_from_slice(&60000u16.to_le_bytes()); + for arg in [past, vec![0, 0, 9]] { + let d = read(&drawing3(vec![with(arg)]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s[0].matrix, Matrix::IDENTITY); + assert_eq!(d.warnings, vec![Warning::Damaged]); + } + // A count of 65,535 over one entry reads that entry. + let mut many = synth::transforms3(&[[1.0, 0.0, 0.0, 1.0, 72.0, 0.0]]); + many[2..4].copy_from_slice(&u16::MAX.to_le_bytes()); + let d = read(&drawing3(vec![with(many)]), Limits::default()).unwrap(); + assert!((shapes(&d.pages[0].layers[0].objects)[0].matrix.0[4] - 72.0).abs() < 0.01); + assert_eq!(d.warnings, vec![Warning::Damaged]); +} + +#[test] +fn version_4_transforms_are_fixed_point_and_compose_in_file_order() { + let v = V(400); + let own = vec![ + chunk(b"loda", v.loda(1, &[(30, v.rect(10.0, 10.0, 0.0))])), + list(b"trfl", vec![chunk(b"trfd", v.trfd(&[[1.0, 0.0, 0.0, 1.0, 72.0, 0.0], [0.0, 2.0, -2.0, 0.0, 0.0, 0.0]]))]), + ]; + let object = list(b"obj ", vec![list(b"lgob", own)]); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![object])]); + let d = read(&synth::riff(400, &[chunk(b"vrsn", 400u16.to_le_bytes().to_vec()), page]), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + // Moved 72 pt right, then turned a quarter and doubled: (0, 0) lands at (0, 144). + let m = shapes(&d.pages[0].layers[0].objects)[0].matrix; + assert!(m.0.iter().zip([0.0, 2.0, -2.0, 0.0, 0.0, 144.0]).all(|(a, b)| (a - b).abs() < 0.01), "{m:?}"); +} + +#[test] +fn version_4_colors_are_words() { + let v = V(400); + let file = |fill: [u8; 12]| { + let doc = list(b"doc ", vec![list(b"filt", vec![chunk(b"fill", v.fill(1, &fill))])]); + let rect = synth::object(v, 1, &[(20, 1u32.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))], None); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect])]); + synth::riff(400, &[chunk(b"vrsn", 400u16.to_le_bytes().to_vec()), doc, page]) + }; + let fill_of = |fill: [u8; 12]| { + let d = read(&file(fill), Limits::default()).unwrap(); + (shapes(&d.pages[0].layers[0].objects)[0].fill.clone(), d.warnings) + }; + assert_eq!(fill_of(synth::color4(1, [20, 40, 60, 80])), (Some(Color::Cmyk([0.2, 0.4, 0.6, 0.8])), vec![])); + assert_eq!(fill_of(synth::color4(0, [0, 30, 0, 0])), (Some(Color::Gray(0.3)), vec![])); + assert_eq!(fill_of(synth::color4(0, [1, 30, 0, 0])), (Some(Color::Gray(0.0)), vec![])); + assert_eq!( + fill_of(synth::color4(0, [513, 30, 0, 0])), + (Some(Color::Spot { name: "Spot 0:513".into(), tint: 0.3, look: None }), vec![Warning::SpotLooks]) + ); + // The version 5 record read in the version 4 layout would take these values from other bytes. + assert_ne!(fill_of(synth::color(2, [20, 40, 60, 80])).0, Some(Color::Cmyk([0.2, 0.4, 0.6, 0.8]))); +} + +#[test] +fn the_version_3_page_size_is_the_distance_between_its_corners() { + let v = V(300); + for corners in [[-306.0, 396.0, 306.0, -396.0], [306.0, -396.0, -306.0, 396.0]] { + let mut b = vec![0xff; 2]; + b.extend(corners.iter().flat_map(|c| v.coord(*c))); + let d = read(&synth::riff(300, &[list(b"doc ", vec![chunk(b"mcfg", b)])]), Limits::default()).unwrap(); + let (w, h) = d.page_size.unwrap(); + assert!((w - 612.0).abs() < 0.1 && (h - 792.0).abs() < 0.1, "{w} {h}"); + } + // Corners that give no width, and a chunk cut inside them, give no page size. + let mut flat = vec![0; 2]; + flat.extend([v.coord(10.0), v.coord(5.0), v.coord(10.0), v.coord(-5.0)].concat()); + for b in [flat.clone(), flat[..9].to_vec()] { + assert_eq!(read(&synth::riff(300, &[list(b"doc ", vec![chunk(b"mcfg", b)])]), Limits::default()).unwrap().page_size, None); + } +} + +#[test] +fn a_point_list_before_version_6_counts_its_points_with_a_u16() { + for version in [300, 400, 500] { + let v = V(version); + let mut points = v.points(&[(0.0, 0.0, 0x00), (10.0, 0.0, 0x40), (10.0, 10.0, 0x40)]); + // The u16 after the count is 1 in some curves; as part of a u32 count it would run the + // count past the points. + points[2] = 1; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 3, &[(30, points)], None)])]); + let d = read(&synth::riff(version, &[chunk(b"vrsn", version.to_le_bytes().to_vec()), page]), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(matches!(&s[0].geometry, Geometry::Path(p) if p.subpaths[0].segments.len() == 2), "{version}"); + } +} + +/// The objects of the one layer of a version 1 or 2 drawing. +fn wl_objects(d: &vectorcraft_cdr::Drawing) -> &[Object] { + assert_eq!((d.pages.len(), d.pages[0].layers.len(), d.master.len(), d.guides.len()), (1, 1, 0, 0)); + &d.pages[0].layers[0].objects +} + +#[test] +fn versions_1_and_2_read_their_sample() { + for (marker, version) in [(b'e', 100), (b'l', 200), (b'm', 200)] { + let file = synth::wl_sample(marker); + assert!(file.starts_with(b"WL") && vectorcraft_cdr::is_cdr(&file)); + let d = read(&file, Limits::default()).unwrap(); + assert_eq!(d.version, version); + let (w, h) = d.page_size.unwrap(); + assert!((w - 612.0).abs() < 0.1 && (h - 792.0).abs() < 0.1, "{w} {h}"); + // The text is left out, and the group record holds nothing. + assert_eq!(d.warnings, vec![Warning::UnsupportedObjects]); + let s = shapes(wl_objects(&d)); + assert_eq!(s.len(), 3); + // Front to back: the rounded rectangle, the ellipse, the curve. + assert!( + matches!(s[0].geometry, Geometry::Rect { w, h, radii } if (w - 100.0).abs() < 0.1 && (h - 50.0).abs() < 0.1 && radii.iter().all(|r| (r - 5.0).abs() < 0.1)) + ); + assert_eq!(s[0].fill, Some(Color::Cmyk([0.0, 1.0, 1.0, 0.0]))); + let o = s[0].outline.as_ref().unwrap(); + assert!((o.width - 2.0).abs() < 0.05, "{}", o.width); + assert_eq!((&o.color, o.cap, o.join, o.dashes.len()), (&Color::Cmyk([0.0, 0.0, 0.0, 1.0]), Cap::Butt, Join::Miter, 0)); + assert!((s[0].matrix.0[4] + 100.0).abs() < 0.1 && (s[0].matrix.0[5] - 100.0).abs() < 0.1, "{:?}", s[0].matrix); + assert!(matches!(s[1].geometry, Geometry::Ellipse { w, h } if (w - 40.0).abs() < 0.1 && (h + 40.0).abs() < 0.1)); + assert!(s[1].outline.is_none() && (s[1].matrix.0[4] - 50.0).abs() < 0.1 && (s[1].matrix.0[5] + 50.0).abs() < 0.1); + assert!(matches!(&s[2].geometry, Geometry::Path(p) if p.subpaths[0].closed && matches!(p.subpaths[0].segments[1], Segment::Cubic(..)))); + assert!(s[2].fill.is_none() && s[2].outline.is_some()); + assert_eq!(&s[2].matrix.0[..4], &[2.0, 0.0, 0.0, 2.0]); + } +} + +#[test] +fn a_version_1_matrix_and_point_place_the_shape() { + use synth::WlShape; + // x' = 0 x - 1 y + 72 and y' = 1 x + 0 y + 36: a quarter turn, then a shift. + let turned = synth::wl_object(WlShape::Rect { w: 10.0, h: 10.0, radius: 0.0 }, [0.0, 1.0, -1.0, 0.0, 72.0, 36.0], None, None); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[turned]), Limits::default()).unwrap(); + let m = shapes(wl_objects(&d))[0].matrix; + assert!(m.0.iter().zip([0.0, 1.0, -1.0, 0.0, 72.0, 36.0]).all(|(a, b)| (a - b).abs() < 0.01), "{m:?}"); + let at = m.apply(vectorcraft_cdr::model::Pt { x: 10.0, y: 0.0 }); + assert!((at.x - 72.0).abs() < 0.01 && (at.y - 46.0).abs() < 0.01, "{at:?}"); +} + +#[test] +fn version_1_arcs_and_text_are_left_out_with_a_warning() { + use synth::WlShape; + let unit = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + let arc = synth::wl_object(WlShape::Ellipse { w: 40.0, h: 40.0, angles: (0, 900) }, unit, None, None); + let whole = synth::wl_object(WlShape::Ellipse { w: 40.0, h: 40.0, angles: (900, 900) }, unit, None, None); + let mut other = synth::wl_object(WlShape::Text, unit, None, None); + other[60] = 9; + for (records, kept) in [(vec![arc], 0), (vec![whole], 1), (vec![synth::wl_object(WlShape::Text, unit, None, None)], 0), (vec![other], 0)] { + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &records), Limits::default()).unwrap(); + assert_eq!(wl_objects(&d).len(), kept); + assert_eq!(d.warnings.contains(&Warning::UnsupportedObjects), kept == 0); + assert!(!d.warnings.contains(&Warning::Damaged)); + } +} + +#[test] +fn hostile_version_1_files_stop_within_their_bytes_and_limits() { + use synth::WlShape; + let unit = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + let rect = || synth::wl_object(WlShape::Rect { w: 10.0, h: 10.0, radius: 0.0 }, unit, None, None); + let file = synth::wl_sample(b'e'); + // Cut at every length: an error, or what the bytes still hold. + for len in 0..file.len() { + let _ = read(&file[..len], Limits::default()); + } + // A body size that runs past the records' end. + let mut long = rect(); + long[28..30].copy_from_slice(&u16::MAX.to_le_bytes()); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[rect(), long]), Limits::default()).unwrap(); + assert_eq!((wl_objects(&d).len(), d.warnings.clone()), (1, vec![Warning::Damaged])); + // A point count larger than the record holds reads the points that fit. + let mut curve = synth::wl_object(WlShape::Curve(vec![(0.0, 0.0, 0x00), (10.0, 0.0, 0x40), (10.0, 10.0, 0x40)]), unit, None, None); + curve[114..116].copy_from_slice(&u16::MAX.to_le_bytes()); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[curve.clone()]), Limits::default()).unwrap(); + assert_eq!((wl_objects(&d).len(), d.warnings.clone()), (1, vec![Warning::Damaged])); + // Points past the coordinate limit leave the curve out. + curve[114..116].copy_from_slice(&3u16.to_le_bytes()); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[curve]), Limits { coordinates: 2, ..Limits::default() }).unwrap(); + assert_eq!(wl_objects(&d).len(), 0); + assert_eq!(d.warnings, vec![Warning::TooDeep]); + // Objects past the object limit are left out, and records past the chunk limit stop the read. + let many: Vec> = (0..10).map(|_| rect()).collect(); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &many), Limits { objects: 4, ..Limits::default() }).unwrap(); + assert_eq!((wl_objects(&d).len(), d.warnings.clone()), (4, vec![Warning::TooDeep])); + let groups: Vec> = (0..10).map(|_| synth::wl_group()).collect(); + assert_eq!(read(&synth::wl_file(b'e', (612.0, 792.0), &groups), Limits { chunks: 4, ..Limits::default() }), Err(Error::Limit("chunk count"))); + assert_eq!(read(&file, Limits { input: file.len() - 1, ..Limits::default() }), Err(Error::Limit("input size"))); + // Bytes left after the last whole record are damage. + let mut ragged = vec![rect()]; + ragged.push(vec![0; 5]); + let d = read(&synth::wl_file(b'e', (612.0, 792.0), &ragged), Limits::default()).unwrap(); + assert_eq!((wl_objects(&d).len(), d.warnings.clone()), (1, vec![Warning::Damaged])); +} + +#[test] +fn a_wl_prefix_alone_is_not_a_drawing() { + for bytes in [ + &b"WL"[..], + b"WLe\0", + b"WLAN settings, exported as plain text for the help desk", + // Records that start inside the header, and a marker and a fourth byte no source gives. + b"WLe\0\x1c\0\0\0\x10\0\0\0\x1c\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", + b"WLAN\x1c\0\0\0\x1c\0\0\0\x1c\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", + ] { + assert!(!vectorcraft_cdr::is_cdr(bytes)); + assert_eq!(read(bytes, Limits::default()), Err(Error::NotCdr)); + } +} + +#[test] +fn versions_outside_1_to_27_and_other_files_are_refused() { + // No source shows a RIFF file of version 1 or 2: those versions are `WL` files. + for version in [100, 200] { + let refused = read(&synth::riff(version, &[]), Limits::default()).unwrap_err(); + assert_eq!(refused, Error::Unsupported("RIFF files of versions before 3"), "{version}"); + assert_eq!(refused.to_string(), "RIFF files of versions before 3 are not read"); + } + assert_eq!(read(&synth::riff(2800, &[]), Limits::default()), Err(Error::Version(2800))); + assert_eq!(read(b"RIFF\x04\0\0\0WAVE", Limits::default()), Err(Error::NotCdr)); + assert_eq!(read(b"RIFF\x04\0\0\0CDRX", Limits::default()), Err(Error::NotCdr)); + assert!(!vectorcraft_cdr::is_cdr(b"PK\x03\x04")); + assert!(vectorcraft_cdr::is_cdr(&synth::sample(1100, true))); +} + +#[test] +fn letters_that_count_differently_take_the_vrsn_version() { + // Version 27 saves the letter `U`, which counts as 29 the older way; the next letter with a + // `vrsn` of 2800 is refused as version 28. + let mut file = synth::sample(2700, false); + file[11] = b'U'; + let d = read(&file, Limits::default()).unwrap(); + check_pages(&d, 2700); + check_shapes(&d, 2700); + let mut file = synth::riff(2800, &[chunk(b"vrsn", 2800u16.to_le_bytes().to_vec())]); + file[11] = b'V'; + assert_eq!(read(&file, Limits::default()), Err(Error::Version(2800))); +} + +#[test] +fn every_version_from_14_to_27_reads_its_package() { + for version in [1400, 1500, 1600, 1700, 1800, 2000, 2200, 2400, 2430, 2600, 2700] { + for compress in [false, true] { + let file = synth::sample_file(version, compress); + assert!(file.starts_with(b"PK\x03\x04") && vectorcraft_cdr::is_cdr(&file), "{version}"); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version} {compress}: {e}")); + assert!(!d.warnings.contains(&Warning::Damaged), "{version} {compress}: {:?}", d.warnings); + check_pages(&d, version); + check_shapes(&d, version); + } + } +} + +/// The version 17 sample's content with `extra` added after it, as a package. +fn package17(extra: Vec, members: &[synth::Member]) -> Vec { + let mut body = vec![chunk(b"vrsn", 1700u16.to_le_bytes().to_vec())]; + body.extend(synth::sample_content(1700)); + body.extend(extra); + synth::package16(1700, &body, true, members) +} + +#[test] +fn lists_whose_bodies_move_to_a_data_stream_read_the_same() { + let mut body = vec![chunk(b"vrsn", 1700u16.to_le_bytes().to_vec())]; + body.extend(synth::sample_content(1700)); + for moved in [*b"layr", *b"obj ", *b"page"] { + let file = synth::package16_with(1700, &body, true, &[], &[moved]); + let d = read(&file, Limits::default()).unwrap(); + assert!(!d.warnings.contains(&Warning::Damaged), "{moved:?}: {:?}", d.warnings); + check_pages(&d, 1700); + check_shapes(&d, 1700); + } +} + +#[test] +fn a_data_stream_no_chunk_reads_is_not_inflated() { + // 32 MiB of picture data that the reader doesn't use, in a stream of its own. + let bitmaps = list(b"bmpt", vec![chunk(b"bmp ", vec![0; 32 << 20])]); + let file = package17(vec![bitmaps], &[]); + assert!(file.len() < 1 << 20); + let d = read(&file, Limits { inflated: 4 << 20, ..Limits::default() }).unwrap(); + assert_eq!(d.warnings, vec![Warning::UnsupportedObjects]); + check_shapes(&d, 1700); +} + +#[test] +fn a_redirected_list_is_inflated_and_counts_toward_the_limit() { + // A list whose body is in a stream must be inflated to be split; past the limit it is left + // out with a warning, and the rest of the drawing reads. + let mut body = vec![chunk(b"vrsn", 1700u16.to_le_bytes().to_vec())]; + body.extend(synth::sample_content(1700)); + body.push(list(b"bmpt", vec![chunk(b"bmp ", vec![0; 32 << 20])])); + let file = synth::package16_with(1700, &body, true, &[], &[*b"bmpt"]); + let d = read(&file, Limits { inflated: 4 << 20, ..Limits::default() }).unwrap(); + assert!(d.warnings.contains(&Warning::TooDeep) && !d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); + check_shapes(&d, 1700); + let d = read(&file, Limits::default()).unwrap(); + assert!(!d.warnings.contains(&Warning::TooDeep)); +} + +#[test] +fn chunks_in_a_data_stream_past_a_limit_are_not_damage() { + // A record and a list in a 2 MiB stream, read with a 1 MiB member limit, stored and deflated + // with a 1 MiB inflate limit: only the limit warning. + let mcfg = synth::mcfg(V(1700), 300.0, 200.0); + let synth::Node::Chunk(_, mcfg) = mcfg else { panic!() }; + let n = mcfg.len() as u32; + let mut stream = mcfg.clone(); + stream.resize(2 << 20, 0); + stream[(1 << 20)..(1 << 20) + 4].copy_from_slice(b"fntt"); + let mut root = b"RIFF".to_vec(); + let body = doc_of(&[redirect(b"mcfg", 0, n, 0), redirect(b"LIST", 0, 4, 1 << 20)]); + root.extend(((body.len() + 4) as u32).to_le_bytes()); + root.extend(b"CDRH"); + root.extend(body); + let m = |name: &str, data: Vec, deflate: bool| synth::Member { name: name.into(), data, deflate }; + for (deflate, limits) in [(false, Limits { member: 1 << 20, ..Limits::default() }), (true, Limits { inflated: 1 << 20, ..Limits::default() })] { + let file = synth::zip( + &[ + m("content/root.dat", root.clone(), false), + m("content/dataFileList.dat", b"data1.dat".to_vec(), false), + m("content/data/data1.dat", stream.clone(), deflate), + ], + b"", + ); + let d = read(&file, limits).unwrap(); + assert_eq!(d.warnings, vec![Warning::TooDeep], "{deflate}"); + assert!(d.page_size.is_none()); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.page_size.is_some() && d.warnings.is_empty(), "{deflate}: {:?}", d.warnings); + } +} + +#[test] +fn encrypted_data_streams_and_other_methods_are_refused() { + let good = synth::sample_file(1700, false); + assert!(read(&good, Limits::default()).is_ok()); + // The directory entry of a data stream: its name's last place, 46 bytes after the entry start. + let name = b"content/data/data1.dat"; + let entry = good.windows(name.len()).rposition(|w| w == name).unwrap() - 46; + assert_eq!(&good[entry..entry + 4], b"PK\x01\x02"); + let mut encrypted = good.clone(); + encrypted[entry + 8] |= 1; + assert_eq!(read(&encrypted, Limits::default()), Err(Error::Unsupported("encrypted packages"))); + let mut other = good.clone(); + other[entry + 10] = 12; + assert_eq!(read(&other, Limits::default()), Err(Error::Unsupported("package compression methods other than storing and deflate"))); +} + +/// A version 17 package whose `root.dat` is `root` (the RIFF body after the form type) and whose +/// one data stream is `stream`. +fn raw_package(root: &[u8], stream: &[u8], list: &[u8]) -> Vec { + let mut riff = b"RIFF".to_vec(); + riff.extend(((root.len() + 4) as u32).to_le_bytes()); + riff.extend(b"CDRH"); + riff.extend(root); + let m = |name: &str, data: &[u8]| synth::Member { name: name.into(), data: data.to_vec(), deflate: false }; + synth::zip(&[m("content/root.dat", &riff), m("content/dataFileList.dat", list), m("content/data/data1.dat", stream)], b"") +} + +/// A chunk header for a redirect record of `stream`, `len` and `offset`. +fn redirect(id: &[u8; 4], stream: u32, len: u32, offset: u32) -> Vec { + let mut out = id.to_vec(); + out.extend(16u32.to_le_bytes()); + for v in [stream, len, offset, 0] { + out.extend(v.to_le_bytes()); + } + out +} + +#[test] +fn a_list_redirected_into_its_own_bytes_is_read_once() { + // The stream holds a `grp ` body whose children are lists redirected to that body again: + // the bytes are taken, so each child is damage and the list is read once. + for children in [1, 2] { + let len = 4 + 24 * children; + let mut stream = b"grp ".to_vec(); + for _ in 0..children { + stream.extend(redirect(b"LIST", 0, len, 0)); + } + let file = raw_package(&redirect(b"LIST", 0, len, 0), &stream, b"data1.dat"); + let d = read(&file, Limits { chunks: 100, ..Limits::default() }).unwrap(); + assert_eq!(d.warnings, vec![Warning::Damaged], "{children}"); + } +} + +/// A `doc ` list holding `records`, as `root.dat`'s body. +fn doc_of(records: &[Vec]) -> Vec { + let records = records.concat(); + let mut body = b"LIST".to_vec(); + body.extend(((records.len() + 4) as u32).to_le_bytes()); + body.extend(b"doc "); + body.extend(records); + body +} + +#[test] +fn records_share_bytes_within_the_member_limit() { + let mcfg = synth::mcfg(V(1700), 300.0, 200.0); + let synth::Node::Chunk(_, mcfg) = mcfg else { panic!() }; + let n = mcfg.len() as u32; + let mut stream = mcfg.clone(); + stream.extend(&mcfg); + // The same bytes, bytes that overlap them, bytes that only touch them, and the same bytes + // through a second line naming the same member: both redirects read. + for (second, list) in [ + (redirect(b"mcfg", 0, n, 0), &b"data1.dat"[..]), + (redirect(b"mcfg", 0, n, n - 1), b"data1.dat"), + (redirect(b"mcfg", 0, n, n), b"data1.dat"), + (redirect(b"mcfg", 1, n, 0), b"data1.dat\ndata1.dat"), + ] { + let file = raw_package(&doc_of(&[redirect(b"mcfg", 0, n, 0), second.clone()]), &stream, list); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.page_size.is_some() && d.warnings.is_empty(), "{:?}: {:?}", &second[8..], d.warnings); + } + // Bytes read again take from the member limit: with a limit of the stream's 1,024 bytes, a + // record of all of them reads twice, and a third read is left out with the limit warning. + let mut stream = mcfg.clone(); + stream.resize(1024, 0); + let limits = Limits { member: 1024, ..Limits::default() }; + for (reads, warnings) in [(2, vec![]), (3, vec![Warning::TooDeep])] { + let records = vec![redirect(b"mcfg", 0, 1024, 0); reads]; + let d = read(&raw_package(&doc_of(&records), &stream, b"data1.dat"), limits).unwrap(); + assert!(d.page_size.is_some(), "{reads}"); + assert_eq!(d.warnings, warnings, "{reads}"); + } +} + +#[test] +fn a_member_two_streams_name_is_inflated_once() { + // One deflated member of 2 MiB named on two lines, a list read from one and the page size + // from the other: within a 3 MiB inflate limit it is inflated once. + let mcfg = synth::mcfg(V(1700), 300.0, 200.0); + let synth::Node::Chunk(_, mcfg) = mcfg else { panic!() }; + let n = mcfg.len() as u32; + let mut stream = mcfg.clone(); + stream.resize(2 << 20, 0); + stream[(1 << 20)..(1 << 20) + 4].copy_from_slice(b"fntt"); + let mut root = b"RIFF".to_vec(); + let body = doc_of(&[redirect(b"LIST", 1, 4, 1 << 20), redirect(b"mcfg", 0, n, 0)]); + root.extend(((body.len() + 4) as u32).to_le_bytes()); + root.extend(b"CDRH"); + root.extend(body); + let m = |name: &str, data: Vec, deflate: bool| synth::Member { name: name.into(), data, deflate }; + let file = synth::zip( + &[ + m("content/root.dat", root, false), + m("content/dataFileList.dat", b"data1.dat\ndata1.dat".to_vec(), false), + m("content/data/data1.dat", stream, true), + ], + b"", + ); + let d = read(&file, Limits { inflated: 3 << 20, ..Limits::default() }).unwrap(); + assert!(d.page_size.is_some() && d.warnings.is_empty(), "{:?}", d.warnings); +} + +#[test] +fn redirects_past_their_stream_or_to_a_missing_one_are_damage() { + let mcfg = synth::mcfg(V(1700), 300.0, 200.0); + let synth::Node::Chunk(_, mcfg) = mcfg else { panic!() }; + let n = mcfg.len() as u32; + for (root, list, damaged) in [ + (redirect(b"mcfg", 0, n, 0), &b"data1.dat"[..], false), + (redirect(b"mcfg", 0, n, 0), b"data1.dat\r\n", false), + (redirect(b"mcfg", 0, n + 1, 0), b"data1.dat", true), + (redirect(b"mcfg", 0, n, u32::MAX), b"data1.dat", true), + (redirect(b"mcfg", 1, n, 0), b"data1.dat", true), + (redirect(b"mcfg", 0, n, 0), b"gone.dat", true), + (redirect(b"mcfg", 0, n, 0), b"", true), + ] { + let mut body = b"LIST".to_vec(); + body.extend(((root.len() + 4) as u32).to_le_bytes()); + body.extend(b"doc "); + body.extend(&root); + let d = read(&raw_package(&body, &mcfg, list), Limits::default()).unwrap(); + assert_eq!(d.warnings.contains(&Warning::Damaged), damaged, "{list:?} {:?}", &root[8..]); + assert_eq!(d.page_size.is_some(), !damaged); + } +} + +#[test] +fn a_redirect_record_holds_up_to_8_bytes_itself() { + let mut inline = b"vrsn".to_vec(); + inline.extend(16u32.to_le_bytes()); + inline.extend(u32::MAX.to_le_bytes()); + inline.extend(2u32.to_le_bytes()); + inline.extend(1800u16.to_le_bytes()); + inline.extend([0; 6]); + let d = read(&raw_package(&inline, b"", b""), Limits::default()).unwrap(); + assert_eq!(d.version, 1800); + // A length past the record's 8 bytes is damage, and the form type's version stands. + inline[12] = 9; + let d = read(&raw_package(&inline, b"", b""), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged)); + assert_eq!(d.version, 1700); +} + +fn zip_of(members: &[(&str, Vec)]) -> Vec { + let m: Vec<_> = members.iter().map(|(n, d)| synth::Member { name: (*n).into(), data: d.clone(), deflate: false }).collect(); + synth::zip(&m, b"") +} + +/// Where the first central directory entry starts. +fn directory(bytes: &[u8]) -> usize { + bytes.windows(4).position(|w| w == b"PK\x01\x02").unwrap() +} + +#[test] +fn hostile_packages_are_refused() { + let riff = synth::sample(1400, false); + let good = zip_of(&[("content/riffData.cdr", riff.clone())]); + assert!(read(&good, Limits::default()).is_ok()); + // More members than a read takes. + let many: Vec<(String, Vec)> = (0..4097).map(|i| (format!("m{i}"), vec![])).collect(); + let many: Vec<(&str, Vec)> = many.iter().map(|(n, d)| (n.as_str(), d.clone())).collect(); + assert_eq!(read(&zip_of(&many), Limits::default()), Err(Error::Limit("package member count"))); + assert_eq!(read(&zip_of(&many[..4096]), Limits::default()), Err(Error::NotCdr)); + // A member named twice. + let twice = zip_of(&[("content/riffData.cdr", riff.clone()), ("content/riffData.cdr", riff.clone())]); + assert_eq!(read(&twice, Limits::default()), Err(Error::Damaged("package member named twice"))); + // A member whose bytes run into the next member's header. + let two = zip_of(&[("a", vec![1; 10]), ("content/riffData.cdr", riff.clone())]); + let mut overlap = two.clone(); + let at = directory(&two) + 20; + overlap[at..at + 4].copy_from_slice(&20u32.to_le_bytes()); + assert_eq!(read(&overlap, Limits::default()), Err(Error::Damaged("package members overlap"))); + // A central directory cut short, and an archive without its end record. + let mut short = good.clone(); + let n = short.len(); + let len_at = n - 22 + 12; + let len = u32::from_le_bytes(short[len_at..len_at + 4].try_into().unwrap()); + short[len_at..len_at + 4].copy_from_slice(&(len - 10).to_le_bytes()); + assert_eq!(read(&short, Limits::default()), Err(Error::Damaged("package directory"))); + assert_eq!(read(&good[..directory(&good) + 30], Limits::default()), Err(Error::Damaged("package directory"))); + // Encrypted members, ZIP64 fields and archives split across files. + let mut encrypted = good.clone(); + encrypted[directory(&good) + 8] |= 1; + assert_eq!(read(&encrypted, Limits::default()), Err(Error::Unsupported("encrypted packages"))); + let mut zip64 = good.clone(); + zip64[n - 22 + 10..n - 22 + 12].copy_from_slice(&[0xff, 0xff]); + assert_eq!(read(&zip64, Limits::default()), Err(Error::Unsupported("ZIP64 packages"))); + let mut split = good.clone(); + split[n - 22 + 4] = 1; + assert_eq!(read(&split, Limits::default()), Err(Error::Unsupported("packages split across files"))); +} + +#[test] +fn a_package_member_bomb_stops_at_its_stated_size_or_the_limit() { + let riff = synth::sample(1400, false); + let m = synth::Member { name: "content/riffData.cdr".into(), data: riff.clone(), deflate: true }; + let good = synth::zip(std::slice::from_ref(&m), b""); + assert!(read(&good, Limits::default()).is_ok()); + // A member that inflates past the size its entry states stops one byte past it. + let bomb = synth::zip(&[synth::Member { data: [riff.clone(), vec![0; 64 << 20]].concat(), ..m.clone() }], b""); + assert!(bomb.len() < 1 << 20); + let mut lying = bomb.clone(); + let at = directory(&bomb) + 24; + lying[at..at + 4].copy_from_slice(&(riff.len() as u32).to_le_bytes()); + assert_eq!(read(&lying, Limits::default()), Err(Error::Damaged("package member"))); + // One that states more than a member may hold, or than is left to inflate, is not inflated. + assert_eq!(read(&bomb, Limits { member: 1 << 20, ..Limits::default() }), Err(Error::Limit("package member size"))); + assert_eq!(read(&bomb, Limits { inflated: 1 << 20, ..Limits::default() }), Err(Error::Limit("inflated size"))); +} + +#[test] +fn stored_package_members_take_nothing_from_the_inflate_limit() { + // Nothing may be inflated, and the stored members of either package layout still read, as + // the same drawing does as a plain RIFF file. + let none = Limits { inflated: 0, ..Limits::default() }; + assert!(read(&synth::sample(1400, false), none).is_ok()); + for version in [1400, 1700] { + let d = read(&synth::sample_file(version, false), none).unwrap_or_else(|e| panic!("{version}: {e}")); + assert!(d.warnings.iter().all(|w| *w == Warning::UnsupportedObjects), "{version}: {:?}", d.warnings); + check_shapes(&d, version); + } + // Deflated members do take from it. + assert_eq!(read(&synth::sample_file(1400, true), none), Err(Error::Limit("inflated size"))); +} + +#[test] +fn redirect_records_that_lead_nowhere_count_toward_the_chunk_limit() { + // 3,000 redirects to a stream the package lacks: each lost record is counted. + let root: Vec = (0..3000).flat_map(|_| redirect(b"mcfg", 7, 4, 0)).collect(); + let file = raw_package(&root, b"", b"data1.dat"); + assert_eq!(read(&file, Limits { chunks: 2_000, ..Limits::default() }), Err(Error::Limit("chunk count"))); + let d = read(&file, Limits { chunks: 4_000, ..Limits::default() }).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); +} + +#[test] +fn rectangles_from_version_15_give_radii_as_shares_of_half_the_shorter_side() { + let v = V(1500); + let mut c = synth::V(1500).rect(100.0, 50.0, 0.0); + // The four shares: 0.2, 0.4, 0, and 3, which half the shorter side holds to 25 pt. + for (k, share) in [0.2f64, 0.4, 0.0, 3.0].iter().enumerate() { + let at = 40 + 24 * k; + c[at..at + 8].copy_from_slice(&share.to_le_bytes()); + } + let file = + synth::riff(1500, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &[(30, c.clone())], None)])])]); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Geometry::Rect { w, h, radii } = s[0].geometry else { panic!("{:?}", s[0].geometry) }; + assert!((w - 100.0).abs() < 1e-6 && (h - 50.0).abs() < 1e-6); + for (got, want) in radii.iter().zip([5.0, 10.0, 0.0, 25.0]) { + assert!((got - want).abs() < 1e-6, "{radii:?}"); + } + // With the scale-with flag set the radii are inches, held to half the shorter side as well. + c[32] = 1; + let file = synth::riff(1500, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &[(30, c)], None)])])]); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Geometry::Rect { radii, .. } = s[0].geometry else { panic!("{:?}", s[0].geometry) }; + for (got, want) in radii.iter().zip([14.4, 25.0, 0.0, 25.0]) { + assert!((got - want).abs() < 1e-6, "{radii:?}"); + } +} + +#[test] +fn paths_from_version_10_read_their_points() { + let v = V(1700); + let mut c = vec![0; 4]; + c.extend(2u16.to_le_bytes()); + c.extend(1u16.to_le_bytes()); + c.extend([0; 16]); + c.extend(&v.points(&[(0.0, 0.0, 0x08), (50.0, 0.0, 0x40), (50.0, 20.0, 0x48)])[4..]); + let objects = |version: u16| { + let v = V(version); + synth::riff( + version, + &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 0x25, &[(30, c.clone())], None)])])], + ) + }; + for version in [1000, 1300, 1500, 1700] { + let d = read(&objects(version), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Geometry::Path(p) = &s[0].geometry else { panic!("{version}: {:?}", s[0].geometry) }; + assert_eq!(p.subpaths[0].segments.len(), 2); + assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings); + } + // No sample before version 10 holds the type, so it is not read as a path there. + let d = read(&objects(900), Limits::default()).unwrap(); + assert!(d.pages[0].layers[0].objects.is_empty() && d.warnings.contains(&Warning::UnsupportedObjects)); +} + +#[test] +fn a_template_takes_its_version_from_the_vrsn_chunk() { + let mut file = synth::sample(2100, false); + file[8..12].copy_from_slice(b"CDTQ"); + assert!(vectorcraft_cdr::is_cdr(&file)); + let d = read(&file, Limits::default()).unwrap(); + assert_eq!(d.version, 2100); + check_shapes(&d, 2100); + let mut bare = synth::riff(2100, &[]); + bare[8..12].copy_from_slice(b"CDTQ"); + assert_eq!(read(&bare, Limits::default()), Err(Error::NotCdr)); + // A template of a version after 27 is refused by its version, and one before 3 as a RIFF + // file of those versions. + for (version, refused) in [(2800u16, Error::Version(2800)), (200, Error::Unsupported("RIFF files of versions before 3"))] { + let mut t = synth::riff(2100, &[chunk(b"vrsn", version.to_le_bytes().to_vec())]); + t[8..12].copy_from_slice(b"CDTQ"); + assert_eq!(read(&t, Limits::default()), Err(refused)); + } +} + +#[test] +fn layers_take_their_kind_from_their_object_type() { + for version in [300, 800, 1300, 1700] { + let v = V(version); + let rect = || synth::object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0))], None); + // Version 3 counts its types from 0 (R32). + let ty = |t: u32| if version < 400 { t - 1 } else { t }; + // Master page layers flagged in the older way, with the types of guides and desktop layers, + // and a drawing layer whose flags would make it a desktop layer. + let master = synth::page( + true, + vec![ + synth::layer_of_type(v, [2, 1, 1, 0x98], ty(12), "G", vec![rect()]), + synth::layer_of_type(v, [0, 1, 1, 0x98], ty(17), "D", vec![rect()]), + synth::layer_of_type(v, [8, 1, 0, 0x98], 0, "M", vec![rect()]), + ], + ); + // A drawing layer with flag bit 0x10 set, and a grid layer. + let own = synth::page( + false, + vec![ + synth::layer_of_type(v, [0x10, 0, 0, 0x98], 0, "L", vec![rect()]), + synth::layer_of_type(v, [0x1a, 0, 1, 0x98], ty(11), "Grid", vec![rect()]), + ], + ); + let body = [chunk(b"vrsn", version.to_le_bytes().to_vec()), master, own]; + let file = if version < 1400 { synth::riff(version, &body) } else { synth::package16(version, &body, true, &[]) }; + let d = read(&file, Limits::default()).unwrap(); + let kinds: Vec<_> = d.master.iter().map(|l| l.kind).collect(); + assert_eq!(kinds, [LayerKind::Guides, LayerKind::Desktop, LayerKind::Drawing], "{version}"); + let kinds: Vec<_> = d.pages[0].layers.iter().map(|l| (l.kind, l.objects.len())).collect(); + assert_eq!(kinds, [(LayerKind::Drawing, 1), (LayerKind::Grid, 1)], "{version}"); + } +} + +#[test] +fn a_lower_case_form_type_names_the_same_versions() { + let mut file = synth::sample(600, false); + file[8..12].copy_from_slice(b"cdr6"); + // The `vrsn` chunk agrees; without it the form type alone decides. + assert_eq!(read(&file, Limits::default()).unwrap().version, 600); + assert!(vectorcraft_cdr::is_cdr(&file)); + file[8..12].copy_from_slice(b"cdrX"); + assert_eq!(read(&file, Limits::default()), Err(Error::NotCdr)); +} + +#[test] +fn rectangles_keep_four_corner_radii_from_version_9() { + let v = V(900); + let c = [v.coord(100.0), v.coord(50.0), v.coord(1.0), v.coord(2.0), v.coord(3.0), v.coord(4.0)].concat(); + let file = synth::riff(900, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &[(30, c)], None)])])]); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Geometry::Rect { radii, .. } = s[0].geometry else { panic!("{:?}", s[0].geometry) }; + for (got, want) in radii.iter().zip([1.0, 2.0, 3.0, 4.0]) { + assert!((got - want).abs() < 0.01, "{radii:?}"); + } + // Before version 9 one radius rounds every corner. + let v = V(800); + let c = [v.coord(100.0), v.coord(50.0), v.coord(6.0)].concat(); + let file = synth::riff(800, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &[(30, c)], None)])])]); + let s = read(&file, Limits::default()).unwrap(); + let s = shapes(&s.pages[0].layers[0].objects); + assert!(matches!(s[0].geometry, Geometry::Rect { radii, .. } if radii.iter().all(|r| (r - 6.0).abs() < 0.01))); +} + +#[test] +fn version_7_guidelines_count_toward_the_object_limit() { + let v = V(700); + let mut guid = 1000u32.to_le_bytes().to_vec(); + guid.extend(1000u32.to_le_bytes()); + for i in 0..1000 { + guid.extend([0; 12]); + guid.extend(90_000_000i32.to_le_bytes()); + guid.extend([v.coord(f64::from(i)), v.coord(0.0), v.coord(f64::from(i)), v.coord(1.0), v.coord(f64::from(i)), v.coord(0.0)].concat()); + } + let file = synth::riff(700, &[chunk(b"vrsn", 700u16.to_le_bytes().to_vec()), list(b"doc ", vec![chunk(b"guid", guid)])]); + let d = read(&file, Limits::default()).unwrap(); + assert_eq!(d.guides.len(), 1000); + let d = read(&file, Limits { objects: 10, ..Limits::default() }).unwrap(); + assert_eq!(d.guides.len(), 10); + assert!(d.warnings.contains(&Warning::TooDeep)); +} + +/// Guidelines on any layer of the master page show on every page, not only those of its guides +/// layer: one on a drawing layer that also holds art, and one alone on the desktop layer. +#[test] +fn master_guidelines_on_any_layer_show_on_every_page() { + let v = V(1100); + let guide = |x: f64| { + let mut g = vec![0; 12]; + g.extend(90_000_000i32.to_le_bytes()); + g.extend([v.coord(x), v.coord(0.0)].concat()); + synth::object(v, 0x16, &[(16000, g)], None) + }; + let rect = synth::object(v, 1, &[(30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + let master = synth::page( + true, + vec![synth::layer(v, [0, 0, 1, 0x98], "Art", vec![guide(10.0), rect]), synth::layer(v, [0x08, 0, 1, 0x98], "Desktop", vec![guide(20.0)])], + ); + let file = synth::riff(1100, &[master, synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "Art", vec![])])]); + let d = read(&file, Limits::default()).unwrap(); + let mut xs: Vec = d.guides.iter().map(|g| g.at.x).collect(); + xs.sort_by(f64::total_cmp); + assert_eq!(xs.len(), 2, "{:?}", d.guides); + assert!((xs[0] - 10.0).abs() < 0.01 && (xs[1] - 20.0).abs() < 0.01, "{xs:?}"); + assert_eq!(d.master.len(), 1); + assert_eq!(d.master[0].objects.len(), 1); +} + +/// An object with more arguments than the limit keeps the ones read paired with their own types: +/// the types table runs from the stored count, not from the limit. +#[test] +fn arguments_past_the_limit_leave_the_first_ones_paired_with_their_types() { + let v = V(1100); + let mut args = vec![(30, [v.coord(40.0), v.coord(20.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())]; + args.extend((0..69).map(|i| (500 + i, vec![0; 4]))); + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &args, None)])])]); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert!( + matches!(s.first().map(|s| &s.geometry), Some(Geometry::Rect { w, h, .. }) if (w - 40.0).abs() < 0.01 && (h - 20.0).abs() < 0.01), + "{s:?}" + ); + assert!(d.warnings.contains(&Warning::Damaged)); +} + +/// Groups count toward the object limit; a group past it leaves its objects ungrouped. +#[test] +fn groups_count_toward_the_object_limit() { + fn count(objects: &[Object]) -> usize { + objects.iter().map(|o| 1 + if let Object::Group { objects: kids, .. } = o { count(kids) } else { 0 }).sum() + } + let v = V(1100); + let rect = synth::object(v, 1, &[(30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + let nested = list(b"grp ", vec![list(b"grp ", vec![rect])]); + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![nested])])]); + let d = read(&file, Limits { objects: 2, ..Limits::default() }).unwrap(); + let objects = &d.pages[0].layers[0].objects; + assert_eq!(count(objects), 2, "{objects:?}"); + assert!(matches!(objects.as_slice(), [Object::Group { objects: kids, .. }] if matches!(kids.as_slice(), [Object::Shape(_)])), "{objects:?}"); + assert!(d.warnings.contains(&Warning::TooDeep)); +} + +/// A rectangle, ellipse, curve or polygon stored without its coordinates is left out as damage. +#[test] +fn shapes_without_their_coordinates_are_damage() { + let v = V(1100); + for kind in [1, 2, 3, 0x14] { + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, kind, &[], None)])])]); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.pages[0].layers[0].objects.is_empty(), "{kind}"); + assert!(d.warnings.contains(&Warning::Damaged), "{kind}: {:?}", d.warnings); + } +} + +/// An object list without its `loda`, a fill or outline record that can't be read, and a `guid` +/// chunk that counts more guidelines than it holds are each damage. +#[test] +fn unreadable_records_and_lists_are_damage() { + let v = V(1300); + let rect = |args: Vec<(u32, Vec)>| { + let mut args = args; + args.push((30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())); + synth::object(v, 1, &args, None) + }; + let on_page = |objects: Vec, styles: Vec| { + let mut kids = vec![chunk(b"vrsn", 1300u16.to_le_bytes().to_vec())]; + kids.extend(styles); + kids.push(synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", objects)])); + read(&synth::riff(1300, &kids), Limits::default()).unwrap() + }; + let d = on_page(vec![list(b"obj ", vec![chunk(b"flgs", vec![0, 0, 0, 0x08])])], vec![]); + assert!(d.warnings.contains(&Warning::Damaged), "no loda: {:?}", d.warnings); + // A fill record of only its id. + let d = on_page(vec![rect(vec![(20, 4u32.to_le_bytes().to_vec())])], vec![list(b"filt", vec![chunk(b"fild", 4u32.to_le_bytes().to_vec())])]); + assert_eq!(shapes(&d.pages[0].layers[0].objects)[0].fill, None); + assert!(d.warnings.contains(&Warning::Damaged), "fill: {:?}", d.warnings); + // A tagged outline whose first records are none of record 1. + let mut outl = 9u32.to_le_bytes().to_vec(); + for _ in 0..16 { + outl.extend(5u32.to_le_bytes()); + outl.extend(0u32.to_le_bytes()); + } + let d = on_page(vec![rect(vec![(10, 9u32.to_le_bytes().to_vec())])], vec![list(b"otlt", vec![chunk(b"outl", outl)])]); + assert!(shapes(&d.pages[0].layers[0].objects)[0].outline.is_none()); + assert!(d.warnings.contains(&Warning::Damaged), "outline: {:?}", d.warnings); + // Version 7: a `guid` chunk counting three guidelines and holding one. + let mut guid = 3u32.to_le_bytes().to_vec(); + guid.extend(3u32.to_le_bytes()); + guid.extend([0; 40]); + let d = read(&synth::riff(700, &[chunk(b"vrsn", 700u16.to_le_bytes().to_vec()), list(b"doc ", vec![chunk(b"guid", guid)])]), Limits::default()) + .unwrap(); + assert_eq!(d.guides.len(), 1); + assert!(d.warnings.contains(&Warning::Damaged), "guid: {:?}", d.warnings); +} + +/// Pages keep their layers in a `gobj` list, and layers and objects their `loda` (and objects +/// their transform) in a `lgob` list. The layout with those chunks directly in the page, layer and +/// object lists reads the same. +#[test] +fn layers_and_objects_read_from_their_gobj_and_lgob_lists() { + let v = V(1000); + let c = [v.coord(10.0), v.coord(20.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat(); + let m = [1.0, 0.0, 0.0, 1.0, 5.0, 6.0]; + let nested = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &[(30, c.clone())], Some(m))])]); + let plain_object = list(b"obj ", vec![chunk(b"loda", v.loda(1, &[(30, c)])), list(b"trfl", vec![chunk(b"trfd", v.trfd(&[m]))])]); + let plain_layer = list(b"layr", vec![chunk(b"flgs", vec![0, 0, 0, 0x98]), chunk(b"loda", v.loda(0, &[(1000, b"L\0".to_vec())])), plain_object]); + let plain = list(b"page", vec![chunk(b"flgs", vec![0, 0, 0, 0x90]), plain_layer]); + for page in [nested, plain] { + let d = read(&synth::riff(1000, &[page]), Limits::default()).unwrap(); + let layer = &d.pages[0].layers[0]; + assert_eq!(layer.name, "L"); + let s = shapes(&layer.objects); + assert_eq!(s.len(), 1, "{:?}", layer.objects); + assert!(matches!(s[0].geometry, Geometry::Rect { w, .. } if (w - 10.0).abs() < 0.01)); + assert!((s[0].matrix.0[4] - 5.0).abs() < 0.01 && (s[0].matrix.0[5] - 6.0).abs() < 0.01, "{:?}", s[0].matrix); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + } +} + +/// From version 7 a `LIST stlt` holds the style tables, which don't parse as chunks: it is not +/// damage. +#[test] +fn a_style_table_list_is_not_read_as_chunks() { + let v = V(1000); + let stlt = chunk(b"LIST", [b"stlt".to_vec(), 3u32.to_le_bytes().to_vec(), vec![0xff; 30]].concat()); + let d = read(&synth::riff(1000, &[list(b"doc ", vec![stlt, synth::mcfg(v, 100.0, 50.0)])]), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + assert!(d.page_size.is_some_and(|(w, h)| (w - 100.0).abs() < 0.01 && (h - 50.0).abs() < 0.01)); +} + +/// Before version 7 a `LIST stlt` holds chunks (R4), which are read like the document's others. +#[test] +fn a_style_list_before_version_7_is_read_as_chunks() { + for version in [400, 500, 600] { + let v = V(version); + let red = if version < 500 { synth::color4(1, [0, 100, 100, 0]) } else { synth::color(5, [0, 0, 255, 0]) }; + let styles = list(b"stlt", vec![list(b"filt", vec![chunk(b"fill", v.fill(1, &red))])]); + let rect = synth::object(v, 1, &[(20, 1u32.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))], None); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect])]); + let content = vec![list(b"doc ", vec![styles]), page]; + let d = read(&synth::file_of(version, content.clone()), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(s[0].fill.is_some(), "{version}"); + assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings); + // A template, whose form type names no version, by its `vrsn` chunk. + let mut template = synth::file_of(version, content); + template[8..12].copy_from_slice(b"CDTA"); + let d = read(&template, Limits::default()).unwrap(); + assert!(shapes(&d.pages[0].layers[0].objects)[0].fill.is_some(), "{version}"); + } +} + +/// The objects of a styled drawing: a rectangle with only its style (argument 200), one whose +/// style leaves the fill and outline to its parent, and one with an outline argument of its own. +fn graphic_style_drawing(version: u16, table: synth::Node) -> Vec { + let v = V(version); + let black = synth::color(2, [0, 0, 0, 100]); + let doc = list( + b"doc ", + vec![ + synth::mcfg(v, 612.0, 792.0), + list(b"filt", vec![chunk(if version >= 700 { b"fild" } else { b"fill" }, v.fill(1, &synth::color(5, [0, 0, 255, 0])))]), + list( + b"otlt", + vec![ + chunk(b"outl", v.outline(2, synth::Pen { line_type: 0, width: 2.0, cap: 1, join: 1 }, &black, &[])), + chunk(b"outl", v.outline(3, synth::Pen { line_type: 1, width: 1.0, cap: 0, join: 0 }, &black, &[])), + ], + ), + table, + ], + ); + let rect = (30, v.rect(20.0, 10.0, 0.0)); + let styled = |style: u32, own: &[(u32, Vec)]| { + let mut args = vec![(200, style.to_le_bytes().to_vec())]; + args.extend(own.iter().cloned()); + args.push(rect.clone()); + synth::object(v, 1, &args, None) + }; + let objects = vec![styled(0x10, &[]), styled(0x11, &[]), styled(0x10, &[(10, 3u32.to_le_bytes().to_vec())])]; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", objects)]); + synth::file_of(version, vec![doc, page]) +} + +/// From version 7 an object without a fill or outline argument of its own takes its style's +/// (argument 200, `LIST stlt`), through the style's parent where the style names none; its own +/// argument wins over the style's. +#[test] +fn objects_without_their_own_fill_or_outline_take_their_styles() { + let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }]; + for version in [700, 800, 801, 900, 1000, 1100, 1200, 1300, 1400, 1500] { + for text in [false, true] { + let table = synth::stlt(V(version), &[(0x100, 1)], &[(0x200, 2)], &styles, text); + let d = read(&graphic_style_drawing(version, table), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s.len(), 3, "{version}"); + for shape in &s[..2] { + assert_eq!(shape.fill, Some(Color::Rgb([1.0, 0.0, 0.0])), "{version} {text}"); + assert!(shape.outline.as_ref().is_some_and(|o| (o.width - 2.0).abs() < 0.05), "{version} {text}: {:?}", shape.outline); + } + assert_eq!(s[2].fill, Some(Color::Rgb([1.0, 0.0, 0.0])), "{version} {text}"); + assert!(s[2].outline.is_none(), "{version} {text}"); + assert!(d.warnings.is_empty(), "{version} {text}: {:?}", d.warnings); + } + } +} + +/// A template whose style table comes before its `vrsn` chunk still reads the table by the +/// version that chunk names. +#[test] +fn a_style_table_before_the_version_chunk_reads_by_that_version() { + let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }]; + let table = synth::stlt(V(1000), &[(0x100, 1)], &[(0x200, 2)], &styles, true); + let mut file = graphic_style_drawing(1000, chunk(b"junk", vec![])); + // The drawing's chunks, the table put first, ahead of `vrsn`. + let body = file.split_off(12); + file.extend(synth::plain(&table)); + file.extend(body); + file[8..12].copy_from_slice(b"CDTA"); + let len = (file.len() - 8) as u32; + file[4..8].copy_from_slice(&len.to_le_bytes()); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s[0].fill, Some(Color::Rgb([1.0, 0.0, 0.0]))); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); +} + +/// A style table that doesn't parse to its end is damage when an object needs a style from it; +/// the object is drawn with what it holds itself. +#[test] +fn a_style_table_that_does_not_parse_is_damage_when_an_object_needs_it() { + let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }]; + let mut body = synth::stlt_body(V(1000), &[(0x100, 1)], &[(0x200, 2)], &styles, true); + body.push(0); + let table = chunk(b"LIST", [b"stlt".to_vec(), body].concat()); + let d = read(&graphic_style_drawing(1000, table), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s.len(), 3); + assert!(s[0].fill.is_none() && s[0].outline.is_none()); + assert_eq!(d.warnings, vec![Warning::Damaged]); +} + +/// A drawing with fill 1 (red), whose `LIST clpt` holds `groups` and whose page holds `objects`. +fn clip_drawing(version: u16, groups: Vec<(u32, Vec)>, objects: Vec) -> Vec { + let v = V(version); + let doc = list( + b"doc ", + vec![ + synth::mcfg(v, 612.0, 792.0), + list(b"filt", vec![chunk(if version >= 700 { b"fild" } else { b"fill" }, v.fill(1, &synth::color(5, [0, 0, 255, 0])))]), + synth::clpt(groups), + ], + ); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", objects)]); + synth::file_of(version, vec![doc, page]) +} + +fn clip_rect(v: V, w: f64, extra: &[(u32, Vec)], at: [f64; 2]) -> synth::Node { + let mut args = vec![(20, 1u32.to_le_bytes().to_vec()), (30, v.rect(w, w, 0.0))]; + args.extend(extra.iter().cloned()); + synth::object(v, 1, &args, Some([1.0, 0.0, 0.0, 1.0, at[0], at[1]])) +} + +/// A container (argument 8005) clips the group of `LIST clpt` whose `spnd` id it names; the +/// group's objects keep their own transforms, front to back. +#[test] +fn a_container_clips_the_group_it_names() { + for version in [700, 900, 1200, 1300, 1500, 1600, 2000] { + let v = V(version); + let contents = vec![clip_rect(v, 10.0, &[], [5.0, 6.0]), clip_rect(v, 20.0, &[], [-50.0, 0.0])]; + let container = clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0]); + let d = read(&clip_drawing(version, vec![(0x77, contents)], vec![container]), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let objects = &d.pages[0].layers[0].objects; + let [Object::Clip { container, objects: clipped }] = objects.as_slice() else { panic!("{version}: {objects:?}") }; + assert!(matches!(container.geometry, Geometry::Rect { w, .. } if (w - 40.0).abs() < 0.01), "{version}"); + let s = shapes(clipped); + assert_eq!(s.len(), 2, "{version}"); + assert!((s[0].matrix.0[4] - 5.0).abs() < 0.01 && (s[1].matrix.0[4] + 50.0).abs() < 0.01, "{version}: {:?}", s[0].matrix); + assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings); + } +} + +/// The feature sample, the seed of the importer's fuzz tests, reads its style table, clipping +/// container, lens, flags, winding flag, transparency and named outline color in every version +/// from 7 to 13, plain and compressed. +#[test] +fn the_feature_sample_reads_its_styles_container_and_lens() { + for version in [700, 800, 900, 1000, 1100, 1200, 1300] { + for compress in [false, true] { + let d = read(&synth::feature_sample(version, compress), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let objects = &d.pages[0].layers[0].objects; + let [ + Object::Shape(styled), + Object::Clip { objects: clipped, .. }, + Object::Shape(_), + Object::Shape(flagged), + Object::Group { objects: grouped, flags }, + ] = objects.as_slice() + else { + panic!("{version}: {objects:?}") + }; + assert_eq!(styled.fill, Some(Color::Rgb([1.0, 0.0, 0.0])), "{version}"); + assert!(styled.outline.as_ref().is_some_and(|o| o.dashes == [3.0, 1.0]), "{version}"); + let s = shapes(clipped); + assert_eq!(s.len(), 2, "{version}"); + assert!(s[1].outline.as_ref().is_some_and(|o| o.behind_fill), "{version}"); + assert_eq!(flagged.flags, Flags { hidden: true, locked: true }, "{version}"); + assert!(flagged.nonzero, "{version}"); + assert_eq!(*flags, Flags { hidden: true, locked: false }, "{version}"); + let named = shapes(grouped)[0].outline.as_ref().map(|o| o.color.clone()); + // A transparency and a named outline color are read from version 13. + if version >= 1300 { + assert_eq!((flagged.opacity, flagged.blend), (0.75, Blend::Multiply), "{version}"); + assert_eq!(named, Some(Color::Spot { name: "Sky Blue".into(), tint: 1.0, look: Some([1.0, 0.0, 0.0]) }), "{version}"); + assert_eq!(d.warnings, vec![Warning::Lenses], "{version} {compress}"); + } else { + assert_eq!((flagged.opacity, flagged.blend), (1.0, Blend::Normal), "{version}"); + assert_eq!(named, Some(Color::Spot { name: "Spot 0:7".into(), tint: 1.0, look: None }), "{version}"); + assert_eq!(d.warnings, vec![Warning::Lenses, Warning::SpotLooks], "{version} {compress}"); + } + } + } +} + +/// A container whose group isn't there is damage, and one whose group holds a container naming +/// it again is read once, with the limit warning; the containers stay as plain shapes. +#[test] +fn a_missing_or_repeating_clipped_group_keeps_the_container() { + let v = V(1100); + let missing = clip_rect(v, 40.0, &[synth::container(0x78)], [0.0, 0.0]); + let d = read(&clip_drawing(1100, vec![(0x77, vec![clip_rect(v, 10.0, &[], [0.0, 0.0])])], vec![missing]), Limits::default()).unwrap(); + assert!(matches!(d.pages[0].layers[0].objects.as_slice(), [Object::Shape(_)])); + assert_eq!(d.warnings, vec![Warning::Damaged]); + let inner = clip_rect(v, 10.0, &[synth::container(0x77)], [0.0, 0.0]); + let outer = clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0]); + let d = read(&clip_drawing(1100, vec![(0x77, vec![inner])], vec![outer]), Limits::default()).unwrap(); + let [Object::Clip { objects: clipped, .. }] = d.pages[0].layers[0].objects.as_slice() else { panic!("{:?}", d.pages[0].layers[0].objects) }; + assert!(matches!(clipped.as_slice(), [Object::Shape(_)]), "{clipped:?}"); + assert_eq!(d.warnings, vec![Warning::TooDeep]); +} + +/// Each chunk of a clipped group counts toward the clipped chunk limit every time a container +/// names the group, empty groups included; past it the containers stay as plain shapes, and a +/// group cut off at the limit leaves out its guidelines too. +#[test] +fn containers_naming_one_group_stop_at_the_clipped_chunk_limit() { + let v = V(1100); + // The group walks 53 chunks: its `spnd`, a guideline, 50 empty groups and a rectangle. + let mut guide = vec![0; 12]; + guide.extend(90_000_000i32.to_le_bytes()); + guide.extend([v.coord(36.0), v.coord(0.0)].concat()); + let mut contents = vec![synth::object(v, 0x16, &[(16000, guide)], None)]; + contents.extend((0..50).map(|_| list(b"grp ", vec![]))); + contents.push(clip_rect(v, 10.0, &[], [0.0, 0.0])); + let containers: Vec = (0..20).map(|_| clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0])).collect(); + let file = clip_drawing(1100, vec![(0x77, contents)], containers); + let count = |objects: &[Object]| objects.iter().filter(|o| matches!(o, Object::Clip { .. })).count(); + let d = read(&file, Limits::default()).unwrap(); + assert_eq!((count(&d.pages[0].layers[0].objects), d.pages[0].layers[0].guides.len()), (20, 20)); + assert!(d.warnings.is_empty(), "{:?}", d.warnings); + // The sixth container's walk stops after its guideline and 8 empty groups. + let d = read(&file, Limits { clipped_chunks: 53 * 5 + 10, ..Limits::default() }).unwrap(); + let layer = &d.pages[0].layers[0]; + assert_eq!((layer.objects.len(), count(&layer.objects), layer.guides.len()), (20, 5, 5)); + assert_eq!(d.warnings, vec![Warning::TooDeep]); +} + +/// A container, fill, outline or style argument too short for the id it names is damage: the +/// shape comes in as a plain shape without that id. +#[test] +fn an_id_argument_cut_short_is_damage() { + for version in [700, 1100, 1600] { + let v = V(version); + let group = vec![(0x77, vec![clip_rect(v, 10.0, &[], [0.0, 0.0])])]; + let container = clip_rect(v, 40.0, &[(8005, vec![0x77, 0, 0])], [0.0, 0.0]); + let d = read(&clip_drawing(version, group, vec![container]), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + assert!(matches!(d.pages[0].layers[0].objects.as_slice(), [Object::Shape(_)]), "{version}: {:?}", d.pages[0].layers[0].objects); + assert_eq!(d.warnings, vec![Warning::Damaged], "{version}"); + for kind in [20, 10, 200] { + let short = synth::object(v, 1, &[(kind, vec![1, 0]), (30, v.rect(10.0, 10.0, 0.0))], None); + let d = read(&clip_drawing(version, vec![], vec![short]), Limits::default()).unwrap_or_else(|e| panic!("{version} {kind}: {e}")); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(s.len() == 1 && s[0].fill.is_none() && s[0].outline.is_none(), "{version} {kind}"); + assert_eq!(d.warnings, vec![Warning::Damaged], "{version} {kind}"); + } + } +} + +/// A fill or outline id that no record has is damage: the shape comes in without that paint. Id 0 +/// without a record is no paint. +#[test] +fn a_fill_or_outline_without_its_record_is_damage() { + for version in [700, 1100, 1600] { + let v = V(version); + for kind in [20, 10] { + for (id, want) in [(9u32, vec![Warning::Damaged]), (0, vec![])] { + let object = synth::object(v, 1, &[(kind, id.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))], None); + let d = + read(&clip_drawing(version, vec![], vec![object]), Limits::default()).unwrap_or_else(|e| panic!("{version} {kind} {id}: {e}")); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(s.len() == 1 && s[0].fill.is_none() && s[0].outline.is_none(), "{version} {kind} {id}"); + assert_eq!(d.warnings, want, "{version} {kind} {id}"); + } + } + } +} + +/// An object with a lens or transparency (argument 8000) comes in opaque, with the lenses +/// warning; one without the argument gives no warning. +#[test] +fn lenses_and_transparency_are_named_in_the_warnings() { + for (version, lens) in [(1000, [1u8, 0, 0, 0].to_vec()), (1200, [5, 0, 0, 0].to_vec()), (1500, [0x14, 5, 0, 0, 0x75, 0, 0, 0, 5].to_vec())] { + let v = V(version); + let plain = clip_rect(v, 10.0, &[], [0.0, 0.0]); + let d = read(&clip_drawing(version, vec![], vec![plain]), Limits::default()).unwrap(); + assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings); + let see_through = clip_rect(v, 10.0, &[(8000, lens)], [0.0, 0.0]); + let d = read(&clip_drawing(version, vec![], vec![see_through]), Limits::default()).unwrap(); + assert_eq!(shapes(&d.pages[0].layers[0].objects).len(), 1, "{version}"); + assert_eq!(d.warnings, vec![Warning::Lenses], "{version}"); + } +} + +/// From version 13 a uniform transparency (a 117-byte record of version 1300 in argument 8000) +/// gives the shape its opacity and blend mode, records of other versions before it skipped. A +/// lens record, a value outside 0 to 100, a merge mode without a blend mode, and the record in an +/// earlier version are not applied: the shape stays opaque, with the lenses warning. +#[test] +fn a_uniform_transparency_from_version_13_applies() { + let record = |since: u32, body: Vec| [since.to_le_bytes().to_vec(), (body.len() as u32).to_le_bytes().to_vec(), body].concat(); + for version in [1300, 1500, 1600, 2000] { + let v = V(version); + let read_with = |arg: Vec| { + let d = read(&clip_drawing(version, vec![], vec![clip_rect(v, 10.0, &[(8000, arg)], [0.0, 0.0])]), Limits::default()) + .unwrap_or_else(|e| panic!("{version}: {e}")); + let s = shapes(&d.pages[0].layers[0].objects)[0]; + ((s.opacity, s.blend), d.warnings) + }; + for (percent, merge, want) in [(25.0, 0, Blend::Normal), (0.0, 9, Blend::Multiply), (100.0, 28, Blend::Screen), (60.0, 36, Blend::Exclusion)] + { + let opacity = (1.0 - percent / 100.0) as f32; + assert_eq!(read_with(synth::transparency(percent, merge).1), ((opacity, want), vec![]), "{version} {percent} {merge}"); + } + // A record of a later version comes first. + let later = [record(1600, vec![0; 20]), synth::transparency(25.0, 0).1].concat(); + assert_eq!(read_with(later), ((0.75, Blend::Normal), vec![]), "{version}"); + let opaque = ((1.0, Blend::Normal), vec![Warning::Lenses]); + assert_eq!(read_with(record(1300, vec![0; 84])), opaque, "{version}: a lens"); + for bad in [150.0, -1.0, f64::NAN] { + assert_eq!(read_with(synth::transparency(bad, 0).1), opaque, "{version} {bad}"); + } + for merge in [1, 2, 3, 6, 7, 8, 10, 13, 18, 19, 20, 27, 37, 255] { + assert_eq!(read_with(synth::transparency(25.0, merge).1), opaque, "{version} {merge}"); + } + assert_eq!(read_with(vec![]), opaque, "{version}: empty"); + } + let d = + read(&clip_drawing(1200, vec![], vec![clip_rect(V(1200), 10.0, &[synth::transparency(25.0, 0)], [0.0, 0.0])]), Limits::default()).unwrap(); + assert_eq!(shapes(&d.pages[0].layers[0].objects)[0].opacity, 1.0); + assert_eq!(d.warnings, vec![Warning::Lenses]); +} + +/// Bit 0x01 of byte 1 of a layer's, group's or object's flags hides it and bit 0x10 of byte 0 +/// locks it, in every version; a group left ungrouped at the object limit passes its flags to its +/// objects. +#[test] +fn flags_hide_and_lock_layers_groups_and_objects() { + for version in [300, 700, 1100, 1300, 1600] { + let v = V(version); + let rect = |flags: [u8; 4]| synth::flagged(synth::object(v, 1, &[(30, v.rect(10.0, 10.0, 0.0))], None), flags); + let group = |flags: [u8; 4], objects: Vec| { + let mut kids = vec![chunk(b"flgs", flags.to_vec())]; + kids.extend(objects); + list(b"grp ", kids) + }; + let objects = vec![ + rect([0, 0, 0, 8]), + rect([0, 1, 0, 8]), + rect([0x10, 0, 0, 8]), + rect([0x10, 1, 0, 8]), + group([0x10, 1, 0, 0x10], vec![rect([0, 0, 0, 8])]), + ]; + let layers = + vec![synth::layer(v, [0, 0, 0, 0x98], "Shown", objects), synth::layer(v, [0x10, 1, 0, 0x98], "Hidden", vec![rect([0, 0, 0, 8])])]; + let file = synth::file_of(version, vec![synth::page(false, layers)]); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let [shown, hidden] = d.pages[0].layers.as_slice() else { panic!("{version}: {:?}", d.pages[0].layers) }; + assert_eq!(shown.flags, Flags::default(), "{version}"); + assert_eq!(hidden.flags, Flags { hidden: true, locked: true }, "{version}"); + let f = |hidden: bool, locked: bool| Flags { hidden, locked }; + let own: Vec = shown + .objects + .iter() + .map(|o| match o { + Object::Shape(s) => s.flags, + Object::Group { flags, .. } => *flags, + Object::Clip { container, .. } => container.flags, + }) + .collect(); + assert_eq!(own, [f(false, false), f(true, false), f(false, true), f(true, true), f(true, true)], "{version}"); + assert!( + matches!(&shown.objects[4], Object::Group { objects, .. } if matches!(&objects[0], Object::Shape(s) if s.flags == Flags::default())), + "{version}" + ); + assert!(d.warnings.contains(&Warning::UnsupportedObjects) || d.warnings.is_empty(), "{version}: {:?}", d.warnings); + // Past the object limit the group's rectangle comes in ungrouped, hidden and locked. + let d = read(&file, Limits { objects: 5, ..Limits::default() }).unwrap_or_else(|e| panic!("{version}: {e}")); + let last = d.pages[0].layers[0].objects.last(); + assert!(matches!(last, Some(Object::Shape(s)) if s.flags == f(true, true)), "{version}: {last:?}"); + } +} + +/// A guideline is hidden when its own object, a group around it or its layer is. +#[test] +fn hidden_guidelines_say_so() { + for version in [700, 1300, 1600] { + let v = V(version); + let guide = |flags: [u8; 4]| { + let mut arg = vec![0; 12]; + arg.extend(90_000_000i32.to_le_bytes()); + arg.extend([v.coord(36.0), v.coord(0.0)].concat()); + synth::flagged(synth::object(v, 0x16, &[(16000, arg)], None), flags) + }; + let group = list(b"grp ", vec![chunk(b"flgs", vec![0, 1, 0, 0x10]), guide([0, 0, 0, 8])]); + let layers = vec![ + synth::layer(v, [0, 0, 0, 0x98], "Shown", vec![guide([0, 0, 0, 8]), guide([0, 1, 0, 8]), group]), + synth::layer(v, [0, 1, 0, 0x98], "Hidden", vec![guide([0, 0, 0, 8])]), + ]; + let d = read(&synth::file_of(version, vec![synth::page(false, layers)]), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let hidden: Vec> = d.pages[0].layers.iter().map(|l| l.guides.iter().map(|g| g.hidden).collect()).collect(); + assert_eq!(hidden, [vec![false, true, true], vec![true]], "{version}"); + } +} + +/// Byte 0 of argument 14001 other than 0 fills the shape nonzero; 0, or no argument, fills it +/// even-odd; an argument without its byte is damage. +#[test] +fn a_winding_flag_fills_nonzero() { + for version in [300, 700, 1200, 1600] { + let v = V(version); + let read_with = |extra: &[(u32, Vec)]| { + let mut args = vec![(30, v.rect(10.0, 10.0, 0.0))]; + args.extend(extra.iter().cloned()); + let file = synth::file_of( + version, + vec![synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &args, None)])])], + ); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + (shapes(&d.pages[0].layers[0].objects)[0].nonzero, d.warnings) + }; + assert_eq!(read_with(&[(14001, vec![1, 0, 0, 0])]), (true, vec![]), "{version}"); + assert_eq!(read_with(&[(14001, vec![2])]), (true, vec![]), "{version}"); + assert_eq!(read_with(&[(14001, vec![0, 0, 0, 0])]), (false, vec![]), "{version}"); + assert_eq!(read_with(&[]), (false, vec![]), "{version}"); + assert_eq!(read_with(&[(14001, vec![])]), (false, vec![Warning::Damaged]), "{version}"); + } +} + +/// A `cdr8` form type makes the file the 8.01 variant whatever its `vrsn` chunk names: its style +/// table is read with the 8.01 layout. +#[test] +fn a_cdr8_file_whose_version_chunk_names_800_reads_as_801() { + let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x100, outline: 0x200 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }]; + for named in [800u16, 900, 1300] { + let table = synth::stlt(V(801), &[(0x100, 1)], &[(0x200, 2)], &styles, true); + let mut file = graphic_style_drawing(801, table); + file[8..12].copy_from_slice(b"cdr8"); + let at = file.windows(4).position(|w| w == b"vrsn").unwrap() + 8; + assert_eq!(&file[at..at + 2], &801u16.to_le_bytes()); + file[at..at + 2].copy_from_slice(&named.to_le_bytes()); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{named}: {e}")); + assert_eq!(d.version, 801, "{named}"); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s[0].fill, Some(Color::Rgb([1.0, 0.0, 0.0])), "{named}"); + assert!(d.warnings.is_empty(), "{named}: {:?}", d.warnings); + } +} + +/// Before version 6 an object names its style in 2 bytes, which is not damage; an argument too +/// short for them is. +#[test] +fn a_style_id_before_version_6_is_two_bytes() { + for version in [400, 500] { + let v = V(version); + let read_with = |style: Vec| { + let object = synth::object(v, 1, &[(200, style), (30, v.rect(10.0, 10.0, 0.0))], None); + let file = synth::file_of(version, vec![synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![object])])]); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + (shapes(&d.pages[0].layers[0].objects).len(), d.warnings) + }; + assert_eq!(read_with(vec![0x10, 0]), (1, vec![]), "{version}"); + assert_eq!(read_with(vec![0x10]), (1, vec![Warning::Damaged]), "{version}"); + } +} + +/// A hidden or locked group of `LIST clpt` hides or locks the objects a container clips from it. +#[test] +fn a_clipped_groups_flags_reach_its_objects() { + for version in [700, 1300, 1600] { + let v = V(version); + let group = list( + b"grp ", + vec![chunk(b"flgs", vec![0x10, 1, 0x80, 0x10]), chunk(b"spnd", 0x77u32.to_le_bytes().to_vec()), clip_rect(v, 10.0, &[], [0.0, 0.0])], + ); + let doc = list(b"doc ", vec![synth::mcfg(v, 612.0, 792.0), list(b"clpt", vec![group])]); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![clip_rect(v, 40.0, &[synth::container(0x77)], [0.0, 0.0])])]); + let d = read(&synth::file_of(version, vec![doc, page]), Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + let [Object::Clip { container, objects }] = d.pages[0].layers[0].objects.as_slice() else { + panic!("{version}: {:?}", d.pages[0].layers[0].objects) + }; + assert_eq!(container.flags, Flags::default(), "{version}"); + assert!(matches!(objects.as_slice(), [Object::Shape(s)] if s.flags == Flags { hidden: true, locked: true }), "{version}: {objects:?}"); + } +} + +/// Before version 6 a clipped group's `spnd` id is 2 bytes. +#[test] +fn a_clipped_group_id_before_version_6_is_two_bytes() { + for version in [400, 500] { + let v = V(version); + let rect = |w: f64, extra: Vec<(u32, Vec)>| { + let mut args = vec![(30, v.rect(w, w, 0.0))]; + args.extend(extra); + synth::object(v, 1, &args, None) + }; + let clpt = list(b"clpt", vec![list(b"grp ", vec![chunk(b"spnd", vec![0x77, 0]), rect(10.0, vec![])])]); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect(40.0, vec![synth::container(0x77)])])]); + let d = read(&synth::file_of(version, vec![list(b"doc ", vec![synth::mcfg(v, 612.0, 792.0), clpt]), page]), Limits::default()) + .unwrap_or_else(|e| panic!("{version}: {e}")); + let objects = &d.pages[0].layers[0].objects; + assert!(matches!(objects.as_slice(), [Object::Clip { objects, .. }] if objects.len() == 1), "{version}: {objects:?}"); + assert!(d.warnings.is_empty(), "{version}: {:?}", d.warnings); + } +} + +/// A `trfd` entry ends at the next offset: one too short for its matrix makes the transform +/// damage and leaves the shape in place, even when the bytes after it would read as a matrix. A +/// table that stops before the last entry's end offset leaves that entry the rest of the record. +#[test] +fn a_transform_entry_ends_at_the_next_offset() { + for version in [400, 1100, 1300, 1600] { + let v = V(version); + let w = if version < 600 { 2 } else { 4 }; + let moved = [1.0, 0.0, 0.0, 1.0, 72.0, 0.0]; + let object = |trfd: Vec| { + let own = vec![chunk(b"loda", v.loda(1, &[(30, v.rect(10.0, 10.0, 0.0))])), list(b"trfl", vec![chunk(b"trfd", trfd)])]; + list(b"obj ", vec![chunk(b"flgs", vec![0, 0, 0, 8]), list(b"lgob", own)]) + }; + let read_with = |trfd: Vec| { + let file = synth::file_of(version, vec![synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![object(trfd)])])]); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + (shapes(&d.pages[0].layers[0].objects)[0].matrix.0[4], d.warnings) + }; + let whole = v.trfd(&[moved]); + assert!((read_with(whole.clone()).0 - 72.0).abs() < 0.01, "{version}"); + // The end offset, right after the first, made 4 bytes past the entry's start. + let mut short = whole.clone(); + let start = if w == 2 { + usize::from(u16::from_le_bytes([short[3 * w], short[3 * w + 1]])) + } else { + u32::from_le_bytes(short[12..16].try_into().unwrap()) as usize + }; + short[4 * w..5 * w].copy_from_slice(&v.word(start + 4)); + assert_eq!(read_with(short), (0.0, vec![Warning::Damaged]), "{version}"); + // The entry first, then a table of its start alone at the record's end. + let entry = whole[5 * w..].to_vec(); + let at = 3 * w + entry.len(); + let mut end = [v.word(at + w), v.word(1), v.word(at)].concat(); + end.extend(entry); + end.extend(v.word(3 * w)); + let (x, warnings) = read_with(end); + assert!((x - 72.0).abs() < 0.01 && warnings.is_empty(), "{version}: {x} {warnings:?}"); + } +} + +/// From version 13 an outline's record of type 2 that names a library color gives the outline +/// that color; one without a name leaves the fixed color field. +#[test] +fn an_outline_takes_a_named_library_color_from_its_property_list() { + for version in [1300, 1500, 1600] { + let v = V(version); + let read_with = |props: Vec| { + let mut outl = v.outline(4, synth::Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }, &synth::color(2, [0, 0, 0, 100]), &[]); + let mut record = 2u32.to_le_bytes().to_vec(); + record.extend((props.len() as u32).to_le_bytes()); + record.extend(props); + outl.splice(4..4, record); + let doc = list(b"doc ", vec![synth::mcfg(v, 612.0, 792.0), list(b"otlt", vec![chunk(b"outl", outl)])]); + let object = synth::object(v, 1, &[(10, 4u32.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))], None); + let file = synth::file_of(version, vec![doc, synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![object])])]); + let d = read(&file, Limits::default()).unwrap_or_else(|e| panic!("{version}: {e}")); + (shapes(&d.pages[0].layers[0].objects)[0].outline.as_ref().map(|o| o.color.clone()), d.warnings) + }; + let named = synth::properties(&synth::color(5, [0, 0, 255, 0]), Some("Sky Blue")); + assert_eq!(read_with(named), (Some(Color::Spot { name: "Sky Blue".into(), tint: 1.0, look: Some([1.0, 0.0, 0.0]) }), vec![]), "{version}"); + let plain = synth::properties(&synth::color(5, [0, 0, 255, 0]), None); + assert_eq!(read_with(plain), (Some(Color::Cmyk([0.0, 0.0, 0.0, 1.0])), vec![]), "{version}"); + } +} + +#[test] +fn linked_groups_are_left_out_with_a_warning() { + let v = V(1100); + let rect = synth::object(v, 1, &[(30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![list(b"lnkg", vec![rect])])])]); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.pages[0].layers[0].objects.is_empty()); + assert!(d.warnings.contains(&Warning::UnsupportedObjects)); +} + +#[test] +fn a_file_cut_short_keeps_what_it_holds() { + let full = synth::sample(900, false); + let cut = &full[..full.len() - 40]; + let d = read(cut, Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged)); + // The last page is cut inside its layer: the lists that hold the cut keep their whole + // children, so the rectangle, ellipse and curve before the cut are read. + assert_eq!(d.pages.len(), 1); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(s.len() >= 3, "{}", s.len()); + assert!(matches!(s[0].geometry, Geometry::Rect { .. }) && matches!(s[1].geometry, Geometry::Ellipse { .. })); +} + +#[test] +fn a_riff_length_shorter_than_the_form_type_is_damage() { + for declared in 0u32..4 { + let mut file = synth::sample(900, false); + file[4..8].copy_from_slice(&declared.to_le_bytes()); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{declared}"); + check_shapes(&d, 900); + } +} + +#[test] +fn a_zip_bomb_stops_at_the_inflate_limit() { + let v = V(1100); + let big = chunk(b"junk", vec![0; 4 << 20]); + let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), synth::cmpr(&[big, synth::mcfg(v, 10.0, 10.0)])]); + assert!(file.len() < 64 << 10); + let limits = Limits { inflated: 1 << 20, ..Limits::default() }; + assert_eq!(read(&file, limits), Err(Error::Limit("inflated size"))); +} + +/// What a compressed stream inflates before it fails counts toward the inflate limit, so that +/// streams failing at their checksum can't each inflate up to the limit. +#[test] +fn bytes_inflated_by_a_failing_stream_count_toward_the_limit() { + let failing = || { + let mut cmpr = synth::cmpr(&[chunk(b"junk", vec![0; 600 << 10])]); + if let synth::Node::Chunk(_, body) = &mut cmpr { + // The last byte of the first block's zlib stream is part of its checksum. + let first = u32::from_le_bytes(body[4..8].try_into().unwrap()) as usize; + body[4 + 16 + first - 1] ^= 0xff; + } + cmpr + }; + let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), failing(), failing()]); + let one = + read(&synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), failing()]), Limits { inflated: 1 << 20, ..Limits::default() }); + assert!(one.is_ok_and(|d| d.warnings == vec![Warning::Damaged])); + assert_eq!(read(&file, Limits { inflated: 1 << 20, ..Limits::default() }), Err(Error::Limit("inflated size"))); +} + +#[test] +fn a_million_empty_chunks_stop_at_the_chunk_limit() { + let kids: Vec<_> = (0..5000).map(|_| chunk(b"junk", vec![])).collect(); + let file = synth::riff(1100, &[list(b"doc ", kids)]); + let limits = Limits { chunks: 1000, ..Limits::default() }; + assert_eq!(read(&file, limits), Err(Error::Limit("chunk count"))); + assert!(read(&file, Limits::default()).is_ok()); +} + +#[test] +fn deep_nesting_is_left_out_with_a_warning() { + let v = V(1100); + let mut inner = synth::object(v, 1, &[(30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + for _ in 0..300 { + inner = list(b"grp ", vec![inner]); + } + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![inner])])]); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::TooDeep)); +} + +#[test] +fn a_size_pool_index_out_of_range_is_damage() { + // A compressed stream whose one chunk names pool entry 7 of a pool of one. + let mut cmpr = synth::cmpr(&[chunk(b"mcfg", vec![0; 8])]); + if let synth::Node::Chunk(_, body) = &mut cmpr { + // Rebuild the stream with a bad index: the pool keeps its one size. + let mut stream = b"mcfg".to_vec(); + stream.extend(7u32.to_le_bytes()); + stream.extend([0; 8]); + let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + std::io::Write::write_all(&mut e, &stream).unwrap(); + let z = e.finish().unwrap(); + let pool_block = body[4 + 16 + u32::from_le_bytes(body[4..8].try_into().unwrap()) as usize..].to_vec(); + let mut b = b"cmpr".to_vec(); + b.extend(((z.len() + 8) as u32).to_le_bytes()); + b.extend((stream.len() as u32).to_le_bytes()); + b.extend(body[12..20].to_vec()); + b.extend(b"CPng\x01\x00\x04\x00"); + b.extend(z); + b.extend(pool_block); + *body = b; + } + let d = read(&synth::riff(1100, &[cmpr]), Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings); +} + +#[test] +fn backward_and_huge_loda_offsets_do_not_panic() { + let v = V(1100); + let mut loda = v.loda(3, &[(30, v.points(&[(0.0, 0.0, 0), (1.0, 1.0, 0x40)]))]); + // The offsets table now points before the header and far past the end. + let at = u32::from_le_bytes(loda[8..12].try_into().unwrap()) as usize; + loda[at..at + 4].copy_from_slice(&40u32.to_le_bytes()); + loda[at + 4..at + 8].copy_from_slice(&2u32.to_le_bytes()); + let obj = list(b"obj ", vec![chunk(b"loda", loda)]); + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![obj])])]); + let d = read(&file, Limits::default()).unwrap(); + assert!(d.warnings.contains(&Warning::Damaged)); +} + +#[test] +fn outlines_flagged_none_and_dashes_read() { + let v = V(1300); + let black = synth::color(2, [0, 0, 0, 100]); + let dashed = v.outline(9, synth::Pen { line_type: 4, width: 1.0, cap: 2, join: 2 }, &black, &[3, 1]); + let style = vec![(10, 9u32.to_le_bytes().to_vec()), (30, v.points(&[(0.0, 0.0, 0), (10.0, 0.0, 0x40)]))]; + let file = synth::riff( + 1300, + &[ + chunk(b"vrsn", 1300u16.to_le_bytes().to_vec()), + list(b"otlt", vec![chunk(b"outl", dashed)]), + synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 3, &style, None)])]), + ], + ); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let o = s[0].outline.as_ref().unwrap(); + assert_eq!(o.dashes, vec![3.0, 1.0]); + assert_eq!((o.cap, o.join), (Cap::Square, vectorcraft_cdr::model::Join::Bevel)); +} + +/// A curve or polygon left out at the coordinate limit gives the limit warning, not the damage +/// warning. +#[test] +fn shapes_past_the_coordinate_limit_are_not_damage() { + let v = V(1100); + let curve = synth::object(v, 3, &[(30, v.points(&[(0.0, 0.0, 0), (10.0, 0.0, 0x40), (10.0, 10.0, 0x40)]))], None); + let side = synth::POLYGON_SIDE; + let mut sides = vec![0; 4]; + sides.extend(5u32.to_le_bytes()); + sides.extend([0; 8]); + sides.extend(0.05f64.to_le_bytes()); + sides.extend(0.05f64.to_le_bytes()); + sides.extend([v.coord(0.0), v.coord(0.0)].concat()); + let base = v.points(&[(0.0, side, 0x0C), (side * 0.587, side * 0.809, 0x44)]); + let polygon = synth::object(v, 0x14, &[(30, base.clone()), (11000, sides)], None); + for (objects, limit) in [(vec![curve], 2), (vec![polygon], 4)] { + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", objects)])]); + let d = read(&file, Limits { coordinates: limit, ..Limits::default() }).unwrap(); + assert!(d.pages[0].layers[0].objects.is_empty()); + assert_eq!(d.warnings, vec![Warning::TooDeep]); + } + // A polygon without its sides is damage, past the limit too. + let sideless = synth::object(v, 0x14, &[(30, base)], None); + let file = synth::riff(1100, &[synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![sideless])])]); + let d = read(&file, Limits { coordinates: 1, ..Limits::default() }).unwrap(); + assert_eq!(d.warnings, vec![Warning::Damaged]); +} + +/// Dashes stored in an outline whose line type doesn't mark it dashed (bit 2) are not drawn: the +/// outline is solid. +#[test] +fn dashes_are_drawn_only_when_the_line_type_marks_them() { + let black = synth::color(2, [0, 0, 0, 100]); + for version in [700, 1200, 1500] { + for (line_type, dashed) in [(2, false), (0x22, false), (0x42, false), (4, true), (0x24, true), (0x44, true)] { + let v = V(version); + let outline = v.outline(9, synth::Pen { line_type, width: 1.0, cap: 0, join: 0 }, &black, &[2, 1]); + let style = vec![(10, 9u32.to_le_bytes().to_vec()), (30, v.points(&[(0.0, 0.0, 0), (10.0, 0.0, 0x40)]))]; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 3, &style, None)])]); + let d = read(&synth::file_of(version, vec![list(b"otlt", vec![chunk(b"outl", outline)]), page]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let o = s[0].outline.as_ref().unwrap(); + assert_eq!(o.dashes.is_empty(), !dashed, "{version} {line_type:#x}: {:?}", o.dashes); + } + } +} + +/// Bit 4 of the line type puts the outline behind the fill. +#[test] +fn outlines_flagged_behind_the_fill_say_so() { + let black = synth::color(2, [0, 0, 0, 100]); + for version in [700, 1300, 1600] { + for (line_type, behind) in [(2, false), (0x22, false), (0x12, true), (0x14, true)] { + let v = V(version); + let outline = v.outline(9, synth::Pen { line_type, width: 4.0, cap: 0, join: 0 }, &black, &[]); + let style = vec![(10, 9u32.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))]; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &style, None)])]); + let d = read(&synth::file_of(version, vec![list(b"otlt", vec![chunk(b"outl", outline)]), page]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s[0].outline.as_ref().map(|o| o.behind_fill), Some(behind), "{version} {line_type:#x}"); + } + } +} + +/// Bit 5 of the line type scales the outline with the shape. +#[test] +fn outlines_flagged_to_scale_with_the_shape_say_so() { + let black = synth::color(2, [0, 0, 0, 100]); + for version in [700, 1300, 1600] { + for (line_type, scale_with) in [(2, false), (0x22, true), (0x12, false), (0x26, true)] { + let v = V(version); + let outline = v.outline(9, synth::Pen { line_type, width: 4.0, cap: 0, join: 0 }, &black, &[]); + let style = vec![(10, 9u32.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))]; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &style, None)])]); + let d = read(&synth::file_of(version, vec![list(b"otlt", vec![chunk(b"outl", outline)]), page]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s[0].outline.as_ref().map(|o| o.scale_with), Some(scale_with), "{version} {line_type:#x}"); + } + } +} + +#[test] +fn library_colors_from_version_13_keep_their_names_and_tints() { + // A model 21 color (blue, green, red, tint) shown at 50 %, and its library name. + let shown = synth::color(21, [255, 191, 128, 50]); + let mut props = vec![1]; + props.extend(12u32.to_le_bytes()); + props.extend(shown); + props.push(8); + let name: Vec = "Sky Blue".encode_utf16().flat_map(|u| u.to_le_bytes()).collect(); + props.extend((16 + 4 + name.len() as u32).to_le_bytes()); + props.extend([0; 16]); + props.extend(8u32.to_le_bytes()); + props.extend(name); + props.extend([0, 0, 0, 0, 0]); + let mut solid = 1300u32.to_le_bytes().to_vec(); + solid.extend((props.len() as u32).to_le_bytes()); + solid.extend(props); + let mut body = 1u16.to_le_bytes().to_vec(); + body.extend(solid); + let mut fill = 4u32.to_le_bytes().to_vec(); + // A record of a later layout first, which the reader steps over. + fill.extend(2400u32.to_le_bytes()); + fill.extend(16u32.to_le_bytes()); + fill.extend([0; 16]); + fill.extend(1300u32.to_le_bytes()); + fill.extend((body.len() as u32).to_le_bytes()); + fill.extend(body); + // The same records in a plain file of version 13 and the packages of later versions. + for version in [1300, 1400, 1700, 2700] { + let v = V(version); + let style = vec![(20, 4u32.to_le_bytes().to_vec()), (30, v.rect(1.0, 1.0, 0.0))]; + let body = [ + chunk(b"vrsn", version.to_le_bytes().to_vec()), + list(b"filt", vec![chunk(b"fild", fill.clone())]), + synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &style, None)])]), + ]; + let file = match version { + ..1400 => synth::riff(version, &body), + 1400..1600 => synth::package14(synth::riff(version, &body), true), + _ => synth::package16(version, &body, true, &[]), + }; + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Some(Color::Spot { name, tint, look: Some(look) }) = &s[0].fill else { panic!("{version}: {:?}", s[0].fill) }; + assert_eq!((name.as_str(), *tint), ("Sky Blue", 0.5)); + // 128/255 shown at half strength comes from about 1/255 at full strength. + assert!(look[0] < 0.01 && (look[2] - 1.0).abs() < 1e-6, "{version}: {look:?}"); + } +} + +/// One rectangle of version `v` that uses fill `fill` and outline `outline` (0: none). +fn styled_rect(v: V, fill: u32, outline: u32) -> synth::Node { + let mut args = vec![(30, [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())]; + if fill != 0 { + args.push((20, fill.to_le_bytes().to_vec())); + } + if outline != 0 { + args.push((10, outline.to_le_bytes().to_vec())); + } + synth::object(v, 1, &args, None) +} + +/// A drawing of version `v` with `styles` in its `doc` list and `objects` on one page. +fn styled_drawing(v: V, styles: Vec, objects: Vec) -> Vec { + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", objects)]); + synth::riff(v.0, &[chunk(b"vrsn", v.0.to_le_bytes().to_vec()), list(b"doc ", styles), page]) +} + +/// An outline's dashes count toward the read's dashes for every shape that uses it: one outline +/// of 65,535 dashes on 260 shapes would copy 17 million dashes, past the default limit. +#[test] +fn a_shared_dashed_outline_counts_its_dashes_for_every_shape() { + let v = V(1300); + let pen = synth::Pen { line_type: 4, width: 1.0, cap: 0, join: 0 }; + let outl = |dashes: &[u16]| list(b"otlt", vec![chunk(b"outl", v.outline(9, pen, &synth::color(2, [0, 0, 0, 100]), dashes))]); + let file = styled_drawing(v, vec![outl(&[2, 1].repeat(10))], (0..20).map(|_| styled_rect(v, 0, 9)).collect()); + let d = read(&file, Limits { dashes: 100, ..Limits::default() }).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s.len(), 20); + let dashed = s.iter().filter(|s| s.outline.as_ref().is_some_and(|o| o.dashes.len() == 20)).count(); + assert_eq!(dashed, 5, "100 dashes hold five outlines of 20"); + assert!(s.iter().all(|s| s.outline.as_ref().is_some_and(|o| o.dashes.is_empty() || o.dashes.len() == 20))); + assert!(d.warnings.contains(&Warning::TooDeep), "{:?}", d.warnings); + // An outline with more dashes than the limit is solid, not cut short. + let file = styled_drawing(v, vec![outl(&[2, 1])], vec![styled_rect(v, 0, 9)]); + let d = read(&file, Limits { dashes: 1, ..Limits::default() }).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert!(s[0].outline.as_ref().is_some_and(|o| o.dashes.is_empty()), "{:?}", s[0].outline); + assert_eq!(d.warnings, vec![Warning::TooDeep]); + // At the default limit. + let file = styled_drawing(v, vec![outl(&[1; 65_535])], (0..260).map(|_| styled_rect(v, 0, 9)).collect()); + assert!(file.len() < 256 << 10); + let d = read(&file, Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let total: usize = s.iter().filter_map(|s| s.outline.as_ref()).map(|o| o.dashes.len()).sum(); + assert!(total <= Limits::default().dashes, "{total}"); + assert!(d.warnings.contains(&Warning::TooDeep), "{:?}", d.warnings); +} + +/// A library color's name is copied for every shape that uses it: a long one keeps its first 256 +/// units and a hash of the whole name. +#[test] +fn a_library_color_keeps_the_first_256_units_of_its_name() { + let v = V(1300); + let mut props = vec![1]; + props.extend(12u32.to_le_bytes()); + props.extend(synth::color(21, [255, 191, 128, 100])); + props.push(8); + let name: Vec = "N".repeat(10_000).encode_utf16().flat_map(|u| u.to_le_bytes()).collect(); + props.extend((16 + 4 + name.len() as u32).to_le_bytes()); + props.extend([0; 16]); + props.extend(10_000u32.to_le_bytes()); + props.extend(name); + props.extend([0, 0, 0, 0, 0]); + let mut body = 1u16.to_le_bytes().to_vec(); + body.extend(1300u32.to_le_bytes()); + body.extend((props.len() as u32).to_le_bytes()); + body.extend(props); + let mut fill = 4u32.to_le_bytes().to_vec(); + fill.extend(1300u32.to_le_bytes()); + fill.extend((body.len() as u32).to_le_bytes()); + fill.extend(body); + let d = read(&styled_drawing(v, vec![list(b"filt", vec![chunk(b"fild", fill)])], vec![styled_rect(v, 4, 0)]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + let Some(Color::Spot { name, .. }) = &s[0].fill else { panic!("{:?}", s[0].fill) }; + assert_eq!(name.chars().count(), 256 + 17, "{name}"); + assert!(name.starts_with(&"N".repeat(256)), "{name}"); + assert!(d.warnings.contains(&Warning::TooDeep), "{:?}", d.warnings); +} + +/// A transform or a uniform fill's color that is there but can't be read is damage: the shape +/// stays, without its transform or its fill, and the warnings say so. +#[test] +fn unreadable_transforms_and_fill_colors_are_damage() { + let v = V(1100); + let rect = [v.coord(1.0), v.coord(1.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat(); + let obj = list(b"obj ", vec![chunk(b"loda", v.loda(1, &[(30, rect)])), list(b"trfl", vec![chunk(b"trfd", vec![1, 2])])]); + let d = read(&styled_drawing(v, vec![], vec![obj]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!((s.len(), s[0].matrix), (1, vectorcraft_cdr::model::Matrix::IDENTITY)); + assert!(d.warnings.contains(&Warning::Damaged), "trfd: {:?}", d.warnings); + // A uniform fill cut off in its color record, before version 13 and from it. + for v in [V(1100), V(1300)] { + let mut fill = v.fill(4, &synth::color(2, [0, 100, 0, 0])); + fill.truncate(fill.len() - 10); + let d = read(&styled_drawing(v, vec![list(b"filt", vec![chunk(b"fild", fill)])], vec![styled_rect(v, 4, 0)]), Limits::default()).unwrap(); + let s = shapes(&d.pages[0].layers[0].objects); + assert_eq!(s[0].fill, None, "{}", v.0); + assert!(d.warnings.contains(&Warning::Damaged), "fill {}: {:?}", v.0, d.warnings); + } +} + +/// The inflate limit may be as large as `usize` holds. +#[test] +fn the_largest_inflate_limit_reads_compressed_lists() { + let d = read(&synth::sample(1100, true), Limits { inflated: usize::MAX, ..Limits::default() }).unwrap(); + check_shapes(&d, 1100); +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })] + + #[test] + fn never_panics_on_garbage(bytes in prop::collection::vec(any::(), 0..2048)) { + let mut b = b"RIFF".to_vec(); + b.extend(bytes); + let _ = read(&b, Limits::default()); + } + + #[test] + fn never_panics_on_mutated_samples(version in prop::sample::select(vec![300u16, 400, 500, 700, 900, 1100, 1300]), compress: bool, edits in prop::collection::vec((any::(), any::()), 1..24)) { + let mut b = synth::sample(version, compress && version >= 700); + let n = b.len(); + for (at, v) in edits { + b[at % n] = v; + } + let _ = read(&b, Limits::default()); + } + + #[test] + fn never_panics_on_garbage_after_a_wl_header(marker in prop::sample::select(vec![b'e', b'l', b'm']), bytes in prop::collection::vec(any::(), 0..2048)) { + // Offsets that fit the file, so the garbage is walked as records. + let mut b = vec![b'W', b'L', marker, 0]; + b.extend(28u32.to_le_bytes()); + b.extend(28u32.to_le_bytes()); + b.extend((28 + bytes.len() as u32).to_le_bytes()); + b.extend([0; 12]); + b.extend(bytes); + prop_assert!(vectorcraft_cdr::is_cdr(&b)); + let _ = read(&b, Limits::default()); + } + + #[test] + fn never_panics_on_mutated_wl_files(marker in prop::sample::select(vec![b'e', b'l', b'm']), cut in any::(), edits in prop::collection::vec((any::(), any::()), 1..24)) { + let mut b = synth::wl_sample(marker); + let n = b.len(); + for (at, v) in edits { + b[at % n] = v; + } + let _ = read(&b, Limits::default()); + let _ = read(&b[..cut % (n + 1)], Limits::default()); + } + + #[test] + fn never_panics_on_mutated_packages(version in prop::sample::select(vec![1400u16, 1500, 1700, 2700]), edits in prop::collection::vec((any::(), any::(), any::()), 1..24)) { + // The members are edited before they are zipped, so that the edits reach the chunks and + // redirect records rather than stop at the CRC-32. + let mut body = vec![chunk(b"vrsn", version.to_le_bytes().to_vec())]; + body.extend(synth::sample_content(version)); + let mut members = if version < 1600 { + vec![synth::Member { name: "content/riffData.cdr".into(), data: synth::sample(version, false), deflate: false }] + } else { + synth::package16_members(version, &body, false, &[]) + }; + for (m, at, v) in edits { + let k = m % members.len(); + let data = &mut members[k].data; + if !data.is_empty() { + let n = data.len(); + data[at % n] = v; + } + } + let _ = read(&synth::zip(&members, b""), Limits::default()); + } +} diff --git a/crates/color/src/cms.rs b/crates/color/src/cms.rs index 96640b5508..a3c35db8ce 100644 --- a/crates/color/src/cms.rs +++ b/crates/color/src/cms.rs @@ -185,6 +185,15 @@ pub struct ColorSettings { /// The color management policy for CMYK profiles. Settings saved without one take the default. #[serde(default)] pub cmyk_policy: Policy, + /// Profile Mismatches: Ask When Opening. Off by default, as in settings saved without it. + #[serde(default)] + pub ask_mismatch_open: bool, + /// Profile Mismatches: Ask When Pasting. + #[serde(default)] + pub ask_mismatch_paste: bool, + /// Missing Profiles: Ask When Opening. + #[serde(default)] + pub ask_missing_open: bool, } impl Default for ColorSettings { @@ -196,6 +205,9 @@ impl Default for ColorSettings { bpc: true, rgb_policy: Policy::default(), cmyk_policy: Policy::default(), + ask_mismatch_open: false, + ask_mismatch_paste: false, + ask_missing_open: false, } } } @@ -589,10 +601,11 @@ impl Cms { /// An RGB or CMYK colour of this context's space as the colour of the same model in `dest`'s /// space that looks the same, converted with `intent` (Edit → Color Settings › Convert to - /// Working Space). RGB converts directly from profile to profile, and CMYK between two loaded - /// profiles through ProPhoto RGB ([`IccProfile::to_same_model_of`]), both with this context's - /// black-point compensation; CMYK goes through Lab when either space is built in. Grey and - /// Lab colours stay as they are. + /// Working Space). RGB converts directly from profile to profile, with this context's + /// black-point compensation. CMYK converts between two loaded profiles through ProPhoto RGB + /// ([`IccProfile::to_same_model_of`]), and through Lab when either space is built in: the Lab it + /// displays as ([`Self::cmyk_display_lab`]), or for Absolute Colorimetric its absolute Lab. Grey + /// and Lab colours stay as they are. pub fn convert_into(&self, dest: &Cms, c: &Color, intent: Intent) -> Color { match *c { Color::Rgb { r, g, b } => { @@ -612,9 +625,16 @@ impl Cms { (CmykSpace::Icc(s), CmykSpace::Icc(d)) => s.to_same_model_of(d, &inks, intent, self.settings.bpc), _ => None, }; + // Absolute colorimetry starts from the inks' absolute Lab, paper color included and + // without black-point compensation; the other intents from the Lab they display as. + let source_lab = || match (&self.cmyk, intent) { + (CmykSpace::Generic(g), Intent::AbsoluteColorimetric) => g.to_lab_abs(inks), + (_, Intent::AbsoluteColorimetric) => lab::srgb_to_lab(self.cmyk_to_srgb(inks, true)), + _ => self.cmyk_display_lab(inks), + }; let [c, m, y, k] = match direct.as_deref() { Some(&[c, m, y, k]) => [c, m, y, k], - _ => dest.lab_to_cmyk(self.cmyk_to_lab(inks), intent), + _ => dest.lab_to_cmyk(source_lab(), intent), }; Color::Cmyk { c, m, y, k } } diff --git a/crates/color/src/cms/tests.rs b/crates/color/src/cms/tests.rs index 95e465b623..836ff9fdb6 100644 --- a/crates/color/src/cms/tests.rs +++ b/crates/color/src/cms/tests.rs @@ -459,6 +459,23 @@ fn policies_parse_and_default_in_saved_settings() { assert_eq!((saved["rgbPolicy"].as_str(), saved["cmykPolicy"].as_str()), (Some("preserveEmbedded"), Some("preserveNumbers"))); } +/// The three Ask boxes are off by default and in settings saved before they existed, and save +/// under their own keys. +#[test] +fn ask_boxes_default_off_and_save() { + let old: ColorSettings = + serde_json::from_str(r#"{"rgb": "sRGB IEC61966-2.1", "cmyk": "Device CMYK (uncalibrated)", "intent": "perceptual", "bpc": false}"#).unwrap(); + assert!(!old.ask_mismatch_open && !old.ask_mismatch_paste && !old.ask_missing_open); + let st = ColorSettings::default(); + assert!(!st.ask_mismatch_open && !st.ask_mismatch_paste && !st.ask_missing_open); + let saved = serde_json::to_value(ColorSettings { ask_mismatch_paste: true, ..Default::default() }).unwrap(); + assert_eq!(saved["askMismatchOpen"], false); + assert_eq!(saved["askMismatchPaste"], true); + assert_eq!(saved["askMissingOpen"], false); + let back: ColorSettings = serde_json::from_value(saved).unwrap(); + assert!(back.ask_mismatch_paste); +} + /// Convert to Working Space keeps a color's appearance: an RGB color of a wide space converts into /// sRGB, and a CMYK color of one CMYK space into another, with numbers that look the same. Grey and /// Lab colors stay as they are. @@ -478,3 +495,48 @@ fn convert_into_keeps_the_appearance() { assert_eq!(wide.convert_into(&working, &c, Intent::RelativeColorimetric), c); } } + +/// With black-point compensation on, Generic CMYK displays its press black as black, so dark inks +/// converted out of it keep that appearance: into Device CMYK, and into another document whose +/// CMYK space is also Generic CMYK. +#[test] +fn convert_into_keeps_compensated_dark_inks() { + let generic = cms(); + let device = Cms::new(&ColorSettings { cmyk: DEVICE_CMYK.into(), ..Default::default() }).unwrap(); + let other_generic = Cms::new(&ColorSettings { rgb: WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap(); + for ink in [ + Color::Cmyk { c: 0.6, m: 0.5, y: 0.5, k: 0.9 }, + Color::Cmyk { c: 0.0, m: 0.0, y: 0.0, k: 1.0 }, + Color::Cmyk { c: 0.3, m: 0.2, y: 0.2, k: 0.75 }, + ] { + for dest in [&device, &other_generic] { + let moved = generic.convert_into(dest, &ink, Intent::RelativeColorimetric); + assert!(matches!(moved, Color::Cmyk { .. }), "{ink:?} → {moved:?}"); + let d = delta_e2000(generic.lab(&ink), dest.lab(&moved)); + assert!(d < 2.0, "{ink:?} → {moved:?}: ΔE {d}"); + } + } +} + +/// Absolute Colorimetric converts CMYK out of Generic CMYK from the inks' absolute Lab (paper color +/// included, no black-point compensation): into another document whose CMYK space is also Generic +/// CMYK, the paper, dark inks and mid tones keep their absolute appearance. +#[test] +fn absolute_cmyk_conversion_keeps_the_absolute_appearance() { + let generic = cms(); + let other_generic = Cms::new(&ColorSettings { rgb: WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap(); + let absolute = |c: &Cms, ink: &Color| match (&c.cmyk, ink) { + (CmykSpace::Generic(g), Color::Cmyk { c, m, y, k }) => g.to_lab_abs([*c, *m, *y, *k]), + _ => panic!("Generic CMYK inks expected, not {ink:?}"), + }; + for ink in [ + Color::Cmyk { c: 0.0, m: 0.0, y: 0.0, k: 0.0 }, + Color::Cmyk { c: 0.6, m: 0.5, y: 0.5, k: 0.9 }, + Color::Cmyk { c: 0.3, m: 0.2, y: 0.2, k: 0.75 }, + Color::Cmyk { c: 0.4, m: 0.1, y: 0.6, k: 0.1 }, + ] { + let moved = generic.convert_into(&other_generic, &ink, Intent::AbsoluteColorimetric); + let d = delta_e2000(absolute(&generic, &ink), absolute(&other_generic, &moved)); + assert!(d < 2.0, "{ink:?} → {moved:?}: ΔE {d}"); + } +} diff --git a/crates/color/src/harmony.rs b/crates/color/src/harmony.rs index 2cca6e264d..87e1c54548 100644 --- a/crates/color/src/harmony.rs +++ b/crates/color/src/harmony.rs @@ -176,18 +176,33 @@ impl Harmony { /// The rule's colours in the base colour's model, the base colour itself first. pub fn apply(self, base: Color) -> Vec { - let [h, s, v] = base.to_hsb(); - std::iter::once(base) - .chain(self.tones()[1..].iter().map(|tone| { + let rest = self.apply_hsb(base.to_hsb()).into_iter().skip(1); + std::iter::once(base).chain(rest.map(|[h, s, v]| keep_model(base, Color::from_hsb(h, s, v)))).collect() + } + + /// The rule's colours as HSB from base HSB `hsb`, the base first: hue in degrees from 0 to 360, + /// saturation and brightness from 0 to 1. A gray base keeps its hue, so the colours keep their + /// places around a hue wheel. + pub fn apply_hsb(self, [h, s, v]: [f32; 3]) -> Vec<[f32; 3]> { + self.tones() + .iter() + .map(|tone| { let b = match tone.bright { Bright::Times(f) => v * f, Bright::Contrast => contrast(v), }; - keep_model(base, Color::from_hsb(h + tone.turn, (s * tone.sat).clamp(0.0, 1.0), b.clamp(0.0, 1.0))) - })) + [(h + tone.turn).rem_euclid(360.0), (s * tone.sat).clamp(0.0, 1.0), b.clamp(0.0, 1.0)] + }) .collect() } + /// Whether every colour of the rule has a hue of its own (Triad, but not Triad 2 or + /// Monochromatic), so that each can sit on a hue ring apart from the others. + pub fn hues_differ(self) -> bool { + let turns: Vec = self.tones().iter().map(|t| t.turn.rem_euclid(360.0)).collect(); + turns.iter().enumerate().all(|(i, a)| turns[..i].iter().all(|b| a != b)) + } + /// A [`THEME_SIZE`]-colour theme from `base`: the rule's colours, each followed by the lighter or /// darker variations of it that fill the remaining places (the rule's first colours get them /// first). The base colour comes first, every colour in its model. @@ -409,6 +424,34 @@ mod tests { assert_eq!(Harmony::parse("square"), None); } + /// A rule's HSB colours match the colours `apply` gives, and a gray base keeps its hue, so its + /// colours turn around the hue ring from it. + #[test] + fn hsb_colours_match_and_keep_a_grays_hue() { + for h in Harmony::ALL { + let base = Color::rgb8(230, 120, 40); + let hsb = h.apply_hsb(base.to_hsb()); + let colors = h.apply(base); + assert_eq!(hsb.len(), colors.len(), "{}", h.label()); + for (a, c) in hsb.iter().zip(&colors).skip(1) { + assert_eq!(Color::from_hsb(a[0], a[1], a[2]).to_hex(), c.to_hex(), "{}", h.label()); + } + } + let gray = Harmony::Triad.apply_hsb([40.0, 0.0, 0.5]); + assert_eq!(gray.iter().map(|c| c[0]).collect::>(), [40.0, 160.0, 280.0]); + assert_eq!(Harmony::Analogous.apply_hsb([10.0, 1.0, 1.0])[2][0], 340.0, "hues wrap to 0..360"); + } + + /// Fifteen rules give every colour its own hue; the six that repeat a hue are left out. + #[test] + fn rules_whose_colours_all_have_their_own_hue() { + let differ: Vec = Harmony::ALL.into_iter().filter(|h| h.hues_differ()).collect(); + assert_eq!(differ.len(), 15); + for h in [Harmony::Complementary2, Harmony::Monochromatic, Harmony::Shades, Harmony::Triad2, Harmony::Triad3, Harmony::HighContrast2] { + assert!(!h.hues_differ(), "{}", h.label()); + } + } + #[test] fn high_contrast_flips_brightness() { let light = Harmony::HighContrast.apply(Color::rgb(0.9, 0.8, 0.2)); diff --git a/crates/doc/src/appearance.rs b/crates/doc/src/appearance.rs index 737e10eb58..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 diff --git a/crates/doc/src/appearance/layers.rs b/crates/doc/src/appearance/layers.rs index 5e07dc6cde..1728b7e323 100644 --- a/crates/doc/src/appearance/layers.rs +++ b/crates/doc/src/appearance/layers.rs @@ -113,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 @@ -187,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/document.rs b/crates/doc/src/document.rs index 4365f7788a..608902756b 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -35,6 +35,7 @@ impl Document { char_styles, para_styles, composite_fonts, + kinsoku_sets, text_threads, symbols, graph_designs, @@ -96,6 +97,7 @@ impl Document { && *char_styles == other.char_styles && *para_styles == other.para_styles && *composite_fonts == other.composite_fonts + && *kinsoku_sets == other.kinsoku_sets && *text_threads == other.text_threads && symbols.len() == other.symbols.len() && symbols.iter().zip(&other.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art)) @@ -221,6 +223,7 @@ impl Document { char_styles: Default::default(), para_styles: Default::default(), composite_fonts: Default::default(), + kinsoku_sets: Default::default(), text_threads: vec![], symbols: vec![], graph_designs: vec![], 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 93baa85ed8..c996699391 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -74,11 +74,24 @@ pub struct HitOptions { /// its edge. Off for the tools that act on what is drawn (sampling, type, gradients…); /// [`hit_test_visible`] never does it. pub clip_outlines: bool, + /// The Type tool: area type is hit anywhere inside its frame, where a click places the caret. + /// Off, the empty part of the frame (away from its edge and its lines of type) takes no + /// clicks, so they reach the art behind (#7274). + pub area_type_interior: bool, } impl Default for HitOptions { fn default() -> Self { - Self { tol: 3.0, outline: false, path_only: false, type_path_only: false, skip_guides: false, clip_outlines: false, scope: None } + Self { + tol: 3.0, + outline: false, + path_only: false, + type_path_only: false, + skip_guides: false, + clip_outlines: false, + area_type_interior: false, + scope: None, + } } } @@ -1507,7 +1520,11 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio 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) + n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p))?; + match &n.kind { + NodeKind::Text(t) if !opt.area_type_interior => in_area_type_art(n, t, p, opt.tol).unwrap_or(true).then_some(HitKind::Bounds), + _ => Some(HitKind::Bounds), + } } // A symbol instance is hit within its bounds, and outside them where its art paints // ([`instance_art_hit`]) or where the geometry effects of its active fill or stroke reshape @@ -1577,6 +1594,30 @@ fn on_type_path(n: &Node, t: &crate::TextObject, p: Point, tol: f64) -> bool { stroke_contains(&path.to_bezpath(), 0.0, tol, p) } +/// Is `p` on area type `t` (in `n`) where it is drawn: within `tol` of its frame's edge or inside +/// its laid-out lines ([`crate::TextObject::cached_bounds`], with the characters' strokes)? The +/// rest of the frame is empty and takes no clicks (#7274). `None` when that is not known: other +/// type, type in perspective, or area type not laid out yet, which are hit within their bounds. +fn in_area_type_art(n: &Node, t: &crate::TextObject, p: Point, tol: f64) -> Option { + use vectorcraft_geom::kurbo::Shape; + let crate::TextKind::Area { frame } = &t.kind else { return None }; + if n.projection().is_some() { + return None; + } + if stroke_contains(&frame.transformed(t.xf).to_bezpath(), 0.0, tol, p) { + return Some(true); + } + let lines = t.cached_bounds?; + // No lines (empty type): only the frame's edge. + if lines.width() <= 0.0 && lines.height() <= 0.0 { + return Some(false); + } + let mut lines = lines.to_path(0.1); + lines.apply_affine(t.xf); + let reach = tol + t.char_stroke_outset(); + Some(fill_contains(&lines, FillRule::NonZero, p) || stroke_contains(&lines, 0.0, reach, p)) +} + /// Hit anywhere in an evaluated subtree (groups recurse; leaves use [`hit_leaf`]). In symbol art /// placed by [`FindPart`], each object visited takes one object of the [`ArtWalk`] limit, and /// nothing more is tested once the limit is used up. @@ -2106,20 +2147,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)? @@ -2127,8 +2187,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(); @@ -2142,7 +2211,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)) @@ -2164,7 +2233,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 @@ -2173,17 +2242,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() { @@ -2192,7 +2254,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() { @@ -2209,12 +2271,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())) } @@ -2271,12 +2333,16 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh /// 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, whole_compounds: bool, outline: bool) -> bool { + 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), @@ -2287,25 +2353,26 @@ 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, 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, whole_compounds) || painted_touches(n, s, r)) + !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), @@ -2334,7 +2401,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) { @@ -2351,15 +2418,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); } @@ -2374,18 +2441,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); } } @@ -2420,14 +2487,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 9d0133ec60..e94b2b8ba8 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. @@ -1393,8 +1455,16 @@ fn masked_square(layer: bool) -> (Document, NodeId, NodeId, NodeId) { } } -const SELECTING: HitOptions = - HitOptions { tol: 3.0, outline: false, path_only: false, type_path_only: false, skip_guides: false, clip_outlines: true, scope: None }; +const SELECTING: HitOptions = HitOptions { + tol: 3.0, + outline: false, + path_only: false, + type_path_only: false, + skip_guides: false, + clip_outlines: true, + area_type_interior: false, + scope: None, +}; /// For the selection tools a clip group's clipping path is hit on its outline, within the /// tolerance, before the art it clips and just outside it too; inside, the art is hit. @@ -1688,6 +1758,41 @@ fn type_path_only_picks_type_on_its_path() { assert_eq!(hit(Point::new(60.0, 339.5), path_only), Some((on_path, HitKind::Outline)), "type on a path: its path"); } +/// Area type is hit on its frame's edge and where its lines are laid out, not in the empty rest of +/// its frame: a click there reaches the art behind, in Preview and in Outline mode (#7274). The +/// Type tool still finds the type anywhere inside its frame. +#[test] +fn area_type_passes_clicks_through_its_empty_frame() { + use crate::{CharStyle, TextKind, TextObject}; + let mut d = Document::new(400.0, 400.0); + let l = d.layers[0].id; + // A filled square behind the type, its edge at x = 150 inside the frame. + let square = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(150.0, 150.0, 350.0, 350.0)), Appearance::default_art()); + let square_id = square.id; + d.insert(Some(l), 9, square).unwrap(); + // Area type at (100, 100): a 200 × 200 frame with one 80 wide line at its top. + let mut area = TextObject::point(Point::new(100.0, 100.0), "Area", CharStyle { size: 20.0, ..CharStyle::default() }); + area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)) }; + area.cached_bounds = Some(Rect::new(0.0, 0.0, 80.0, 24.0)); + area.cached_baselines = vec![(Point::new(0.0, 18.0), Point::new(80.0, 18.0))]; + let area_id = d.alloc_id(); + d.insert(Some(l), 9, Node::new(area_id, NodeKind::Text(Box::new(area)))).unwrap(); + let outline = HitOptions { outline: true, ..Default::default() }; + for (opt, mode) in [(HitOptions::default(), "preview"), (outline, "outline")] { + let hit = |p: Point| hit_test(&d, p, opt).map(|h| h.leaf); + assert_eq!(hit(Point::new(140.0, 110.0)), Some(area_id), "{mode}: on the line of type"); + assert_eq!(hit(Point::new(200.0, 100.5)), Some(area_id), "{mode}: on the frame's top edge"); + assert_eq!(hit(Point::new(299.0, 250.0)), Some(area_id), "{mode}: on the frame's right edge"); + assert_eq!(hit(Point::new(220.0, 130.0)), None, "{mode}: the empty frame, nothing behind"); + assert_eq!(hit(Point::new(120.0, 250.0)), None, "{mode}: the empty frame, nothing behind"); + assert_eq!(hit(Point::new(150.0, 250.0)), Some(square_id), "{mode}: the square's edge behind the empty frame"); + } + assert_eq!(hit_test(&d, Point::new(250.0, 250.0), HitOptions::default()).map(|h| h.leaf), Some(square_id), "the square's fill"); + // The Type tool: anywhere inside the frame. + let typing = HitOptions { area_type_interior: true, ..Default::default() }; + assert_eq!(hit_test(&d, Point::new(250.0, 250.0), typing).map(|h| h.leaf), Some(area_id), "type tool: inside the frame"); +} + /// Type Object Selection by Path Only with the layout's baselines: every line's for point type, /// area type's besides its frame, a vertical column's centre line, and type in perspective /// where it is drawn. @@ -2674,7 +2779,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/lib.rs b/crates/doc/src/lib.rs index 123e31bc08..3f53bc693f 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -17,6 +17,7 @@ pub mod corners; pub mod decode; pub mod depth; pub mod dimension; +pub mod flare; pub mod graph; mod halftone_radii; pub mod hit; @@ -137,7 +138,7 @@ pub use text::{ RubyPosition, RubySpan, ScriptMetrics, SingleWordJustify, TabAlign, TabStop, TextFlow, TextKind, TextObject, TextRun, TextStyleDef, TextWrap, VerticalAlign, WrapShape, }; -pub use text::{CharClass, CompositeClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet}; +pub use text::{CharClass, CompositeClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet, KinsokuSet}; pub use trace::TraceView; pub use variables::{DataSet, DataValue, Variable, VariableKind, Variables}; pub use vectorcraft_color as color; @@ -170,7 +171,7 @@ use limits::MAX_NEXT_ID; pub use limits::{DocError, FORMAT_VERSION, MAX_COORD}; pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit}; pub use stored_art::{StoredPlace, StoredRoot}; -pub use units::{ColorMode, Unit, decimal_point, finite_in_every_unit, parse_number}; +pub use units::{ColorMode, Unit, arithmetic_signs, decimal_point, finite_in_every_unit, parse_number}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Document { @@ -217,6 +218,10 @@ pub struct Document { /// Type › Composite Fonts…: the composite fonts defined in the document, by name. #[serde(default, skip_serializing_if = "skip::is_empty_vec")] pub composite_fonts: Shared>, + /// Type › Kinsoku Shori Settings…: the custom Kinsoku Shori sets defined in the document, by + /// name. A paragraph using one holds a copy of it ([`ParaStyle::kinsoku_set`]). + #[serde(default, skip_serializing_if = "skip::is_empty_vec", deserialize_with = "text::read_kinsoku_sets")] + pub kinsoku_sets: Shared>, /// Threaded text: area-type frames one story flows through, in order. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub text_threads: Vec>, diff --git a/crates/doc/src/mem.rs b/crates/doc/src/mem.rs index 68aaedd68e..3519986512 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -113,6 +113,19 @@ impl Document { .map(|f| f.name.capacity() + crate::CharClass::ALL.into_iter().map(|k| part(f.parts.get(k))).sum::() + custom(f)) .sum::() }); + n += shared(&self.kinsoku_sets, &newer.kinsoku_sets, |k| { + vec_bytes(k) + + k.iter() + .map(|s: &crate::KinsokuSet| { + s.name.capacity() + + vec_bytes(&s.cannot_start) + + vec_bytes(&s.cannot_end) + + vec_bytes(&s.hanging) + + vec_bytes(&s.inseparable) + + s.inseparable.iter().map(String::capacity).sum::() + }) + .sum::() + }); n += shared(&self.saved_selections, &newer.saved_selections, |s| { vec_bytes(s) + s.iter().map(|s: &SavedSelection| s.name.capacity() + vec_bytes(&s.objects)).sum::() }); @@ -271,6 +284,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 +367,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 +439,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/node/extras.rs b/crates/doc/src/node/extras.rs index f75e473039..f953deda71 100644 --- a/crates/doc/src/node/extras.rs +++ b/crates/doc/src/node/extras.rs @@ -10,8 +10,9 @@ use super::{Node, PathData}; pub struct NodeExtras { /// Opacity mask (Transparency panel). Its art lives here, outside the layer tree. pub mask: Option>, - /// Image Trace object: `{preset, params, view?}` it was traced with (the Image Trace panel shows - /// them; `view` is its [`crate::TraceView`] id, absent for the tracing result). + /// Image Trace object: `{preset, params, view?, split?}` it was traced with (the Image Trace + /// panel shows them; `view` is its [`crate::TraceView`] id, absent for the tracing result, and + /// `split` the Split view's divider, [`crate::TraceView::split_of`]). pub trace: Option>, /// Object → Text Wrap: area type below this object (in the same layer) flows around it. pub wrap: Option, @@ -41,6 +42,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 +104,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras { slice: None, perspective: None, dimension: None, + flare: None, intertwine: None, intertwine_tiers: Vec::new(), live_paint_gaps: None, diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 42978c81b0..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, .. }) @@ -484,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/style_libs.rs b/crates/doc/src/style_libs.rs index 34faf1f9c4..4bb4ce85bf 100644 --- a/crates/doc/src/style_libs.rs +++ b/crates/doc/src/style_libs.rs @@ -157,6 +157,7 @@ pub const STYLE_LIBRARIES: &[BuiltinStyleLibrary] = &[ BuiltinStyleLibrary { id: "hand-drawn", name: "Hand-Drawn", make: hand_drawn }, BuiltinStyleLibrary { id: "textures", name: "Textures", make: textures }, BuiltinStyleLibrary { id: "painted-sketched", name: "Painted and Sketched", make: painted_sketched }, + BuiltinStyleLibrary { id: "paper-cutouts", name: "Paper Cutouts", make: paper_cutouts }, BuiltinStyleLibrary { id: "gradient-finishes", name: "Gradient Finishes", make: gradient_finishes }, BuiltinStyleLibrary { id: "shape-effects", name: "Shape Effects", make: shape_effects }, BuiltinStyleLibrary { id: "blends-transparency", name: "Blends and Transparency", make: blends_transparency }, @@ -384,6 +385,25 @@ fn painted_sketched() -> Vec { ] } +/// Paper Cutouts: original layered paper colors with visible cut edges and crisp cast shadows. +fn paper_cutouts() -> Vec { + let cutout = |name: &str, face: &str, edge: &str, rim: &str, shadow: &str, x: f64, y: f64| { + style( + name, + vec![F(fill(face)), S(stroke(edge, 7.0)), S(stroke(rim, 2.0))], + vec![fx("stylize.dropShadow", json!({"mode": "normal", "opacity": 100.0, "x": x, "y": y, "blur": 0.0, "color": shadow}))], + ) + }; + vec![ + cutout("Coral Layers", "#ff6b6b", "#f9c74f", "#fff4e6", "#6d597a", 5.0, 5.0), + cutout("Mint Layers", "#80cbc4", "#2a9d8f", "#e9f5db", "#355070", 4.0, 6.0), + cutout("Midnight Layers", "#3d5a80", "#ee6c4d", "#e0fbfc", "#1b263b", 6.0, 4.0), + cutout("Sunflower Sheet", "#ffbe0b", "#fb5607", "#fff3b0", "#6a4c93", 3.0, 6.0), + cutout("Rose Layers", "#f28482", "#84a59d", "#f7ede2", "#4a4e69", 6.0, 3.0), + cutout("Monochrome Stack", "#f5f5f5", "#444444", "#ffffff", "#222222", 5.0, 5.0), + ] +} + /// Textures: fills and strokes painted with the catalog's texture effects (grain, canvas and /// burlap surfaces, craquelure, tiles, patchwork, stained glass and water paper). fn textures() -> Vec { @@ -702,6 +722,26 @@ mod tests { assert_eq!(ids.iter().position(|&i| i == "textures"), ids.iter().position(|&i| i == "hand-drawn").map(|i| i + 1), "after Hand-Drawn"); } + #[test] + fn paper_cutouts_have_layered_edges_and_crisp_shadows() { + let lib = builtin_style_library("paper-cutouts").unwrap(); + assert_eq!(lib.name, "Paper Cutouts"); + let names: Vec<&str> = lib.styles.iter().map(|g| g.name.as_str()).collect(); + assert_eq!(names, ["Coral Layers", "Mint Layers", "Midnight Layers", "Sunflower Sheet", "Rose Layers", "Monochrome Stack"]); + for g in &lib.styles { + assert_eq!(g.appearance.items.len(), 3, "{} has a face and two cut edges", g.name); + assert!(matches!(g.appearance.items[0], AppearanceItem::Fill(_))); + assert!(matches!(g.appearance.items[1], AppearanceItem::Stroke(_))); + assert!(matches!(g.appearance.items[2], AppearanceItem::Stroke(_))); + assert_eq!(g.appearance.effects.len(), 1); + let shadow = &g.appearance.effects[0]; + assert_eq!(shadow.id, "stylize.dropShadow"); + assert_eq!(shadow.params["blur"], 0.0); + assert_eq!(shadow.params["opacity"], 100.0); + } + assert_eq!(read(&write(&lib), "Fallback").unwrap(), *lib); + } + /// The built-in styles' Warps draw with the map a new Warp takes. #[test] fn builtin_warp_styles_take_the_nets_map() { 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 a07afd0843..c6a9860189 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -9,6 +9,7 @@ use crate::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, Li mod area; mod char_style; mod composite; +mod kinsoku_set; mod object; mod para_style; mod runs; @@ -25,6 +26,8 @@ pub use composite::{ COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX, CharClass, CompositeClass, CompositeClasses, CompositeFont, CompositePart, CompositeParts, CustomCharSet, }; +pub(crate) use kinsoku_set::read_sets as read_kinsoku_sets; +pub use kinsoku_set::{KINSOKU_BUILT_IN, KINSOKU_CATEGORY_MAX, KINSOKU_NAME_MAX, KINSOKU_SEQUENCE, KINSOKU_SETS_MAX, KinsokuSet}; pub use para_style::{ Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, KinsokuShoriType, LeadingModel, Mojikumi, ParaDirection, ParaStyle, SingleWordJustify, diff --git a/crates/doc/src/text/kinsoku_set.rs b/crates/doc/src/text/kinsoku_set.rs new file mode 100644 index 0000000000..625c5a8ffa --- /dev/null +++ b/crates/doc/src/text/kinsoku_set.rs @@ -0,0 +1,382 @@ +//! Type › Kinsoku Shori Settings…: a custom Kinsoku Shori set, saved with the document. Its four +//! categories hold the characters that may not start a line, those that may not end one, the +//! hanging punctuation that Burasagari lets stand outside a line, and the inseparable sequences +//! that Bunri-Kinshi keeps on one line. A paragraph that uses a set holds a copy of it +//! ([`super::ParaStyle::kinsoku_set`]). +//! +//! Behavior reference: the help page +//! . +//! The name rules and the limits are VectorCraft's own. + +use serde::{Deserialize, Serialize}; + +/// The longest set name, in characters. +pub const KINSOKU_NAME_MAX: usize = 128; +/// The most custom sets a document keeps. +pub const KINSOKU_SETS_MAX: usize = 256; +/// The most characters one category holds (an inseparable sequence counts each of its characters). +pub const KINSOKU_CATEGORY_MAX: usize = 4096; +/// The fewest and most characters of an inseparable sequence. +pub const KINSOKU_SEQUENCE: std::ops::RangeInclusive = 2..=16; +/// The names of the built-in sets, which no custom set may take (in any case). +pub const KINSOKU_BUILT_IN: [&str; 3] = ["None", "Hard", "Soft"]; + +/// A custom Kinsoku Shori set. Each list of characters is sorted and holds each character once; +/// the inseparable sequences are sorted and unique. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(from = "KinsokuSetFile", into = "KinsokuSetFile")] +pub struct KinsokuSet { + pub name: String, + /// Cannot Start Line: characters that never start a line. + pub cannot_start: Vec, + /// Cannot End Line: characters that never end a line. + pub cannot_end: Vec, + /// Hanging Punctuation: characters that Burasagari lets hang outside a line's end. + pub hanging: Vec, + /// Bunri-Kinshi: sequences of characters that a line never breaks inside while Bunri-Kinshi is + /// on. + pub inseparable: Vec, +} + +/// [`KinsokuSet`] as saved: each category of single characters as one string. +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct KinsokuSetFile { + #[serde(default, deserialize_with = "read_name")] + name: String, + #[serde(default, deserialize_with = "read_category")] + cannot_start: String, + #[serde(default, deserialize_with = "read_category")] + cannot_end: String, + #[serde(default, deserialize_with = "read_category")] + hanging: String, + #[serde(default, deserialize_with = "read_sequences")] + inseparable: Vec, +} + +/// The most characters of a name read from a file, spaces around it included; a longer name is +/// not read. +const NAME_READ_MAX: usize = KINSOKU_CATEGORY_MAX; +/// The most characters of a category read from a file, before control and space characters are +/// left out. +const CATEGORY_READ_MAX: usize = KINSOKU_CATEGORY_MAX * 4; +/// The longest inseparable sequence, as a constant for [`Capped`]. +const SEQUENCE_MAX: usize = *KINSOKU_SEQUENCE.end(); + +/// Text read from a file, copied up to `N` characters: a longer text keeps its first `N + 1`, which +/// no rule that allows `N` takes, and is not copied whole. +struct Capped(String); + +impl<'de, const N: usize> Deserialize<'de> for Capped { + fn deserialize>(d: D) -> Result { + struct Text; + impl serde::de::Visitor<'_> for Text { + type Value = Capped; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("text") + } + fn visit_str(self, v: &str) -> Result, E> { + Ok(Capped(v.chars().take(N + 1).collect())) + } + } + d.deserialize_str(Text::) + } +} + +/// A set's name as read from a file: empty, so not read, when it is longer than [`NAME_READ_MAX`]. +fn read_name<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let Capped(name) = Capped::::deserialize(d)?; + Ok(if name.chars().count() > NAME_READ_MAX { String::new() } else { name }) +} + +/// A category of a set as read from a file: its first [`CATEGORY_READ_MAX`] characters. +fn read_category<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let Capped(text) = Capped::::deserialize(d)?; + Ok(text.chars().take(CATEGORY_READ_MAX).collect()) +} + +/// Reads a list, keeping the items `keep` keeps up to `max` of them and skipping the rest of a +/// longer list without storing it. +struct Kept(usize, F, std::marker::PhantomData); + +impl<'de, T: Deserialize<'de>, F: FnMut(&T) -> bool> serde::de::Visitor<'de> for Kept { + type Value = Vec; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("a list") + } + fn visit_seq>(mut self, mut seq: A) -> Result, A::Error> { + let mut out = Vec::new(); + while out.len() < self.0 { + match seq.next_element::()? { + Some(item) if (self.1)(&item) => out.push(item), + Some(_) => {} + None => return Ok(out), + } + } + while seq.next_element::()?.is_some() {} + Ok(out) + } +} + +/// A set's inseparable sequences as read from a file: those [`KinsokuSet::takes_sequence`] takes, +/// at most [`KINSOKU_CATEGORY_MAX`]. A text longer than a sequence is not copied whole. +fn read_sequences<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + let keep = |s: &Capped| KinsokuSet::takes_sequence(&s.0); + let kept = d.deserialize_seq(Kept(KINSOKU_CATEGORY_MAX, keep, std::marker::PhantomData))?; + Ok(kept.into_iter().map(|Capped(s)| s).collect()) +} + +impl From for KinsokuSetFile { + fn from(s: KinsokuSet) -> Self { + Self { + name: s.name, + cannot_start: s.cannot_start.into_iter().collect(), + cannot_end: s.cannot_end.into_iter().collect(), + hanging: s.hanging.into_iter().collect(), + inseparable: s.inseparable, + } + } +} + +impl From for KinsokuSet { + /// A set read from a file keeps what a set can hold: its name trimmed, or no name when + /// [`KinsokuSet::clean_name`] refuses it; each category's characters sorted and unique, without + /// control or space characters, up to [`KINSOKU_CATEGORY_MAX`]; and the inseparable sequences of + /// [`KINSOKU_SEQUENCE`] characters, up to the same count of characters. + fn from(f: KinsokuSetFile) -> Self { + let chars = |s: &str| s.chars().filter(|&c| KinsokuSet::takes_char(c)).take(KINSOKU_CATEGORY_MAX * 4).collect::>(); + let mut set = KinsokuSet { + name: KinsokuSet::clean_name(&f.name).unwrap_or_default(), + cannot_start: chars(&f.cannot_start), + cannot_end: chars(&f.cannot_end), + hanging: chars(&f.hanging), + inseparable: f.inseparable, + }; + set.normalize(); + set.cannot_start.truncate(KINSOKU_CATEGORY_MAX); + set.cannot_end.truncate(KINSOKU_CATEGORY_MAX); + set.hanging.truncate(KINSOKU_CATEGORY_MAX); + let mut total = 0; + set.inseparable.retain(|s| { + total += s.chars().count(); + total <= KINSOKU_CATEGORY_MAX + }); + set + } +} + +/// A document's custom sets as read from a file: each set with a name, the first set of each name +/// (in any case), at most [`KINSOKU_SETS_MAX`]; the sets past those are skipped without being +/// stored. +pub(crate) fn read_sets<'de, D: serde::Deserializer<'de>>(d: D) -> Result>, D::Error> { + let mut seen = std::collections::HashSet::new(); + let keep = move |s: &KinsokuSet| !s.name.is_empty() && seen.insert(s.name.to_lowercase()); + Ok(crate::Shared::new(d.deserialize_seq(Kept(KINSOKU_SETS_MAX, keep, std::marker::PhantomData))?)) +} + +impl KinsokuSet { + /// Do `a` and `b` name the same set: equal in any case? + pub fn same_name(a: &str, b: &str) -> bool { + a == b || a.to_lowercase() == b.to_lowercase() + } + + /// The set of `sets` (a document's custom sets) named `name`, in any case. + pub fn named<'a>(sets: &'a [KinsokuSet], name: &str) -> Option<&'a KinsokuSet> { + sets.iter().find(|s| Self::same_name(&s.name, name)) + } + + /// `name` trimmed, when it can name a custom set: not empty, at most [`KINSOKU_NAME_MAX`] + /// characters, without control characters, and none of [`KINSOKU_BUILT_IN`] in any case. + pub fn clean_name(name: &str) -> Option { + let name = name.trim(); + let ok = !name.is_empty() + && name.chars().count() <= KINSOKU_NAME_MAX + && !name.chars().any(char::is_control) + && !KINSOKU_BUILT_IN.iter().any(|b| Self::same_name(b, name)); + ok.then(|| name.to_string()) + } + + /// Can a category hold character `c`: not a control character nor a space? + pub fn takes_char(c: char) -> bool { + !c.is_control() && !c.is_whitespace() + } + + /// Can `s` be an inseparable sequence: [`KINSOKU_SEQUENCE`] characters that + /// [`Self::takes_char`] takes? + pub fn takes_sequence(s: &str) -> bool { + KINSOKU_SEQUENCE.contains(&s.chars().count()) && s.chars().all(Self::takes_char) + } + + /// Sort each category and keep each character or sequence once. + pub fn normalize(&mut self) { + for list in [&mut self.cannot_start, &mut self.cannot_end, &mut self.hanging] { + list.sort_unstable(); + list.dedup(); + } + self.inseparable.sort_unstable(); + self.inseparable.dedup(); + } + + /// Why this set can't be used, if it can't: a name [`Self::clean_name`] refuses, a character + /// [`Self::takes_char`] refuses, a sequence [`Self::takes_sequence`] refuses, or a category of + /// more than [`KINSOKU_CATEGORY_MAX`] characters. + pub fn check(&self) -> Result<(), String> { + if Self::clean_name(&self.name).as_deref() != Some(self.name.as_str()) { + return Err(format!( + "`{}` can't name a Kinsoku set (1 to {KINSOKU_NAME_MAX} characters, no control characters, not None, Hard or Soft)", + self.name + )); + } + for (key, list) in [("cannotStart", &self.cannot_start), ("cannotEnd", &self.cannot_end), ("hanging", &self.hanging)] { + if list.len() > KINSOKU_CATEGORY_MAX { + return Err(format!("{key}: at most {KINSOKU_CATEGORY_MAX} characters")); + } + if let Some(c) = list.iter().find(|&&c| !Self::takes_char(c)) { + return Err(format!("{key}: U+{:04X} is a control or space character", u32::from(*c))); + } + } + if let Some(s) = self.inseparable.iter().find(|s| !Self::takes_sequence(s)) { + return Err(format!( + "inseparable: `{s}` must be {} to {} characters, none of them control or space characters", + KINSOKU_SEQUENCE.start(), + KINSOKU_SEQUENCE.end() + )); + } + if self.inseparable.iter().map(|s| s.chars().count()).sum::() > KINSOKU_CATEGORY_MAX { + return Err(format!("inseparable: at most {KINSOKU_CATEGORY_MAX} characters in all")); + } + Ok(()) + } + + /// May `c` not start a line? + pub fn cannot_start(&self, c: char) -> bool { + self.cannot_start.binary_search(&c).is_ok() + } + + /// May `c` not end a line? + pub fn cannot_end(&self, c: char) -> bool { + self.cannot_end.binary_search(&c).is_ok() + } + + /// May `c` hang outside a line's end (Burasagari)? + pub fn hangs(&self, c: char) -> bool { + self.hanging.binary_search(&c).is_ok() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::text::{Kinsoku, ParaStyle}; + use serde_json::json; + use std::sync::Arc; + + /// A set is saved with each category as one string and read back as it was; a paragraph saves + /// its copy of the set beside Hard, and a paragraph saved without one reads with none. + #[test] + fn kinsoku_sets_are_saved_with_the_paragraphs_that_use_them() { + let mut set = KinsokuSet { + name: "Tight".into(), + cannot_start: "」。、".chars().collect(), + cannot_end: vec!['「'], + hanging: vec!['、', '。'], + inseparable: vec!["——".into(), "あいう".into()], + }; + set.normalize(); + let saved = serde_json::to_value(&set).unwrap(); + assert_eq!(saved, json!({"name": "Tight", "cannotStart": "、。」", "cannotEnd": "「", "hanging": "、。", "inseparable": ["——", "あいう"]})); + assert_eq!(serde_json::from_value::(saved).unwrap(), set); + let p = ParaStyle { kinsoku_set: Some(Arc::new(set.clone())), ..ParaStyle::default() }; + let v = serde_json::to_value(&p).unwrap(); + assert_eq!(v["kinsoku_set"]["name"], "Tight"); + assert!(v.get("kinsoku").is_none(), "Hard, the default, is left out"); + let back: ParaStyle = serde_json::from_value(v).unwrap(); + assert_eq!(back.kinsoku_set.as_deref(), Some(&set)); + assert_eq!((back.kinsoku, back.kinsoku_name(), back.kinsoku_on()), (Kinsoku::Hard, "Tight", true)); + let old: ParaStyle = serde_json::from_value(json!({"justify": "Left", "kinsoku": "soft"})).unwrap(); + assert_eq!((old.kinsoku_set, old.kinsoku), (None, Kinsoku::Soft)); + assert!(serde_json::to_value(ParaStyle::default()).unwrap().get("kinsoku_set").is_none()); + } + + /// A set read from a file keeps only what a set can hold: each character once, sorted, without + /// control or space characters, at most 4096 to a category, and sequences of 2 to 16 + /// characters; a category left out is empty. Only the start of a longer text is read. + #[test] + fn kinsoku_sets_read_from_a_file_keep_what_a_set_can_hold() { + let long: String = (0x4E00..0x4E00 + 5000).filter_map(char::from_u32).collect(); + let v = json!({ + "name": "Odd", + "cannotStart": "ccba \t\u{0}a", + "cannotEnd": long, + "inseparable": ["a", "ab", "ab", "a b", "abcdefghijklmnopq", "abcdefghijklmnop"], + }); + let set: KinsokuSet = serde_json::from_value(v).unwrap(); + assert_eq!(set.cannot_start, ['a', 'b', 'c']); + assert_eq!(set.cannot_end.len(), KINSOKU_CATEGORY_MAX); + assert!(set.hanging.is_empty()); + assert_eq!(set.inseparable, ["ab", "abcdefghijklmnop"]); + assert!(set.check().is_ok()); + let empty: KinsokuSet = serde_json::from_value(json!({})).unwrap(); + assert!(empty.check().is_err(), "a set needs a name"); + // Only the start of a long text is read: a category's first 16384 characters, a name of at + // most 4096 characters, spaces included, and a sequence's first 17. + let spaces = " ".repeat(CATEGORY_READ_MAX); + let text = format!( + r#"{{"name": "{}Tight", "hanging": "{spaces}、", "cannotEnd": "、", "inseparable": ["{}あ"]}}"#, + " ".repeat(NAME_READ_MAX), + "あ".repeat(100) + ); + let set: KinsokuSet = serde_json::from_str(&text).unwrap(); + assert_eq!((set.name.as_str(), set.hanging.len(), set.cannot_end.len(), set.inseparable.len()), ("", 0, 1, 0)); + let set: KinsokuSet = serde_json::from_str(&format!(r#"{{"name": "{}Tight"}}"#, " ".repeat(NAME_READ_MAX - 5))).unwrap(); + assert_eq!(set.name, "Tight"); + } + + /// A set read from a file under a name a custom set can't take (a built-in name, a blank one) + /// is not read: a paragraph holding it keeps its Kinsoku Set, so it doesn't show as Hard while + /// composing by other characters, and a document's list drops it. The list also keeps the + /// first set of each name in any case, and a name read with spaces around it is trimmed. A + /// paragraph's set read beside None or Soft is not read either. + #[test] + fn kinsoku_sets_read_under_names_a_set_cannot_take_are_dropped() { + let p: ParaStyle = serde_json::from_value(json!({"kinsoku_set": {"name": "Hard", "cannotStart": "あ"}})).unwrap(); + assert_eq!((p.kinsoku_set, p.kinsoku), (None, Kinsoku::Hard)); + let p: ParaStyle = serde_json::from_value(json!({"kinsoku": "none", "kinsoku_set": {"name": "Tight", "cannotStart": "あ"}})).unwrap(); + assert_eq!((p.kinsoku_set.is_none(), p.kinsoku_name()), (true, "None")); + let p: ParaStyle = serde_json::from_value(json!({"kinsoku_set": {"name": " Tight ", "cannotStart": "あ"}})).unwrap(); + assert_eq!(p.kinsoku_name(), "Tight"); + let mut v = serde_json::to_value(crate::Document::new(100.0, 100.0)).unwrap(); + v["kinsoku_sets"] = json!([{"name": "soft"}, {"name": " "}, {"name": "Tight", "cannotEnd": "「"}, {"name": "TIGHT"}, {"name": "Loose"}]); + let d: crate::Document = serde_json::from_value(v).unwrap(); + let names: Vec<&str> = d.kinsoku_sets.iter().map(|s| s.name.as_str()).collect(); + assert_eq!(names, ["Tight", "Loose"]); + assert_eq!(d.kinsoku_sets[0].cannot_end, ['「']); + let mut v = serde_json::to_value(crate::Document::new(100.0, 100.0)).unwrap(); + // The sets past the limit are skipped unread: one that isn't a set at all doesn't fail the + // file. + let mut list: Vec = (0..KINSOKU_SETS_MAX + 5).map(|i| json!({"name": format!("S{i}")})).collect(); + list.push(json!("not a set")); + v["kinsoku_sets"] = json!(list); + let d: crate::Document = serde_json::from_value(v).unwrap(); + assert_eq!(d.kinsoku_sets.len(), KINSOKU_SETS_MAX); + let past: Vec = (0..KINSOKU_CATEGORY_MAX + 1).map(|i| format!("あ{i}")).chain(["x".to_string()]).collect(); + let mut seqs: Vec = past.iter().map(|s| json!(s)).collect(); + seqs.push(json!(7)); + let set: KinsokuSet = serde_json::from_value(json!({"name": "Long", "inseparable": seqs})).unwrap(); + assert!(set.check().is_ok()); + } + + /// A name is trimmed, 1 to 128 characters without control characters, and never None, Hard or + /// Soft in any case; names match in any case. + #[test] + fn kinsoku_set_names_are_checked() { + assert_eq!(KinsokuSet::clean_name(" Tight "), Some("Tight".into())); + for bad in ["", " ", "hard", "SOFT", "None", "a\u{7}b", &"x".repeat(KINSOKU_NAME_MAX + 1)] { + assert_eq!(KinsokuSet::clean_name(bad), None, "{bad:?}"); + } + assert!(KinsokuSet::clean_name(&"漢".repeat(KINSOKU_NAME_MAX)).is_some()); + assert!(KinsokuSet::same_name("Tight", "tIGHT")); + let sets = [KinsokuSet { name: "Tight".into(), ..Default::default() }]; + assert!(KinsokuSet::named(&sets, "TIGHT").is_some() && KinsokuSet::named(&sets, "Loose").is_none()); + } +} diff --git a/crates/doc/src/text/para_style.rs b/crates/doc/src/text/para_style.rs index 17325d071c..3b0847d8fb 100644 --- a/crates/doc/src/text/para_style.rs +++ b/crates/doc/src/text/para_style.rs @@ -1,4 +1,7 @@ +use std::sync::Arc; + use super::char_style::CharStyle; +use super::kinsoku_set::KinsokuSet; use super::tabs_lists::{ParaList, TabStop}; use super::{Deserialize, Serialize}; @@ -256,14 +259,18 @@ pub struct ParaStyle { /// How leading is measured (Paragraph panel menu): from baseline to baseline, or from the top /// of one line's ideographic em box to the next. pub leading_model: LeadingModel, - /// Hanging punctuation (Paragraph panel menu › Burasagari): a comma or full stop ending a line - /// may stand outside the frame. New type takes [`Burasagari::Standard`]; documents from before + /// Hanging punctuation (Paragraph panel menu › Burasagari): the Kinsoku Set's hanging + /// punctuation ending a line may stand outside the frame. New type takes [`Burasagari::Standard`]; documents from before /// it and imported text keep [`Burasagari::None`], except legacy `.ai` type with binding /// punctuation on, which opens with [`Burasagari::Forced`]. pub burasagari: Burasagari, /// Kinsoku (Paragraph panel › Kinsoku Set): which Japanese characters may not start or end a /// line. pub kinsoku: Kinsoku, + /// A custom Kinsoku Shori set (Type › Kinsoku Shori Settings…) chosen in Kinsoku Set: a copy of + /// the document's set of that name, which takes the place of [`Self::kinsoku`]. A paragraph + /// with one keeps [`Kinsoku::Hard`] in `kinsoku`, which builds without custom sets read. + pub kinsoku_set: Option>, /// Kinsoku Shori Type (Paragraph panel menu): how a line keeps those characters off its start /// and end, by pushing them in onto the line or out to the next one. No effect without kinsoku. pub kinsoku_type: KinsokuShoriType, @@ -310,6 +317,21 @@ impl ParaStyle { } } + /// Does kinsoku apply: a custom set, or a Kinsoku Set other than None? + pub fn kinsoku_on(&self) -> bool { + self.kinsoku_set.is_some() || self.kinsoku != Kinsoku::None + } + + /// The name Kinsoku Set shows: the custom set's, or None, Hard or Soft. + pub fn kinsoku_name(&self) -> &str { + match (&self.kinsoku_set, self.kinsoku) { + (Some(set), _) => &set.name, + (None, Kinsoku::None) => "None", + (None, Kinsoku::Hard) => "Hard", + (None, Kinsoku::Soft) => "Soft", + } + } + /// The left indent the layout sets the paragraph at: its left indent, and for a paragraph in a /// list at a level past the first, [`ParaList::level_indent`] more. pub fn laid_out_left_indent(&self) -> f64 { @@ -373,6 +395,8 @@ struct ParaStyleFile { burasagari: Burasagari, #[serde(default, skip_serializing_if = "crate::skip::is_default")] kinsoku: Kinsoku, + #[serde(default, skip_serializing_if = "Option::is_none")] + kinsoku_set: Option>, #[serde(default, skip_serializing_if = "crate::skip::is_default")] kinsoku_type: KinsokuShoriType, #[serde(default, skip_serializing_if = "crate::skip::is_default")] @@ -415,6 +439,7 @@ impl From for ParaStyleFile { leading_model, burasagari, kinsoku, + kinsoku_set, kinsoku_type, bunri_kinshi, kurikaeshi_moji_shori, @@ -443,6 +468,7 @@ impl From for ParaStyleFile { leading_model, burasagari, kinsoku, + kinsoku_set, kinsoku_type, bunri_kinshi, kurikaeshi_moji_shori, @@ -475,6 +501,7 @@ impl From for ParaStyle { leading_model, burasagari, kinsoku, + kinsoku_set, kinsoku_type, bunri_kinshi, kurikaeshi_moji_shori, @@ -483,6 +510,11 @@ impl From for ParaStyle { korean_line_break_anywhere, .. } = f; + // A set whose saved name can't name a custom set (None, Hard or Soft, say) is read as no set: + // the paragraph keeps its Kinsoku Set. A paragraph with a custom set keeps Hard, so one read + // with None or Soft (a paragraph style written before custom sets, applied over one) has no + // custom set. + let kinsoku_set = kinsoku_set.filter(|s| !s.name.is_empty() && kinsoku == Kinsoku::Hard); Self { justify, left_indent, @@ -502,6 +534,7 @@ impl From for ParaStyle { leading_model, burasagari, kinsoku, + kinsoku_set, kinsoku_type, bunri_kinshi, kurikaeshi_moji_shori, @@ -604,19 +637,21 @@ pub enum KinsokuShoriType { PushOutOnly, } -/// Hanging punctuation (burasagari): an East Asian comma or full stop ending a line (、。,.、。) -/// stands outside the line's measure, in the space its punctuation spacing gives it (half width -/// with Line-end Punctuation Half Width). Closing brackets and Latin punctuation don't hang. Shown -/// as None / Regular / Force. +/// Hanging punctuation (burasagari): hanging punctuation ending a line stands outside the line's +/// measure, in the space its punctuation spacing gives it (half width with Line-end Punctuation +/// Half Width). With the built-in Kinsoku Sets that is an East Asian comma or full stop +/// (、。,.、。), and closing brackets and Latin punctuation don't hang; a custom Kinsoku Set hangs +/// the characters in its hanging category. Shown as None / Regular / Force. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum Burasagari { /// A comma or full stop that doesn't fit goes to the next line with the character before it. #[default] None, - /// A comma or full stop that doesn't fit hangs outside the line; one that fits stays inside. + /// Hanging punctuation that doesn't fit hangs outside the line; punctuation that fits stays + /// inside. Standard, - /// A comma or full stop ending a line always hangs, and the rest of the line fills the measure. + /// Hanging punctuation ending a line always hangs, and the rest of the line fills the measure. Forced, } diff --git a/crates/doc/src/trace.rs b/crates/doc/src/trace.rs index 042d6b3ada..a2d17cc990 100644 --- a/crates/doc/src/trace.rs +++ b/crates/doc/src/trace.rs @@ -20,11 +20,18 @@ pub enum TraceView { OutlinesWithSource, /// Only the source image. Source, + /// The source image on the part of the image left of a divider across it, and the traced + /// shapes everywhere else ([`TraceView::split_of`]). + Split, } +/// Where the Split view's divider is when the `trace` settings name no valid position: across the +/// middle of the source image. +pub const DEFAULT_TRACE_SPLIT: f64 = 0.5; + impl TraceView { /// Panel order. - pub const ALL: [Self; 5] = [Self::Result, Self::ResultWithOutlines, Self::Outlines, Self::OutlinesWithSource, Self::Source]; + pub const ALL: [Self; 6] = [Self::Result, Self::ResultWithOutlines, Self::Outlines, Self::OutlinesWithSource, Self::Source, Self::Split]; /// The id used in command params and in the saved `trace` object. pub fn id(self) -> &'static str { @@ -34,6 +41,7 @@ impl TraceView { Self::Outlines => "outlines", Self::OutlinesWithSource => "outlinesWithSourceImage", Self::Source => "sourceImage", + Self::Split => "split", } } @@ -48,14 +56,21 @@ impl TraceView { trace.get("view").and_then(serde_json::Value::as_str).and_then(Self::from_id).unwrap_or_default() } - /// Whether the source image shows. - pub fn shows_source(self) -> bool { - matches!(self, Self::OutlinesWithSource | Self::Source) + /// The Split view's divider in `trace` settings: the fraction of the source image's width, from + /// its left edge in its own pixels, that shows the source image ([`DEFAULT_TRACE_SPLIT`] when + /// `split` is missing, not a number or outside 0 to 1). + pub fn split_of(trace: &serde_json::Value) -> f64 { + trace.get("split").and_then(serde_json::Value::as_f64).filter(|f| (0.0..=1.0).contains(f)).unwrap_or(DEFAULT_TRACE_SPLIT) } - /// Whether the traced shapes show filled. + /// Whether the source image shows (in the Split view, on one side of the divider). + pub fn shows_source(self) -> bool { + matches!(self, Self::OutlinesWithSource | Self::Source | Self::Split) + } + + /// Whether the traced shapes show filled (in the Split view, on one side of the divider). pub fn shows_result(self) -> bool { - matches!(self, Self::Result | Self::ResultWithOutlines) + matches!(self, Self::Result | Self::ResultWithOutlines | Self::Split) } /// Whether the traced shapes' outlines show. @@ -69,6 +84,12 @@ impl Node { pub fn trace_view(&self) -> TraceView { self.extras().trace.as_deref().map(TraceView::of).unwrap_or_default() } + + /// The Split view's divider of an Image Trace object ([`TraceView::split_of`]; + /// [`DEFAULT_TRACE_SPLIT`] for anything else). + pub fn trace_split(&self) -> f64 { + self.extras().trace.as_deref().map_or(DEFAULT_TRACE_SPLIT, TraceView::split_of) + } } #[cfg(test)] @@ -89,6 +110,26 @@ mod tests { g.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "sepia"}))); assert_eq!(g.trace_view(), TraceView::Result); } + + #[test] + fn the_split_divider_reads_a_fraction_and_falls_back_to_the_middle() { + let mut g = Node::group(crate::NodeId(1), vec![]); + assert_eq!(g.trace_split(), DEFAULT_TRACE_SPLIT); + assert_eq!(TraceView::from_id("Split"), Some(TraceView::Split)); + assert!(TraceView::Split.shows_source() && TraceView::Split.shows_result() && !TraceView::Split.shows_outlines()); + for (split, want) in [ + (serde_json::json!(0.25), 0.25), + (serde_json::json!(0), 0.0), + (serde_json::json!(1), 1.0), + (serde_json::json!(-0.1), DEFAULT_TRACE_SPLIT), + (serde_json::json!(1.5), DEFAULT_TRACE_SPLIT), + (serde_json::json!("0.3"), DEFAULT_TRACE_SPLIT), + (serde_json::Value::Null, DEFAULT_TRACE_SPLIT), + ] { + g.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "split", "split": split}))); + assert_eq!(g.trace_split(), want, "{split}"); + } + } #[test] fn live_trace_result_bounds_exclude_the_retained_bitmap_at_any_angle() { use crate::{Appearance, Document, ImageObject, NodeId, NodeKind}; @@ -132,6 +173,13 @@ mod tests { } } } + // The Split view measures the whole image wherever the divider is, so the selection box + // stays put while the divider moves. + for split in [0.0, 0.01, 1.0] { + let want = Rect::new(0.0, 0.0, 200.0, 200.0); + group.extras_mut().trace = Some(Box::new(serde_json::json!({"view": "split", "split": split}))); + assert_eq!((group.geometric_bounds(), group.visual_bounds()), (Some(want), Some(want)), "split {split}"); + } group.extras_mut().trace = None; assert_eq!( group.geometric_bounds(), diff --git a/crates/doc/src/units.rs b/crates/doc/src/units.rs index 7e061d02c0..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"). @@ -348,9 +408,10 @@ pub fn finite_in_every_unit(pt: f64) -> bool { } /// A unitless field value (percent, degrees, counts) with the same `+ - * /` arithmetic as -/// [`Unit::parse`] (`45*2`, `100/3`); text other than digits, `.` and operators reads as nothing. +/// [`Unit::parse`] (`45*2`, `45x2`, `100/3`); text other than digits, `.` and operators reads as +/// nothing. pub fn parse_number(s: &str) -> Option { - if !s.chars().all(|c| c.is_ascii_digit() || " .+-*/".contains(c)) { + if !s.chars().all(|c| c.is_ascii_digit() || " .+-*/xX×".contains(c)) { return None; } // A leading `+` is a sign (`+5`), as a plain number read it. diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index b17045e934..7bba8d44a0 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -210,15 +210,15 @@ pub fn effect_catalog() -> Vec { CLASSIC_EXTRUDE, "Extrude & Bevel (Classic)…", &["Effect", "3D and Materials", "3D (Classic)"], - "{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), 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), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), 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, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.", - json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"drawHiddenFaces":false}), + "{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), 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), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), 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, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others), mapArt: array of 0..64 objects ([]; Map Art, see threeD.mapArt: surface: integer (1..100000; the numbered surface, one map for a surface), symbol: name of a document symbol, x: pt (-1000000..1000000, 0; the offset of the art's center from the center of the surface laid out flat), y: pt (-1000000..1000000, 0), scaleX: % (1..10000, 100; of the symbol's own width), scaleY: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); the surfaces are numbered through the object's solids in the order they are built: each solid's front cap and back cap (none on a hollow solid, cap false), then each side wall from corner to corner of the outline, then the bevel above each wall; a map past the object's surfaces draws nothing; wireframe draws no mapped art), mapShade: bool (false; Shade Artwork: the mapped art takes the tone and highlight of its face), mapInvisible: bool (false; Invisible Geometry: with at least one map, only the mapped art is drawn)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults, the surface numbering and the limits are VectorCraft's own.", + json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"drawHiddenFaces":false,"mapArt":[],"mapShade":false,"mapInvisible":false}), ), g( CLASSIC_REVOLVE, "Revolve (Classic)…", &["Effect", "3D and Materials", "3D (Classic)"], - "{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends and a partial sweep's cut sides closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), 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), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), 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, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.", - json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}), + "{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends and a partial sweep's cut sides closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), 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), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), 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, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), mapArt: array of 0..64 objects ([]; Map Art, see threeD.mapArt: surface: integer (the swept side is surface 1, the only one; in a group, the side of the member with the longest profile; a map of another surface draws nothing), symbol: name of a document symbol, x: pt (-1000000..1000000, 0; the offset of the art's center from the middle of the side unrolled flat, around the axis), y: pt (-1000000..1000000, 0; along the profile), scaleX: % (1..10000, 100; of the symbol's own width), scaleY: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); the art wraps around the side and is drawn where its outside faces the viewer; wireframe draws no mapped art), mapShade: bool (false; Shade Artwork: the mapped art takes the tone and highlight of its face), mapInvisible: bool (false; Invisible Geometry: with at least one map, only the mapped art is drawn)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults, the surface numbering and the limits are VectorCraft's own.", + json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"mapArt":[],"mapShade":false,"mapInvisible":false}), ), g( CLASSIC_ROTATE, diff --git a/crates/effects/src/geometry.rs b/crates/effects/src/geometry.rs index 39924835fd..6a7405648c 100644 --- a/crates/effects/src/geometry.rs +++ b/crates/effects/src/geometry.rs @@ -312,6 +312,36 @@ impl Carry { } } + /// Undo the actual maps of already placed gradients. Failure only changes this temporary + /// appearance; callers retain the stored row unchanged when a map cannot be inverted. + pub(crate) fn unapply_placed(&self, ap: &mut Appearance) -> Option<()> { + for step in self.0.iter().rev() { + for item in &mut ap.items { + if !matches!(item.paint(), vectorcraft_doc::color::Paint::Gradient(_)) { + continue; + } + let map = match *step { + CarryStep::Affine { m, .. } => m, + CarryStep::Boxes { from, to } => match item { + AppearanceItem::Fill(_) => crate::reshape::box_map(from, to), + AppearanceItem::Stroke(s) => crate::reshape::box_map(s.paint_bounds(from), s.paint_bounds(to)), + }, + }; + if vectorcraft_doc::node::flattens(map) { + return None; + } + let inverse = map.inverse(); + if !inverse.is_finite() { + return None; + } + if let vectorcraft_doc::color::Paint::Gradient(g) = item.paint_mut() { + g.transform(inverse); + } + } + } + Some(()) + } + pub(crate) fn push(&mut self, more: Carry) { self.0.extend(more.0); self.1.extend(more.1); diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index e52a85e125..a6f5af916b 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -846,23 +846,19 @@ fn take_sublayer_guides(n: &mut Node, out: &mut Vec>, is_guide: &impl take_held_guides(n, held, out, false, false); } -/// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects -/// reshaping all its members as one piece (the whole art's bounds as their reference box) after -/// the members' own geometry and Pathfinder effects ([`members_as_drawn`]), and its -/// own fills and strokes turned into art painting the members' geometry ([`member_shapes`]) below -/// the members (after a clipping path) or above them, as its contents slot says. Its -/// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live -/// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]), and -/// a Pathfinder operation or compound shape takes the symbol instances among its members as their -/// symbols' art from `doc`. A Transform effect that makes copies with raster effects listed before -/// it gives each copy those raster effects ([`copied_container`]). -pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { +struct PreparedContainer { + m: Node, + guides: Vec>, + paint: bool, + carry: crate::Carry, +} + +/// The existing container pass up to its own rows becoming art. Keep its carried appearance for +/// rendering, and retain the same Carry for freezing only missing stored placements separately. +fn prepare_container(doc: Option<&Document>, n: &Node) -> Option { if !is_container(n) { return None; } - if let Some(t) = crate::reshape::copied_container_raster_at(n) { - return Some(copied_container(doc, n, t)); - } let pathfinder = has_pathfinder(n); let fx = crate::reshape::geometry_effects(n); let paint = has_own_paint(n); @@ -870,6 +866,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { return None; } let mut m = n.clone(); + let mut carry = crate::Carry::default(); // Its ruler guides take no part: they go back above the evaluated art at the end. With effects // that replace or copy the art, so do its guides among the art and those in its sublayers and // groups, which would otherwise go with that art: they stay on `n`, in order, hidden and @@ -896,7 +893,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { let _later = crate::raster::LaterGroups::enter(&n.appearance.effects); members_as_drawn(doc, &mut m); } - let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc); + carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc); // The group's own fills and strokes paint the members as a whole: their gradients follow // the effects as the members' do. if paint && carry.moves(&m.appearance) { @@ -905,6 +902,27 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { } m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects); m.appearance.effects.retain(|e| !is_pathfinder(&e.id)); + Some(PreparedContainer { m, guides, paint, carry }) +} + +/// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects +/// reshaping all its members as one piece (the whole art's bounds as their reference box) after +/// the members' own geometry and Pathfinder effects ([`members_as_drawn`]), and its +/// own fills and strokes turned into art painting the members' geometry ([`member_shapes`]) below +/// the members (after a clipping path) or above them, as its contents slot says. Its +/// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live +/// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]), and +/// a Pathfinder operation or compound shape takes the symbol instances among its members as their +/// symbols' art from `doc`. A Transform effect that makes copies with raster effects listed before +/// it gives each copy those raster effects ([`copied_container`]). +pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { + if !is_container(n) { + return None; + } + if let Some(t) = crate::reshape::copied_container_raster_at(n) { + return Some(copied_container(doc, n, t)); + } + let PreparedContainer { mut m, guides, paint, .. } = prepare_container(doc, n)?; if paint { // A clip group whose clipping type paints strokes is now a group of a clip group and those // strokes ([`crate::reshape::paint_type_clip`]): its own fills and strokes paint inside @@ -931,16 +949,8 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { Some(m) } -/// `n`, a group or layer whose own effects split at `t` ([`crate::reshape::copied_container_raster_at`]), -/// as plain art: the effects before the Transform effect at `t` evaluated on its members as one -/// piece ([`evaluate_container`]), with the raster effects among them, and that piece copied by the -/// Transform effect, each copy a group of its own carrying those raster effects moved, turned, -/// reflected and scaled with it ([`crate::reshape::copied_container_art`]). The art keeps the kind, -/// transparency and opacity mask of `n` and the raster effects from `t` on, which paint once around -/// all the copies; a clip group's or clipping layer's copies each clip, and the art itself does not. -/// Its ruler guides, those in its sublayers and groups included, go once above the copies, hidden -/// and locked as their containers were. -fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node { +/// The exact pre-copy source shared by rendering and stored gradient placement. +fn copied_container_source(doc: Option<&Document>, n: &Node, t: usize) -> (Node, Vec>, Node) { let mut m = n.clone(); let mut guides = vec![]; take_sublayer_guides(&mut m, &mut guides, &Node::is_ruler_guide); @@ -955,6 +965,20 @@ fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node { let _later = crate::raster::LaterGroups::enter(&n.appearance.effects); members_as_drawn(doc, &mut source); } + (m, guides, source) +} + +/// `n`, a group or layer whose own effects split at `t` ([`crate::reshape::copied_container_raster_at`]), +/// as plain art: the effects before the Transform effect at `t` evaluated on its members as one +/// piece ([`evaluate_container`]), with the raster effects among them, and that piece copied by the +/// Transform effect, each copy a group of its own carrying those raster effects moved, turned, +/// reflected and scaled with it ([`crate::reshape::copied_container_art`]). The art keeps the kind, +/// transparency and opacity mask of `n` and the raster effects from `t` on, which paint once around +/// all the copies; a clip group's or clipping layer's copies each clip, and the art itself does not. +/// Its ruler guides, those in its sublayers and groups included, go once above the copies, hidden +/// and locked as their containers were. +fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node { + let (mut m, guides, source) = copied_container_source(doc, n, t); let mut piece = evaluate_container(doc, &source).unwrap_or_else(|| { let mut p = source.clone(); p.appearance.effects = crate::raster::without_geometry(&p.appearance.effects); @@ -988,6 +1012,36 @@ fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node { m } +/// Freeze representable fitted own paints to the box the container pass gives them, retaining +/// every live effect and already explicit placement. Hidden-only containers the pass does not +/// evaluate stay unchanged; this does not add a different fallback to `evaluate_container`. +pub fn pinned_container_appearance(doc: &Document, n: &Node) -> Option { + if !n.appearance.has_unplaced_gradient() { + return None; + } + if let Some(t) = crate::reshape::copied_container_raster_at(n) { + let (_, _, source) = copied_container_source(Some(doc), n, t); + let pinned = pinned_container_appearance(doc, &source)?; + let mut out = (*n.appearance).clone(); + out.items = pinned.items; + return Some(out); + } + let PreparedContainer { m, carry, .. } = prepare_container(Some(doc), n)?; + let bounds = m.geometric_bounds()?; + let mut out = (*n.appearance).clone(); + let mut changed = false; + for (item, original) in out.items.iter_mut().zip(&n.appearance.items) { + if paints(original) + && matches!(original.paint(), Paint::Gradient(g) if !g.is_placed()) + && let Some(pinned) = crate::pinned_gradient_item(original, bounds, &[&carry]) + { + *item = pinned; + changed = true; + } + } + changed.then_some(out) +} + /// Replace each visible member of `n` with geometry or Pathfinder effects of its own, at every /// depth of its groups and layers, by the art it draws ([`evaluate_container`], /// [`crate::reshape::own_effects_art`]), so the geometry effects of `n` reshape what its members diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 7eec83c7f5..fff4705333 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, @@ -106,6 +108,10 @@ pub use solids::{ 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 solids::{ + MAP_ART, MAP_ART_NOT_TAKEN, MAP_INVISIBLE, MAP_SHADE, MAX_MAP_SURFACE, MAX_MAPS, MapSurface, SurfaceKind, SurfaceMap, map_surfaces_at, + map_surfaces_with, surface_maps, takes_map_art, with_surface_map, +}; pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings}; pub use svg_filter::SVG_FILTER; pub use trap::TRAP; diff --git a/crates/effects/src/placement.rs b/crates/effects/src/placement.rs new file mode 100644 index 0000000000..409022cef7 --- /dev/null +++ b/crates/effects/src/placement.rs @@ -0,0 +1,74 @@ +//! Conservative stored placements for gradients fitted by the existing effects passes. + +use vectorcraft_doc::color::{GradientKind, GradientPaint, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem}; +use vectorcraft_geom::Rect; + +use crate::Carry; + +/// Freeze one fitted gradient at the evaluated row's geometric bounds, before its live effects. +/// `carries` are the actual object and item passes, in rendering order. Only missing placement +/// fields are returned; explicit coordinates and the row's other data stay unchanged. A map or +/// model that cannot reproduce the original resolved row returns `None`, leaving it fitted. +pub fn pinned_gradient_item(item: &AppearanceItem, bounds: Rect, carries: &[&Carry]) -> Option { + if gradient(item)?.is_placed() { + return Some(item.clone()); + } + if ![bounds.x0, bounds.y0, bounds.x1, bounds.y1].iter().all(|v| v.is_finite()) { + return None; + } + let resolved = resolve(item, bounds, carries); + if !finite_placement(resolved.items.first()?) { + return None; + } + let mut stored = resolved.clone(); + for carry in carries.iter().rev() { + carry.unapply_placed(&mut stored)?; + } + if !finite_placement(stored.items.first()?) { + return None; + } + let candidate = missing_placement(item, stored.items.first()?)?; + let replayed = resolve(&candidate, bounds, carries); + (finite_placement(replayed.items.first()?) && replayed.approx_eq(&resolved)).then_some(candidate) +} + +fn gradient(item: &AppearanceItem) -> Option<&GradientPaint> { + match item.paint() { + Paint::Gradient(g) => Some(g), + _ => None, + } +} + +fn resolve(item: &AppearanceItem, bounds: Rect, carries: &[&Carry]) -> Appearance { + let mut ap = Appearance { items: vec![item.clone()], ..Default::default() }; + for carry in carries { + carry.apply(&mut ap); + } + ap.pin_gradients(bounds); + ap +} + +fn missing_placement(item: &AppearanceItem, placed: &AppearanceItem) -> Option { + let original = gradient(item)?; + let placed = gradient(placed)?; + let mut out = item.clone(); + let Paint::Gradient(g) = out.paint_mut() else { return None }; + if original.geom.is_none() { + g.geom = placed.geom; + } + if original.gradient.kind == GradientKind::Freeform && !original.has_freeform_points() { + let freeform = placed.freeform.as_ref()?; + match &mut g.freeform { + Some(f) => f.points.clone_from(&freeform.points), + None => g.freeform = Some(freeform.clone()), + } + } + Some(out) +} + +fn finite_placement(item: &AppearanceItem) -> bool { + let Some(g) = gradient(item) else { return false }; + g.geom.is_none_or(|v| v.start.is_finite() && v.end.is_finite() && v.aspect.is_finite() && v.focal.is_none_or(|p| p.is_finite())) + && g.freeform.as_ref().is_none_or(|f| f.points.iter().all(|p| p.at.is_finite())) +} diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 00bf169b93..85c36f2d89 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -3505,7 +3505,7 @@ pub(crate) fn follow_boxes(ap: &mut Appearance, from: Rect, to: Rect) { /// The map that takes box `from` onto box `to` along each axis (along an axis `from` has no extent /// on, a move from its center to `to`'s). -fn box_map(from: Rect, to: Rect) -> vectorcraft_geom::Affine { +pub(crate) fn box_map(from: Rect, to: Rect) -> vectorcraft_geom::Affine { let axis = |a0: f64, a1: f64, b0: f64, b1: f64| { if (a1 - a0).abs() > 1e-12 { let s = (b1 - b0) / (a1 - a0); diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index 43e60a0022..19522873f3 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -113,7 +113,7 @@ pub fn revolve_options(p: &Value) -> Revolve { /// The options Revolve (`id` [`REVOLVE`]) or Revolve (Classic) ([`CLASSIC_REVOLVE`]) with /// parameters `p` sweeps its surface with. A Revolve with graphics lays out its side for them. -fn options_of(id: &str, p: &Value) -> Revolve { +pub(crate) fn options_of(id: &str, p: &Value) -> Revolve { if id == CLASSIC_REVOLVE { classic::options(p) } else { @@ -141,6 +141,7 @@ pub fn validate_revolve_in(doc: Option<&Document>, n: &Node, p: &Value) -> Resul /// [`validate_revolve_in`] for Revolve or Revolve (Classic), `id`. pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> { validate_params_of(id, p)?; + validate_map_symbols(doc, id, p)?; let n = &*resolve_for(doc, n, "Revolve", false)?; let effects = &n.appearance.effects; // The profile is measured before the object's one Revolve, hidden or shown. @@ -215,7 +216,7 @@ fn check_graphics(doc: Option<&Document>, id: &str, path: &PathData, b: Rect, op /// The member of a group whose side takes the group's graphics: the first with the longest /// profile among those with a fill or stroke. -fn graphics_member(shapes: &[Profile], b: Rect, options: Revolve) -> Option { +pub(crate) fn graphics_member(shapes: &[Profile], b: Rect, options: Revolve) -> Option { shapes .iter() .enumerate() @@ -237,6 +238,20 @@ fn check_shadow<'a>(p: &Value, paths: impl IntoIterator, b: /// [`validate_revolve`] for a Revolve with parameters `p` at index `index` of the effects of /// appearance item `target` of `n` ([`validate_item_of`]). +/// An error when the symbols that Revolve (Classic)'s Map Art in `p` places, with the symbols of +/// `doc`, are past the limits of a graphic's art, as on Extrude & Bevel (Classic), or past the +/// limits of art unrolled onto its side, its only surface. +fn validate_map_symbols(doc: Option<&Document>, id: &str, p: &Value) -> Result<(), String> { + match doc.filter(|_| id == CLASSIC_REVOLVE) { + Some(doc) => { + crate::solids::graphics::validate_symbols(doc, p)?; + // The side is surface 1, laid out about the origin; a map past it draws nothing. + crate::solids::graphics::validate_unrolled_symbols(doc, p, &|surface| (surface == 1).then_some(Point::ZERO)) + } + None => Ok(()), + } +} + #[cfg(test)] pub(crate) fn validate_item_revolve(n: &Node, p: &Value, target: usize, index: usize) -> Result<(), String> { validate_item_of(None, n, REVOLVE, p, target, index) @@ -252,6 +267,7 @@ pub(crate) fn validate_item_of(doc: Option<&Document>, n: &Node, id: &str, p: &V return validate_in(doc, n, id, p); } validate_params_of(id, p)?; + validate_map_symbols(doc, id, p)?; const EMPTY: &str = "Revolve requires a shape with at least two anchors"; let (path, _) = object_profile(n, "Revolve")?; if !has_two_anchors(&path) { @@ -334,7 +350,7 @@ fn check_surface(path: &PathData, b: Rect, options: Revolve, item: Option<&Appea /// `options` with one number of samples for every curve of `shapes`, the members of one group: the /// members share Revolve's limits. -fn shared_options(shapes: &[Profile], options: Revolve) -> Result { +pub(crate) fn shared_options(shapes: &[Profile], options: Revolve) -> Result { let samples = vectorcraft_three_d::revolve_curve_samples(shapes.iter().map(|s| &s.path), options)?; Ok(Revolve { curve_samples: Some(samples), ..options }) } @@ -463,10 +479,12 @@ fn group_shadow( /// with its classic surface, as Extrude & Bevel (Classic) does. Revolve's graphics, with the /// symbols of `doc`, are drawn on the faces of the side ([`crate::solids::graphics::surface_parts`]): /// a face with a part of a graphic is a group of the face and that part. With `cast`, the sweep -/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]). The last -/// value is whether the faces go over an underlay of themselves ([`seals`]): the caller seals them -/// ([`sealed_surface`], [`sealed_runs`]) in the order it draws them. -#[allow(clippy::too_many_arguments)] +/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]). With +/// `hide`, a Revolve (Classic) surface without mapped art leaves its faces out, as Invisible +/// Geometry does ([`crate::solids::classic::surface`]). The last two values are whether the faces +/// go over an underlay of themselves ([`seals`]): the caller seals them ([`sealed_surface`], +/// [`sealed_runs`]) in the order it draws them; and whether the faces were left out. +#[allow(clippy::too_many_arguments, clippy::type_complexity)] fn surface( doc: Option<&Document>, n: &Node, @@ -480,7 +498,8 @@ fn surface( expand: bool, copies: &mut Copies, cast: bool, -) -> Option<(Vec, Node, Option, bool)> { + hide: bool, +) -> Option<(Vec, Node, Option, bool, bool)> { #[cfg(test)] crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1)); // A loaded file or a profile edited past the limits keeps drawing its source path instead @@ -500,7 +519,23 @@ fn surface( let drawn = facets.iter().map(|f| Drawn { depth: f.depth, points: f.contours.first().cloned().unwrap_or_default(), plane: f.plane }).collect(); let p = merged_params(&fx.id, &fx.params); - return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p), kept, false)); + // Mapped art goes on the side, the surface's one numbered surface. Its paints' copies + // count with the graphics', and art past the limits is left out. + let map_art = crate::solids::graphics::map_art::MapArt::of(doc, &fx.id, &p); + let layout = map_art.as_ref().and_then(|_| { + let (width, height) = vectorcraft_three_d::revolve_surface_size(path, b, options)?; + let side = vectorcraft_three_d::SolidSurface { kind: vectorcraft_three_d::SurfaceKind::Side, width, height, center: None }; + Some(crate::solids::graphics::map_art::SolidLayout { first: 0, surfaces: vec![side], ends: None }) + }); + let mut budget = crate::solids::graphics::map_art::MapBudget::default(); + let mapped = map_art.as_ref().zip(layout.as_ref()).map(|(art, layout)| crate::solids::classic::Mapped { + art, + layout, + budget: &mut budget, + copies: &mut copies.graphics, + }); + let (art, hidden, _) = crate::solids::classic::surface(n, &facets, &paint, (opacity, blend), &p, mapped, hide); + return Some((drawn, art, kept, false, hidden)); } let colored = colored(&options); let (faces, kept) = if cast { @@ -632,7 +667,7 @@ fn surface( let mut group = Node::group(n.id, children); group.opacity = opacity; group.blend = blend; - Some((keys, group, kept, seal)) + Some((keys, group, kept, seal, false)) } /// Plain `surface` ([`surface`]: a group of its faces) over an underlay of its faces when `seal` @@ -722,8 +757,8 @@ fn object_surface( let b = path.bounds()?; let (paint, opacity, blend) = paint_of(item); let cast = casts(fx, opacity); - surface(doc, n, path, b, rule_options(fx, rule), fx, paint, opacity, blend, expand, copies, cast) - .map(|(_, art, kept, seal)| (sealed_surface(n.id, art, seal), kept)) + surface(doc, n, path, b, rule_options(fx, rule), fx, paint, opacity, blend, expand, copies, cast, false) + .map(|(_, art, kept, seal, _)| (sealed_surface(n.id, art, seal), kept)) } /// The options effect `fx` sweeps the surface of a profile filled with `rule` with: its cut sides @@ -797,11 +832,12 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul } let (path, rule) = object_profile(n, "Revolve")?; let ctx = GeomContext::of(n); - let mesh = |path: &PathData, fx: &Effect, item: &AppearanceItem| -> Result { + let mut keep = |out: &mut Vec, path: &PathData, fx: &Effect, item: &AppearanceItem| -> Result<(), String> { let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?; let (paint, opacity, _) = paint_of(item); - let mesh = vectorcraft_three_d::revolve_mesh(path, rule, b, fx_options(fx))?; - Ok(crate::SolidMesh::plain(mesh, crate::solids::mesh_color(&paint, opacity))) + surface_meshes(path, rule, b, fx, fx_options(fx), (&paint, opacity, 1.0), true)? + .into_iter() + .try_for_each(|m| crate::solids::keep_mesh(out, total, m, limit)) }; if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) { let before = n.appearance.effects.get(..index).unwrap_or_default(); @@ -810,7 +846,7 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul let paints = solid_paints(n); let item = surface_item(&paints).ok_or("the revolved object has no fill or stroke")?; let mut out = vec![]; - crate::solids::keep_mesh(&mut out, total, mesh(&path, fx, item)?, limit)?; + keep(&mut out, &path, fx, item)?; return Ok(out); } let path = geometry(&path, &n.appearance.effects, &ctx); @@ -820,12 +856,69 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul && let Some(fx) = item.effects().get(index) { let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item)); - crate::solids::keep_mesh(&mut out, total, mesh(&p, fx, item)?, limit)?; + keep(&mut out, &p, fx, item)?; } } Ok(out) } +/// The surface Revolve `fx` sweeps from `path` (filled under `rule`) about the axis of `b` with +/// `options`, painted `paint` at `opacity` in a group member of opacity `member` (1 for an object +/// of its own), as meshes. When `graphics` and `fx` maps graphics onto the side, the side's +/// triangles are a mesh of their own with the point of the unrolled side surface each corner shows +/// ([`crate::MeshGraphics`]), the points the canvas places the graphics by +/// ([`crate::solids::graphics::surface_parts`]), after a mesh of the rest (the end caps and the cut +/// sides). As on the canvas, the graphics take `opacity`, and `member` applies to the side and its +/// graphics together. Otherwise the surface is one plain mesh. +fn surface_meshes( + path: &PathData, + rule: FillRule, + b: Rect, + fx: &Effect, + options: Revolve, + (paint, opacity, member): (&Paint, f32, f32), + graphics: bool, +) -> Result, String> { + let color = crate::solids::mesh_color(paint, opacity * member); + let list: Vec = if graphics && fx.id == REVOLVE && options.map_surface { + crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)).into_iter().filter(|g| g.face == crate::PlanarFace::Front).collect() + } else { + vec![] + }; + if list.is_empty() { + return Ok(vec![crate::SolidMesh::plain(vectorcraft_three_d::revolve_mesh(path, rule, b, options)?, color)]); + } + let (mesh, on) = vectorcraft_three_d::revolve_mesh_surface(path, rule, b, options)?; + let (mut side, mut rest, mut art) = (vectorcraft_three_d::Mesh::default(), vectorcraft_three_d::Mesh::default(), vec![]); + for (t, points) in mesh.triangles.iter().zip(&on) { + let corner = |i: u32| mesh.positions.get(i as usize).copied().zip(mesh.normals.get(i as usize).copied()); + let Some(corners) = t.iter().map(|&i| corner(i)).collect::>>() else { continue }; + let into = match points { + Some(points) => { + art.extend(points); + &mut side + } + None => &mut rest, + }; + let base = into.positions.len() as u32; + for (p, n) in corners { + into.positions.push(p); + into.normals.push(n); + } + into.triangles.push([base, base + 1, base + 2]); + } + let mut out = vec![]; + if !rest.is_empty() { + out.push(crate::SolidMesh::plain(rest, color)); + } + if !side.is_empty() { + let graphics = + crate::MeshGraphics { face: crate::PlanarFace::Front, graphics: list, center: Point::ZERO, art, opacity, object: member.clamp(0.0, 1.0) }; + out.push(crate::SolidMesh { mesh: side, color, graphics: Some(graphics) }); + } + Ok(out) +} + /// The outline of every face [`revolve_art`] draws for `n`'s Revolve or Revolve (Classic) (its symbol /// instances, blends and clipping groups already resolved), in document coordinates: with the /// effect on the object, the surface in its top visible fill (else its stroke); with it on fills and strokes, one surface for each of @@ -919,12 +1012,15 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result, n: &Node, expand: bool) -> Option { let mut opaque = true; // The graphics go once, on the side of the member with the longest profile. Without graphics // no member is measured for them. - let mapped = fx.id == REVOLVE && !crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)).is_empty(); + // Revolve (Classic)'s mapped art goes on that member's side too. + let p = merged_params(&fx.id, &fx.params); + let mapped = (fx.id == REVOLVE && !crate::solids::mapped_graphics(&p).is_empty()) + || (fx.id == CLASSIC_REVOLVE && !crate::solids::surface_maps(&p).is_empty()); let longest = if mapped { graphics_member(&shapes, b, options) } else { None }; - for (k, s) in shapes.iter().enumerate() { - let Some(item) = surface_item(&s.items) else { - kept.push(None); - continue; - }; + // Member `k`'s surface, its faces left out with `hide`, with its opacity and blending mode; + // `None` for a member with no fill or stroke. + let member = |k: usize, s: &Profile, hide: bool, copies: &mut Copies| { + let item = surface_item(&s.items)?; // The opacity and blending of the member and the groups it is in apply through its scopes. let (paint, opacity, blend) = paint_of(item); - opaque &= opacity >= 1.0 && blend == Default::default() && s.scopes.is_empty(); // A member with transparency of its own keeps every face, as a transparent object does. let expand = expand && s.scopes.is_empty(); let doc = doc.filter(|_| longest == Some(k)); let cast = casts(fx, opacity * s.opacity); let options = Revolve { fill_rule: s.rule, ..options }; - let (depths, art, faces, seal) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?; + Some((opacity, blend, surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, copies, cast, hide))) + }; + // With Invisible Geometry the other members leave their faces out too, once the mapped art on + // the longest member's side has left that member's faces out, so it is built first. + let invisible = fx.id == CLASSIC_REVOLVE && doc.is_some() && p.get(crate::solids::MAP_INVISIBLE).and_then(Value::as_bool).unwrap_or(false); + let mut first = None; + if let Some(l) = longest.filter(|_| invisible) + && let Some(s) = shapes.get(l) + { + first = member(l, s, false, &mut copies); + } + let hide = matches!(first, Some((_, _, Some((_, _, _, _, true))))); + for (k, s) in shapes.iter().enumerate() { + let built = if longest == Some(k) && first.is_some() { first.take() } else { member(k, s, hide, &mut copies) }; + let Some((opacity, blend, built)) = built else { + kept.push(None); + continue; + }; + opaque &= opacity >= 1.0 && blend == Default::default() && s.scopes.is_empty(); + let (depths, art, faces, seal, _) = built?; surfaces.push((depths, art, s.scopes.as_slice())); kept.push(faces); seals.push(seal); @@ -1870,8 +1986,9 @@ mod tests { let path = n.path_data().unwrap(); let fx = n.appearance.effects.first().unwrap(); let (paint, opacity, blend) = paint_of(n.appearance.items.first().unwrap()); - let (_, art, _, seal) = - surface(None, n, path, path.bounds().unwrap(), fx_options(fx), fx, paint, opacity, blend, false, &mut Copies::default(), false).unwrap(); + let (_, art, _, seal, _) = + surface(None, n, path, path.bounds().unwrap(), fx_options(fx), fx, paint, opacity, blend, false, &mut Copies::default(), false, false) + .unwrap(); (art, seal) } @@ -2129,7 +2246,7 @@ mod tests { .map(|s| { let (paint, opacity, blend) = paint_of(surface_item(&s.items).unwrap()); let cast = casts(&fx, opacity * s.opacity); - surface(None, &g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast).unwrap().2 + surface(None, &g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast, false).unwrap().2 }) .collect(); assert!(kept.iter().all(Option::is_some), "{id} {params}"); @@ -2165,7 +2282,7 @@ mod tests { .map(|s| { let (paint, opacity, blend) = paint_of(surface_item(&s.items).unwrap()); let cast = casts(&fx, opacity * s.opacity); - surface(None, g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast).unwrap().2 + surface(None, g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast, false).unwrap().2 }) .collect(); [group_shadow(g.id, &fx, &shapes, b, options, kept).unwrap(), group_shadow(g.id, &fx, &shapes, b, options, vec![]).unwrap()] diff --git a/crates/effects/src/revolve/classic.rs b/crates/effects/src/revolve/classic.rs index 4aefb13eef..97bfa67add 100644 --- a/crates/effects/src/revolve/classic.rs +++ b/crates/effects/src/revolve/classic.rs @@ -4,6 +4,8 @@ use serde_json::Value; use vectorcraft_three_d::Revolve; +use crate::solids::graphics::map_art; + pub const CLASSIC_REVOLVE: &str = "threeD.classicRevolve"; /// The numeric parameters: (key, lowest, highest, whole numbers only). @@ -23,19 +25,28 @@ const RANGES: [(&str, f64, f64, bool); 13] = [ ("blendSteps", 1.0, 256.0, true), ]; -const FLAGS: [&str; 3] = ["cap", "lightBehind", "preserveSpotColors"]; +const FLAGS: [&str; 5] = ["cap", "lightBehind", "preserveSpotColors", map_art::MAP_SHADE, map_art::MAP_INVISIBLE]; /// The surface Revolve (Classic)'s parameters `p` sweep: Revolve's angle, cap, offset, edge, -/// rotation and perspective, built unshaded, since the classic surfaces light its faces. +/// rotation and perspective, built unshaded, since the classic surfaces light its faces. With +/// mapped art its side is laid out for it. pub(crate) fn options(p: &Value) -> Revolve { - Revolve { shade: false, smooth_shading: false, lights: None, light_color: [1.0; 3], ..super::revolve_options(p) } + Revolve { + shade: false, + smooth_shading: false, + lights: None, + light_color: [1.0; 3], + map_surface: !map_art::surface_maps(p).is_empty(), + ..super::revolve_options(p) + } } /// Check Revolve (Classic)'s parameters `p` (its defaults filled in) beyond the checks it shares /// with Revolve: every key is one of its parameters, numbers are in range, flags are true or false, -/// and the surface and shading color are named. +/// the surface and shading color are named, and `mapArt` holds valid maps. pub(crate) fn validate(p: &Value) -> Result<(), String> { - crate::solids::classic::validate_classic(CLASSIC_REVOLVE, p, &RANGES, &FLAGS) + crate::solids::classic::validate_classic(CLASSIC_REVOLVE, p, &RANGES, &FLAGS)?; + map_art::validate(CLASSIC_REVOLVE, p) } #[cfg(test)] diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index bdbe16547a..93de078d84 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -24,6 +24,10 @@ mod source; pub(crate) use source::{resolve, resolve_for}; pub(crate) mod graphics; +pub use graphics::map_art::{ + MAP_ART, MAP_ART_NOT_TAKEN, MAP_INVISIBLE, MAP_SHADE, MAX_MAP_SURFACE, MAX_MAPS, SurfaceMap, surface_maps, takes_map_art, with_surface_map, +}; +use graphics::map_art::{MapArt, MapBudget, SolidLayout}; pub use graphics::{ GRAPHICS, GraphicFrame, MAX_GRAPHICS, MappedGraphic, MeshGraphics, graphic_symbols, mapped_graphics, mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, takes_graphics, with_graphic, @@ -32,6 +36,7 @@ pub use graphics::{ MAX_OFFSET as GRAPHIC_MAX_OFFSET, NOT_TAKEN as GRAPHICS_NOT_TAKEN, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols, fitting as graphic_fitting_scale, rename_appearance_graphic_symbol, }; +pub use vectorcraft_three_d::SurfaceKind; pub(crate) mod shadow; @@ -182,6 +187,7 @@ pub fn extrude_options(p: &Value) -> Extrude { both_sides: flag(p, "bevelBothSides", false), }), hidden: false, + map_surfaces: false, map_surface: false, } } @@ -461,11 +467,22 @@ fn check_membrane_graphics(doc: Option<&Document>, n: &Node, id: &str, p: &Value /// ([`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. +/// included. On Extrude & Bevel (Classic), the art Map Art places on walls and bevels must also fit +/// ([`graphics::validate_unrolled_symbols`]). 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); + // Map Art unrolls its art onto walls and bevels; the caps draw it as it is. + if id == CLASSIC_EXTRUDE && !surface_maps(p).is_empty() { + let options = vectorcraft_three_d::Extrude { map_surfaces: true, ..classic_extrude_options(p) }; + let unrolled: Vec> = parts + .iter() + .flat_map(|(_, _, area, rule, _, _)| vectorcraft_three_d::extrude_surfaces(area, *rule, bounds, options).unwrap_or_default()) + .map(|s| (!matches!(s.kind, SurfaceKind::End(_))).then(|| graphics::map_art::flat_center(&s))) + .collect(); + graphics::validate_unrolled_symbols(doc, p, &|surface| surface.checked_sub(1).and_then(|k| unrolled.get(k).copied().flatten()))?; + } if side_carrier(id, p, &parts, bounds).is_none() { return Ok(()); } @@ -2003,8 +2020,11 @@ fn surfaces_with( filled.push(Filled { at: out.len(), member, caps, opacity, blend, masked: masks_surface(&paint, colored) }); } } - let art = - if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored, false) }; + let art = if classic { + classic::surface(n, &f, &paint, (opacity, blend), &p, None, false).0 + } else { + surface(n, f, &paint, opacity, blend, colored, false) + }; out.push((s.scopes.as_slice(), Arc::new(art))); } } @@ -2018,15 +2038,28 @@ fn surfaces_with( let carrier = if graphics_on { side_carrier(&fx.id, &p, &parts, bounds) } else { None }; let mut solids = vec![]; let mut built = vec![]; + // With mapped art, each solid's place among the object's numbered surfaces: the surfaces are + // counted through the parts in order, those of a part whose solid is left out too. + let map_art = MapArt::of(doc, &fx.id, &p).filter(|_| fx.id == CLASSIC_EXTRUDE); + let mut layouts: Vec = vec![]; + let mut surfaces_before = 0usize; let made = built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast, membrane, carrier); - for (k, ((item, opacity, _, _, scopes, member), f)) in parts.iter().zip(made).enumerate() { + for (k, ((item, opacity, area, rule, scopes, member), f)) in parts.iter().zip(made).enumerate() { let item: &AppearanceItem = item; + let layout = map_art.as_ref().map(|_| { + let options = classic_extrude_options(&p); + let surfaces = vectorcraft_three_d::extrude_surfaces(area, *rule, bounds, options).unwrap_or_default(); + let first = surfaces_before; + surfaces_before += surfaces.len(); + SolidLayout { first, surfaces, ends: Some((bounds, options, view_options(&p))) } + }); match f { Ok(Some((f, _))) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => { return None; } Ok(Some((f, faces))) => { solids.push((item, *opacity, *scopes, f, *member)); + layouts.extend(layout); built.push(faces); } // A stroke's outline past the limits is left out; the fill's solid still draws. Built @@ -2115,6 +2148,34 @@ fn surfaces_with( let split = split && solids.iter().filter(|(item, _, _, f, _)| composite(item, f)).map(|(.., f, _)| f.len()).sum::() <= MAX_FACE_COMPOSITES; let members: Vec = solids.iter().map(|s| s.4).collect(); + // The classic surfaces of the solids, with mapped art when the effect has maps. When the art of + // any solid is past the limits the object's maps share, every solid draws without mapped art. + let mut classic_arts = if classic { + let draw = |with_art: bool, copies: &mut usize| { + let mut budget = MapBudget::default(); + let mut dropped = false; + let mut arts = Vec::with_capacity(solids.len()); + for (k, (item, member, _, f, _)) in solids.iter().enumerate() { + let (paint, opacity, blend) = paint_of(item, *member); + let mapped = map_art.as_ref().filter(|_| with_art).zip(layouts.get(k)).map(|(art, layout)| classic::Mapped { + art, + layout, + budget: &mut budget, + copies: &mut *copies, + }); + let (art, _, left_out) = classic::surface(n, f, &paint, (opacity, blend), &p, mapped, false); + dropped |= left_out; + arts.push(art); + } + (arts, dropped) + }; + let mut used = paint_bytes; + let (arts, dropped) = draw(map_art.is_some(), &mut used); + if dropped { draw(false, &mut paint_bytes).0 } else { arts } + } else { + vec![] + } + .into_iter(); // Which surfaces lie over an underlay of their facets, in one order or whole // ([`in_one_order`], [`underlaid_surface`]). let seals: Vec = solids.iter().map(|(.., f, _)| underlaid(f, colored)).collect(); @@ -2150,7 +2211,7 @@ fn surfaces_with( }; let drawn = parts.iter().any(|p| !p.is_empty()); let art = if classic { - classic::surface(n, f, &paint, opacity, blend, &p) + classic_arts.next().unwrap_or_else(|| Node::group(n.id, vec![])) } else { let faces = drawn || (split && shared.get(shape).copied().unwrap_or(false)); with_surface_parts(n.id, surface(n, f, &paint, opacity, blend, colored, faces), parts) @@ -2481,28 +2542,7 @@ pub fn graphic_side_size(doc: Option<&Document>, n: &Node, item: Option, /// 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())?; - let mut shapes = members(n, "").ok()?; - reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes); - (fx, shapes) - } else { - let (path, rule) = profile(n)?; - let ctx = GeomContext::of(n); - match item { - None => { - let (index, fx) = pick(&n.appearance.effects)?; - let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx); - (fx, vec![Profile { path, rule, items: solid_paints(n), opacity: 1.0, scopes: vec![] }]) - } - Some(k) => { - let it = n.appearance.items.get(k)?; - let (index, fx) = pick(it.effects())?; - let path = geometry(&geometry(&path, &n.appearance.effects, &ctx), it.effects().get(..index)?, &ctx.item(it)); - (fx, vec![Profile { path, rule, items: vec![it.clone()], opacity: 1.0, scopes: vec![] }]) - } - } - }; + let (fx, shapes) = picked(n, item, pick)?; Some((fx.clone(), shapes)) } @@ -2560,6 +2600,175 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<' }) } +/// One numbered surface of a 3D object that takes Map Art: what it is, its size laid out flat in +/// points, whether the viewer sees any of it, and the edges of its outline on the page. +#[derive(Clone, Debug, PartialEq)] +pub struct MapSurface { + pub kind: SurfaceKind, + pub width: f64, + pub height: f64, + pub visible: bool, + pub outline: Vec<[Point; 2]>, +} + +/// The numbered surfaces of the 3D effect at `index` of the effects of `n` (on the object itself +/// with `item` `None`, else on its fill or stroke `item`), which must be an Extrude & Bevel +/// (Classic) or Revolve (Classic), shown or hidden, in the order Map Art numbers them from 1. +/// `None` for any other effect, and when the object's art can't be built. +pub fn map_surfaces_at(doc: Option<&Document>, n: &Node, item: Option, index: usize) -> Option> { + let n = &*resolve(doc, n, "").ok()?; + let (fx, shapes) = picked(n, item, &|fx: &[Effect]| fx.get(index).filter(|e| takes_map_art(&e.id)).map(|e| (index, e)))?; + let p = crate::merged_params(&fx.id, &fx.params); + let b = union_bounds(&shapes)?; + // The edges of `facets` on each local surface of `surfaces`, in one pass over the facets: every + // edge of an end, and the edges of the cells that lie along the sides of the flat surface. + let seen = |surfaces: &[vectorcraft_three_d::SolidSurface], facets: &[Facet]| -> Vec> { + let mut edges: Vec> = vec![vec![]; surfaces.len()]; + // Each surface laid out flat, and how near a point must be to its side to lie along it. + let frames: Vec<(Rect, f64)> = surfaces + .iter() + .map(|s| { + let flat = match s.kind { + SurfaceKind::Side => Rect::new(-s.width / 2.0, -s.height / 2.0, s.width / 2.0, s.height / 2.0), + _ => Rect::new(0.0, 0.0, s.width, s.height), + }; + (flat, (s.width.max(s.height) * 1e-6).max(1e-9)) + }) + .collect(); + let ends: Vec<(usize, PlanarFace)> = surfaces + .iter() + .enumerate() + .filter_map(|(k, s)| match s.kind { + SurfaceKind::End(end) => Some((k, end)), + _ => None, + }) + .collect(); + for f in facets.iter().filter(|f| !f.away) { + if let Some(at) = f.end { + for &(k, end) in &ends { + if end == at + && let Some(out) = edges.get_mut(k) + { + for c in &f.contours { + out.extend(c.iter().zip(c.iter().cycle().skip(1)).take(c.len()).map(|(a, b)| [*a, *b])); + } + } + } + } + let Some(cell) = f.cell.as_deref().filter(|c| c.uv.len() == c.page.len()) else { continue }; + let k = cell.surface; + // A facet of an end adds to an end's surface only its own edges, above. + if f.end.is_some() && surfaces.get(k).is_some_and(|s| matches!(s.kind, SurfaceKind::End(_))) { + continue; + } + let (Some(&(flat, near)), Some(out)) = (frames.get(k), edges.get_mut(k)) else { continue }; + let count = cell.uv.len(); + for i in 0..count { + let j = (i + 1) % count; + let (Some(a), Some(c)) = (cell.uv.get(i), cell.uv.get(j)) else { continue }; + let along = |at: f64, of: fn(&Point) -> f64| (of(a) - at).abs() <= near && (of(c) - at).abs() <= near; + let on_side = along(flat.x0, |p| p.x) || along(flat.x1, |p| p.x) || along(flat.y0, |p| p.y) || along(flat.y1, |p| p.y); + if let (true, Some(from), Some(to)) = (on_side, cell.page.get(i), cell.page.get(j)) { + out.push([*from, *to]); + } + } + } + edges + }; + let listed = |surfaces: &[vectorcraft_three_d::SolidSurface], facets: &[Facet], out: &mut Vec| { + for (s, outline) in surfaces.iter().zip(seen(surfaces, facets)) { + out.push(MapSurface { kind: s.kind, width: s.width, height: s.height, visible: !outline.is_empty(), outline }); + } + }; + let mut out = vec![]; + if fx.id == crate::CLASSIC_REVOLVE { + // Revolve (Classic) has one surface: its side, in a group that of the member with the + // longest profile. A group's members share one sampling of their curves, and a group past + // those shared limits has no surface. + let mut options = vectorcraft_three_d::Revolve { map_surface: true, ..crate::revolve::options_of(&fx.id, &p) }; + if is_container(n) { + options = crate::revolve::shared_options(&shapes, options).ok()?; + } + let shape = shapes.get(crate::revolve::graphics_member(&shapes, b, options)?)?; + let (width, height) = vectorcraft_three_d::revolve_surface_size(&shape.path, b, options)?; + let surfaces = [vectorcraft_three_d::SolidSurface { kind: SurfaceKind::Side, width, height, center: None }]; + let facets = vectorcraft_three_d::revolve_facets(&shape.path, b, options).unwrap_or_default(); + listed(&surfaces, &facets, &mut out); + return Some(out); + } + let (parts, bounds) = solid_parts(&shapes, b); + let options = vectorcraft_three_d::Extrude { map_surfaces: true, ..classic_extrude_options(&p) }; + let view = view_options(&p); + // The faces of the solids count together against the limit the art draws within. + let mut kept = 0usize; + for (_, _, area, rule, _, _) in &parts { + let surfaces = vectorcraft_three_d::extrude_surfaces(area, *rule, bounds, options).unwrap_or_default(); + let facets = vectorcraft_three_d::extrude(area, *rule, bounds, options, view).unwrap_or_default(); + kept = kept.saturating_add(facets.len()); + if kept > MAX_OBJECT_FACES { + return None; + } + listed(&surfaces, &facets, &mut out); + } + Some(out) +} + +/// [`map_surfaces_at`] for `n` as it is with 3D effect `id` and parameters `p` among the effects of +/// the object itself (`item` `None`) or of its fill or stroke `item`: in place of the effect at +/// `index` when that is an effect `id`, else of the last effect `id` there, or after those effects +/// when there is none. A dialog lists the surfaces of the effect it edits with this, whether or not +/// its preview has changed the object. +pub fn map_surfaces_with( + doc: Option<&Document>, + n: &Node, + (item, index): (Option, Option), + id: &str, + p: &Value, +) -> Option> { + let mut n = n.clone(); + let effects = n.appearance.effects_mut(item)?; + let at = index.filter(|&k| effects.get(k).is_some_and(|e| e.id == id)).or_else(|| effects.iter().rposition(|e| e.id == id)); + let index = match at { + Some(index) => { + effects.get_mut(index)?.params = p.clone(); + index + } + None => { + effects.push(crate::new_effect(id, p)?); + effects.len() - 1 + } + }; + map_surfaces_at(doc, &n, item, index) +} + +/// The 3D effect `pick` finds in the effects of `n` (resolved) or of its `item`, with the shapes +/// it builds from: the members of a group or layer, or the object's own profile after the geometry +/// effects before the 3D effect. +fn picked<'n>(n: &'n Node, item: Option, pick: &Pick<'_>) -> Option<(&'n Effect, Vec)> { + Some(if is_container(n) { + let (index, fx) = pick(&n.appearance.effects).filter(|_| item.is_none())?; + let mut shapes = members(n, "").ok()?; + reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes); + (fx, shapes) + } else { + let (path, rule) = profile(n)?; + let ctx = GeomContext::of(n); + match item { + None => { + let (index, fx) = pick(&n.appearance.effects)?; + let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx); + (fx, vec![Profile { path, rule, items: solid_paints(n), opacity: 1.0, scopes: vec![] }]) + } + Some(k) => { + let it = n.appearance.items.get(k)?; + let (index, fx) = pick(it.effects())?; + let path = geometry(&geometry(&path, &n.appearance.effects, &ctx), it.effects().get(..index)?, &ctx.item(it)); + (fx, vec![Profile { path, rule, items: vec![it.clone()], opacity: 1.0, scopes: vec![] }]) + } + } + }) +} + /// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates. pub fn graphic_bounds(doc: &Document, name: &str) -> Option { graphics::art_bounds(doc, name) @@ -2602,8 +2811,8 @@ impl SolidMesh { /// The parts of `mesh`, a solid that 3D effect `id` with parameters `p` built about `bounds`, painted /// `color` from a fill or stroke at `opacity`: for each planar face that carries graphics (Extrude & /// Bevel's caps, the plane), the triangles on it as a mesh of their own with the art point of each -/// corner ([`MeshGraphics`]), then the rest. Revolve's side, whose graphics are not mapped onto its -/// mesh, stays plain. +/// corner ([`MeshGraphics`]), then the rest. Revolve's meshes are split by their side instead +/// (`revolve::surface_meshes`), so a Revolve's mesh stays plain here. fn split_graphics(id: &str, p: &Value, bounds: Rect, mesh: Mesh, (color, opacity): ([f32; 4], f32)) -> Vec { let list = graphics::mapped_graphics(p); if list.is_empty() || !takes_graphics(id) || id == crate::REVOLVE { diff --git a/crates/effects/src/solids/classic.rs b/crates/effects/src/solids/classic.rs index 79d87fdb25..609743fe03 100644 --- a/crates/effects/src/solids/classic.rs +++ b/crates/effects/src/solids/classic.rs @@ -9,6 +9,7 @@ use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node}; use vectorcraft_geom::Rect; use vectorcraft_three_d::{Bevel, BevelShape, ClassicShading, ClassicSurface, Extrude, Facet, Light}; +use super::graphics::map_art::{self, MapArt, MapBudget, SolidLayout}; use crate::util::{flag, num, text}; pub const CLASSIC_EXTRUDE: &str = "threeD.classicExtrude"; @@ -51,10 +52,21 @@ pub fn classic_extrude_options(p: &Value) -> Extrude { ..Bevel::default() }), hidden: flag(p, "drawHiddenFaces", false) || classic_shading(p).surface == ClassicSurface::Wireframe, + // The numbered surfaces are laid out only for an effect that maps art onto them. + map_surfaces: !map_art::surface_maps(p).is_empty(), ..Extrude::default() } } +/// The mapped art of one solid for [`surface`]: the effect's maps, the solid's place among the +/// object's numbered surfaces, and the limits the object's mapped art shares. +pub(crate) struct Mapped<'a, 'd> { + pub(crate) art: &'a MapArt<'d>, + pub(crate) layout: &'a SolidLayout, + pub(crate) budget: &'a mut MapBudget, + pub(crate) copies: &'a mut usize, +} + /// The color faces darken toward: black (for Black Overprint too), the custom color, or none (faces /// keep their paint and only the highlight lightens them). fn shading_color(p: &Value) -> Option { @@ -102,13 +114,15 @@ const RANGES: [(&str, f64, f64, bool); 13] = [ ("blendSteps", 1.0, 256.0, true), ]; -const FLAGS: [&str; 5] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces", "preserveSpotColors"]; +const FLAGS: [&str; 7] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces", "preserveSpotColors", map_art::MAP_SHADE, map_art::MAP_INVISIBLE]; /// Check Extrude & Bevel (Classic)'s parameters `p` (its defaults filled in): every key is one of -/// its parameters, numbers are in range, flags are true or false, and `surface`, `shadingColor` and -/// `shadingCustom` name a surface, a shading color and a #rrggbb color. +/// its parameters, numbers are in range, flags are true or false, `surface`, `shadingColor` and +/// `shadingCustom` name a surface, a shading color and a #rrggbb color, and `mapArt` holds valid +/// maps. pub fn validate(p: &Value) -> Result<(), String> { - validate_classic(CLASSIC_EXTRUDE, p, &RANGES, &FLAGS) + validate_classic(CLASSIC_EXTRUDE, p, &RANGES, &FLAGS)?; + map_art::validate(CLASSIC_EXTRUDE, p) } /// Rotate (Classic)'s numeric parameters: (key, lowest, highest, whole numbers only). @@ -261,66 +275,67 @@ pub(crate) fn stroke_width(face: &Facet, p: &Value) -> f64 { /// is shaded opaque and then masked by its own transparency, so the shading follows the gradient's /// coverage; without a placement of its own, it is placed once on all the faces /// ([`crate::lighting::opaque_surface_paint`]). -pub(crate) fn surface(n: &Node, facets: Vec, source: &Paint, opacity: f32, blend: BlendMode, p: &Value) -> Node { +/// +/// With `mapped`, a face that carries mapped art is a group of the face and that art, which the +/// surface's opacity mask covers too. Shade Artwork gives the art its face's tone and highlight, +/// and Invisible Geometry leaves the faces out: a face is then a group of its art alone. Wireframe +/// draws no mapped art. Without `mapped`, `hide` leaves the faces out the same way, for a solid +/// that shares Invisible Geometry with another solid's mapped art; Wireframe still draws. +/// +/// Returns the group, whether its faces were left out, and whether `mapped` art was left out past +/// the limits. +pub(crate) fn surface( + n: &Node, + facets: &[Facet], + source: &Paint, + (opacity, blend): (f32, BlendMode), + p: &Value, + mapped: Option>, + hide: bool, +) -> (Node, bool, bool) { let shading = classic_shading(p); let lights = lights(p); let shade = shading_color(p); let preserve = preserves_spot_colors(p); let overprint = black_overprint(p); let wire = shading.surface == ClassicSurface::Wireframe; - let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_surface_paint(source, || super::facets_bounds(&facets)) }; + let (paint, mask) = if wire { (source.clone(), None) } else { crate::lighting::opaque_surface_paint(source, || super::facets_bounds(facets)) }; let paint = &paint; + // The mapped art of each facet, and whether the faces themselves are left out. Art past the + // limits is left out, and the faces draw; the copies and the points of art left out do not + // count against the art of later solids. + let (mut parts, invisible, dropped) = match mapped.filter(|_| !wire) { + Some(m) => { + let shaded_as = |f: &Facet, c: Color| { + let (tone, spec) = shading.tone(f.normal, &lights); + shaded(c, tone, spec, shade) + }; + let (mut used, mut budget) = (*m.copies, m.budget.clone()); + match m.art.parts(n.id, facets, m.layout, &shaded_as, &mut budget, &mut used) { + Some(parts) => { + (*m.copies, *m.budget) = (used, budget); + (parts, m.art.invisible, false) + } + None => (vec![], false, true), + } + } + None => (vec![], hide && !wire, false), + }; let children = facets - .into_iter() - .map(|face| { + .iter() + .enumerate() + .map(|(k, face)| { + let art = parts.get_mut(k).map(std::mem::take).unwrap_or_default(); + if !art.is_empty() || invisible { + let drawn = (!invisible).then(|| Arc::new(shaded_face(n, face, paint, &shading, &lights, shade, preserve, overprint))); + return Arc::new(Node::group(n.id, drawn.into_iter().chain(art).collect())); + } if wire { // A wire edge is drawn as a seam is: a round-joined stroke of the paint. let edge = crate::lighting::seam_stroke(paint.clone(), WIRE); return Arc::new(Node::path(n.id, face.path(), Appearance { items: vec![AppearanceItem::Stroke(edge)], ..Default::default() })); } - let (tone, spec) = shading.tone(face.normal, &lights); - // A narrow stroke of the face's own paint closes the hairline seams between faces. - let seam = super::seam_width(&face); - if overprint { - let items = overprinted_face(paint, tone, seam); - return Arc::new(Node::path(n.id, face.path(), Appearance { items, ..Default::default() })); - } - let items = match paint.color() { - // Unshaded (No Shading, no shading color, or a face in full light) with no - // highlight: the paint itself, its color space and swatch kept. - Some(_) if (tone >= 1.0 || shade.is_none()) && spec <= 0.0 => { - vec![ - AppearanceItem::Fill(FillLayer::new(paint.clone())), - AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam)), - ] - } - // Preserve Spot Colors: a color linked to a swatch stays a tint of that swatch. - Some(_) if preserve && matches!(paint, Paint::Solid { swatch: Some(_), .. }) && !paint.is_registration() => { - linked_face(paint, tone, spec, shade, seam) - } - Some(c) => { - let fill = Paint::solid(shaded(c, tone, spec, shade)); - vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))] - } - // Gradients and patterns keep their paint, darkened by a layer of the shading color - // and lightened by one of white. As with the other 3D effects' pattern shadow, the - // layers cover the whole face, transparent pattern cells included. - None => { - let mut items = vec![ - AppearanceItem::Fill(FillLayer::new(paint.clone())), - AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam)), - ]; - for (color, share) in [(shade, 1.0 - tone), (Some(Color::WHITE), spec)] { - if let Some(color) = color.filter(|_| share > 0.0) { - let mut layer = FillLayer::new(Paint::solid(color)); - layer.opacity = share as f32; - items.push(AppearanceItem::Fill(layer)); - } - } - items - } - }; - Arc::new(Node::path(n.id, face.path(), Appearance { items, ..Default::default() })) + Arc::new(shaded_face(n, face, paint, &shading, &lights, shade, preserve, overprint)) }) .collect(); let mut group = Node::group(n.id, children); @@ -331,5 +346,61 @@ pub(crate) fn surface(n: &Node, facets: Vec, source: &Paint, opacity: f32 let coverage = Node::path(n.id, vectorcraft_geom::shapes::rectangle(bounds), Appearance::basic(mask, Paint::None, 0.0)); group.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(coverage, true))); } - group + (group, invisible, dropped) +} + +/// One face of a solid in paint `paint` (opaque: [`surface`] masks a gradient's transparency), +/// filled in the paint shaded by the face's tone and highlight under `lights`, toward shading +/// color `shade`. With `preserve` (Preserve Spot Colors), a color linked to a swatch is drawn as +/// [`linked_face`] draws it. With `overprint` (Black Overprint), the face is drawn as +/// [`overprinted_face`] draws it. +#[allow(clippy::too_many_arguments)] +fn shaded_face( + n: &Node, + face: &Facet, + paint: &Paint, + shading: &ClassicShading, + lights: &[([f64; 3], f64)], + shade: Option, + preserve: bool, + overprint: bool, +) -> Node { + let (tone, spec) = shading.tone(face.normal, lights); + // A narrow stroke of the face's own paint closes the hairline seams between faces. + let seam = super::seam_width(face); + if overprint { + let items = overprinted_face(paint, tone, seam); + return Node::path(n.id, face.path(), Appearance { items, ..Default::default() }); + } + let items = match paint.color() { + // Unshaded (No Shading, no shading color, or a face in full light) with no + // highlight: the paint itself, its color space and swatch kept. + Some(_) if (tone >= 1.0 || shade.is_none()) && spec <= 0.0 => { + vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam))] + } + // Preserve Spot Colors: a color linked to a swatch stays a tint of that swatch. + Some(_) if preserve && matches!(paint, Paint::Solid { swatch: Some(_), .. }) && !paint.is_registration() => { + linked_face(paint, tone, spec, shade, seam) + } + Some(c) => { + let fill = Paint::solid(shaded(c, tone, spec, shade)); + vec![AppearanceItem::Fill(FillLayer::new(fill.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(fill, seam))] + } + // Gradients and patterns keep their paint, darkened by a layer of the shading color + // and lightened by one of white. As with the other 3D effects' pattern shadow, the + // layers cover the whole face, transparent pattern cells included. + None => { + let mut items = + vec![AppearanceItem::Fill(FillLayer::new(paint.clone())), AppearanceItem::Stroke(crate::lighting::seam_stroke(paint.clone(), seam))]; + for (color, share) in [(shade, 1.0 - tone), (Some(Color::WHITE), spec)] { + if let Some(color) = color.filter(|_| share > 0.0) { + let mut layer = FillLayer::new(Paint::solid(color)); + layer.opacity = share as f32; + items.push(AppearanceItem::Fill(layer)); + } + } + items + } + }; + Node::path(n.id, face.path(), Appearance { items, ..Default::default() }) } diff --git a/crates/effects/src/solids/graphics.rs b/crates/effects/src/solids/graphics.rs index 687d534c2f..302180fdbc 100644 --- a/crates/effects/src/solids/graphics.rs +++ b/crates/effects/src/solids/graphics.rs @@ -177,6 +177,8 @@ pub fn mapped_graphics(p: &Value) -> Vec { /// Revolve and Inflate take graphics; a plane has only a front, and Revolve's graphics go on its /// side, named the front. Only Extrude & Bevel takes graphics on its side. pub fn validate(id: &str, p: &Value) -> Result<(), String> { + // Map Art's maps are checked with the graphics: an effect that takes none refuses them. + map_art::validate(id, p)?; let list = match p.get(GRAPHICS) { None => return Ok(()), Some(Value::Array(list)) => list, @@ -210,21 +212,23 @@ pub fn validate(id: &str, p: &Value) -> Result<(), String> { /// graphics in `old` (the effect's parameters before an edit) already name: a graphic whose symbol /// was deleted may stay. pub fn missing_symbol(doc: &Document, p: &Value, old: Option<&Value>) -> Option { - let kept = old.map(mapped_graphics).unwrap_or_default(); - mapped_graphics(p) - .into_iter() - .map(|g| g.symbol) - .find(|name| !doc.symbols.iter().any(|s| s.name == *name) && !kept.iter().any(|g| g.symbol == *name)) + let names = |p: &Value| -> Vec { + mapped_graphics(p).into_iter().map(|g| g.symbol).chain(map_art::surface_maps(p).into_iter().map(|m| m.symbol)).collect() + }; + let kept = old.map(names).unwrap_or_default(); + names(p).into_iter().find(|name| !doc.symbols.iter().any(|s| s.name == *name) && !kept.contains(name)) } /// Does the art of the symbols the graphics in `p` name fit the limits? A graphic whose symbol /// `doc` does not have draws nothing and is not counted. With a perspective, each curve counts as -/// the [`PERSPECTIVE_PIECES`] pieces it is cut into; without one, it counts once. +/// the [`PERSPECTIVE_PIECES`] pieces it is cut into; without one, it counts once. The symbols Map +/// Art places count with the graphics. pub fn validate_symbols(doc: &Document, p: &Value) -> Result<(), String> { let curve = if super::view_options(p).perspective > 0.0 { PERSPECTIVE_PIECES } else { 1 }; let mut elements = 0usize; - for g in mapped_graphics(p) { - let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue }; + let names = mapped_graphics(p).into_iter().map(|g| g.symbol).chain(map_art::surface_maps(p).into_iter().map(|m| m.symbol)); + for name in names { + let Some(symbol) = doc.symbols.iter().find(|s| s.name == name) else { continue }; let pieces = pieces_of(doc, symbol)?; elements = elements.saturating_add(pieces.iter().map(|p| drawn_elements(&p.path, curve)).sum()); if elements > MAX_ELEMENTS { @@ -234,6 +238,30 @@ pub fn validate_symbols(doc: &Document, p: &Value) -> Result<(), String> { Ok(()) } +/// Does the art Map Art in `p` places on the surfaces that `unrolled` gives a flat center for (by +/// number, from 1; [`map_art::flat_center`]), with the symbols of `doc`, fit the limits as a wall, a +/// bevel or Revolve's side draws it: each map's art placed about that center at its scale, cut into +/// straight pieces, at most [`MAX_ELEMENTS`] points together and within reach? A map whose symbol +/// `doc` does not have is not counted. +pub fn validate_unrolled_symbols(doc: &Document, p: &Value, unrolled: &dyn Fn(usize) -> Option) -> Result<(), String> { + const TOO_COMPLEX: &str = "The graphics are too complex: simplify the symbols' art"; + let mut points = 0usize; + for m in map_art::surface_maps(p) { + let Some(center) = unrolled(m.surface) else { continue }; + let Some(symbol) = doc.symbols.iter().find(|s| s.name == m.symbol) else { continue }; + let pieces = pieces_of(doc, symbol)?; + let Some(bounds) = pieces.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue }; + let place = m.placement(bounds, center, false); + for piece in &pieces { + straight_pieces(&(place * piece.path.to_bezpath()), &mut points).ok_or(TOO_COMPLEX)?; + } + if points > MAX_ELEMENTS { + return Err(TOO_COMPLEX.into()); + } + } + Ok(()) +} + /// The path elements `path` draws when each curve draws `curve` elements, before curves near the /// eye are split further: one for each straight line, move and close. fn drawn_elements(path: &PathData, curve: usize) -> usize { @@ -886,7 +914,12 @@ pub(crate) fn surface_parts( for k in near { let Some(piece) = pieces.get(k) else { continue }; let mut path = BezPath::new(); - // Each contour is cut only where its own bounds reach the triangle. + // Each contour is cut only where its own bounds reach the triangle. Each bounds test + // counts as one point cut, whether or not the contour reaches it. + cut_points = cut_points.saturating_add(piece.boxes.len()); + if cut_points > MAX_SURFACE_CUTS { + return None; + } for (polygon, b) in piece.polygons.iter().zip(&piece.boxes) { if b.x1 < reach.x0 || b.x0 > reach.x1 || b.y1 < reach.y0 || b.y0 > reach.y1 { continue; @@ -1411,9 +1444,11 @@ pub fn appearance_graphic_symbols(appearance: &Appearance) -> Vec { std::iter::once(&appearance.effects) .chain(appearance.items.iter().map(AppearanceItem::effects)) .flatten() - .filter(|e| takes_graphics(&e.id)) - .flat_map(|e| mapped_graphics(&e.params)) - .map(|g| g.symbol) + .filter(|e| takes_graphics(&e.id) || map_art::takes_map_art(&e.id)) + .flat_map(|e| { + let graphics = mapped_graphics(&e.params).into_iter().map(|g| g.symbol).filter(|_| takes_graphics(&e.id)); + graphics.chain(map_art::surface_maps(&e.params).into_iter().map(|m| m.symbol).filter(|_| map_art::takes_map_art(&e.id))) + }) .collect() } @@ -1433,8 +1468,15 @@ pub fn rename_appearance_graphic_symbol(appearance: &mut Appearance, from: &str, let (effects, items) = (&mut appearance.effects, &mut appearance.items); lists.push(effects); lists.extend(items.iter_mut().map(AppearanceItem::effects_mut)); - for e in lists.into_iter().flatten().filter(|e| takes_graphics(&e.id)) { - if let Some(Value::Array(list)) = e.params.get_mut(GRAPHICS) { + for e in lists.into_iter().flatten() { + let key = if takes_graphics(&e.id) { + GRAPHICS + } else if map_art::takes_map_art(&e.id) { + map_art::MAP_ART + } else { + continue; + }; + if let Some(Value::Array(list)) = e.params.get_mut(key) { for g in list.iter_mut() { if g.get("symbol").and_then(Value::as_str) == Some(from) { g["symbol"] = json!(to); @@ -1480,6 +1522,9 @@ pub fn with_graphic(p: &Value, g: &MappedGraphic) -> Value { Value::Object(out) } +#[path = "map_art.rs"] +pub(crate) mod map_art; + #[cfg(test)] #[path = "tests_graphics.rs"] mod tests; diff --git a/crates/effects/src/solids/map_art.rs b/crates/effects/src/solids/map_art.rs new file mode 100644 index 0000000000..3e395a6d03 --- /dev/null +++ b/crates/effects/src/solids/map_art.rs @@ -0,0 +1,781 @@ +//! Map Art: the art of a document symbol mapped onto the numbered surfaces of Extrude & Bevel +//! (Classic) and Revolve (Classic). +//! +//! The effect keeps its maps in its `mapArt` parameter, each `{surface, symbol, x, y, scaleX, +//! scaleY, rotation}`: the surface's number (from 1), the symbol's name, the offset of the art's +//! center from the center of the surface laid out flat (points, x to the right and y down as the +//! surface is seen from outside the solid), its size as a share of the symbol's own, and its turn +//! (degrees, counterclockwise). `mapShade` shades the mapped art with its surface, and +//! `mapInvisible` draws the mapped art without the solid's faces. +//! +//! The surfaces of Extrude & Bevel (Classic) are numbered through its solids in the order they are +//! built, each solid's as [`vectorcraft_three_d::extrude_surfaces`] lists them. Revolve (Classic) +//! has one surface, its swept side (in a group, the side of the member with the longest profile). +//! A map whose number is past the object's surfaces draws nothing. + +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::color::{Color, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect}; +use vectorcraft_three_d::{Extrude, FaceMap, Facet, MapCell, PlanarFace, SolidSurface, SurfaceKind, View}; + +use super::{ + MAX_ELEMENTS, MAX_SURFACE_CUTS, MAX_SURFACE_POINTS, NotMapped, SURFACE_SEAM, SURFACE_TOLERANCE, Unrolled, counterclockwise, map_path, pieces_of, + straight_pieces, takes_seam, triangle_map, +}; + +/// The effect parameter that holds the maps. +pub const MAP_ART: &str = "mapArt"; + +/// The effect parameter of Shade Artwork. +pub const MAP_SHADE: &str = "mapShade"; + +/// The effect parameter of Invisible Geometry. +pub const MAP_INVISIBLE: &str = "mapInvisible"; + +/// The most surfaces of one 3D effect that carry a map. +pub const MAX_MAPS: usize = 64; + +/// The highest surface number a map may name. +pub const MAX_MAP_SURFACE: usize = 100_000; + +/// The error for maps on a 3D effect that takes none. +pub const MAP_ART_NOT_TAKEN: &str = "Map Art maps symbols onto Extrude & Bevel (Classic) and Revolve (Classic)"; + +/// The symbol mapped onto one numbered surface of a 3D object. +#[derive(Clone, Debug, PartialEq)] +pub struct SurfaceMap { + /// The surface's number, from 1. + pub surface: usize, + pub symbol: String, + pub x: f64, + pub y: f64, + /// Percent of the symbol's own width. + pub scale_x: f64, + /// Percent of the symbol's own height. + pub scale_y: f64, + /// Degrees, counterclockwise. + pub rotation: f64, +} + +impl SurfaceMap { + pub fn to_value(&self) -> Value { + json!({ + "surface": self.surface, + "symbol": self.symbol, + "x": self.x, + "y": self.y, + "scaleX": self.scale_x, + "scaleY": self.scale_y, + "rotation": self.rotation, + }) + } + + /// The map `v` describes. `surface` and `symbol` are required: the offsets and the rotation + /// default to 0 and the scales to 100. + pub fn from_value(v: &Value) -> Result { + let Value::Object(m) = v else { return Err(format!("each of `{MAP_ART}` must be an object")) }; + if let Some(k) = m.keys().find(|k| !matches!(k.as_str(), "surface" | "symbol" | "x" | "y" | "scaleX" | "scaleY" | "rotation")) { + return Err(format!("`{MAP_ART}` entries take surface, symbol, x, y, scaleX, scaleY and rotation, not `{k}`")); + } + let surface = m + .get("surface") + .and_then(Value::as_u64) + .and_then(|n| usize::try_from(n).ok()) + .filter(|n| (1..=MAX_MAP_SURFACE).contains(n)) + .ok_or_else(|| format!("each of `{MAP_ART}` needs `surface`, a whole number from 1 to {MAX_MAP_SURFACE}"))?; + let symbol = match m.get("symbol") { + Some(Value::String(s)) if !s.trim().is_empty() => s.clone(), + _ => return Err(format!("each of `{MAP_ART}` needs `symbol`, the name of a symbol")), + }; + let number = |key: &str, default: f64, (lo, hi): (f64, f64)| -> Result { + match m.get(key) { + None => Ok(default), + Some(v) => v + .as_f64() + .filter(|n| n.is_finite() && (lo..=hi).contains(n)) + .ok_or_else(|| format!("`{MAP_ART}` {key} must be a number from {lo} to {hi}")), + } + }; + Ok(Self { + surface, + symbol, + x: number("x", 0.0, (-super::MAX_OFFSET, super::MAX_OFFSET))?, + y: number("y", 0.0, (-super::MAX_OFFSET, super::MAX_OFFSET))?, + scale_x: number("scaleX", 100.0, super::SCALE_RANGE)?, + scale_y: number("scaleY", 100.0, super::SCALE_RANGE)?, + rotation: number("rotation", 0.0, (-360.0, 360.0))?, + }) + } + + /// Where the symbol's art goes on the flat surface, for art whose bounds are `art` on a + /// surface with center `center`. With `mirrored` (the back cap) x runs to the right as the + /// surface is seen from behind the solid. + pub fn placement(&self, art: Rect, center: Point, mirrored: bool) -> Affine { + let place = Affine::translate((center.x + self.x, center.y + self.y)) + * Affine::rotate(-self.rotation.to_radians()) + * Affine::scale_non_uniform(self.scale_x / 100.0, self.scale_y / 100.0) + * Affine::translate(-art.center().to_vec2()); + if mirrored { + Affine::translate(center.to_vec2()) * Affine::scale_non_uniform(-1.0, 1.0) * Affine::translate(-center.to_vec2()) * place + } else { + place + } + } + + /// The scales (percent) at which art with bounds `art`, turned by the map's rotation, fills a + /// surface `width` by `height` points: Scale to Fit. `None` for art or a surface with no area. + pub fn fitting_scales(&self, art: Rect, (width, height): (f64, f64)) -> Option<(f64, f64)> { + let (w, h) = (art.width(), art.height()); + if w <= 0.0 || h <= 0.0 || width <= 0.0 || height <= 0.0 { + return None; + } + // The box of the art turned by the rotation, at its own size. + let (sin, cos) = self.rotation.to_radians().sin_cos(); + let (bw, bh) = (w * cos.abs() + h * sin.abs(), w * sin.abs() + h * cos.abs()); + let clamp = |v: f64| v.clamp(super::SCALE_RANGE.0, super::SCALE_RANGE.1); + if sin.abs() < 1e-9 || cos.abs() < 1e-9 { + // Square to the surface, each side takes its own scale. + let (sx, sy) = if cos.abs() >= 0.5 { (width / w, height / h) } else { (height / w, width / h) }; + return Some((clamp(sx * 100.0), clamp(sy * 100.0))); + } + let fit = (width / bw).min(height / bh); + Some((clamp(fit * 100.0), clamp(fit * 100.0))) + } +} + +/// The 3D effects that take Map Art: Extrude & Bevel (Classic) and Revolve (Classic). +pub fn takes_map_art(id: &str) -> bool { + id == super::super::CLASSIC_EXTRUDE || id == crate::CLASSIC_REVOLVE +} + +/// The maps in parameters `p`, leaving out entries that are not valid and, of two maps of one +/// surface, the later one (a file may hold anything; commands check every entry with +/// [`validate`]). +pub fn surface_maps(p: &Value) -> Vec { + let Some(Value::Array(list)) = p.get(MAP_ART) else { return vec![] }; + let mut seen = HashSet::new(); + list.iter().filter_map(|v| SurfaceMap::from_value(v).ok()).filter(|m| seen.insert(m.surface)).take(MAX_MAPS).collect() +} + +/// Are the maps in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel (Classic) and +/// Revolve (Classic) take maps, at most [`MAX_MAPS`] of them, one for a surface. +pub fn validate(id: &str, p: &Value) -> Result<(), String> { + let list = match p.get(MAP_ART) { + None => return Ok(()), + Some(Value::Array(list)) => list, + Some(_) => return Err(format!("`{MAP_ART}` must be an array")), + }; + if list.is_empty() { + return Ok(()); + } + if !takes_map_art(id) { + return Err(MAP_ART_NOT_TAKEN.into()); + } + if list.len() > MAX_MAPS { + return Err(format!("`{MAP_ART}` takes at most {MAX_MAPS} maps")); + } + let mut seen = HashSet::new(); + for v in list { + let m = SurfaceMap::from_value(v)?; + if !seen.insert(m.surface) { + return Err(format!("`{MAP_ART}` maps surface {} more than once", m.surface)); + } + } + Ok(()) +} + +/// `p` with the map of surface `surface` replaced by `map`, or removed with `None`. The maps stay +/// in the order of their surfaces. +pub fn with_surface_map(p: &Value, surface: usize, map: Option<&SurfaceMap>) -> Value { + let mut maps: Vec = surface_maps(p).into_iter().filter(|m| m.surface != surface).collect(); + maps.extend(map.cloned()); + maps.sort_by_key(|m| m.surface); + let mut out = p.as_object().cloned().unwrap_or_else(Map::new); + out.insert(MAP_ART.into(), Value::Array(maps.iter().map(SurfaceMap::to_value).collect())); + Value::Object(out) +} + +/// One solid's place among its object's numbered surfaces: the index of its first surface, its +/// surfaces, and for a solid with planar ends the bounds, options and view it was built with. +pub(crate) struct SolidLayout { + pub(crate) first: usize, + pub(crate) surfaces: Vec, + pub(crate) ends: Option<(Rect, Extrude, View)>, +} + +/// What the mapped art of one object has drawn so far, against the limits its maps share. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct MapBudget { + elements: usize, + /// The points of the maps' symbols cut into straight pieces, against [`MAX_ELEMENTS`]. + input: usize, + /// The points the maps' art draws on the faces, against [`MAX_SURFACE_POINTS`]. + points: usize, + cuts: usize, +} + +/// The maps of one 3D effect, with the document whose symbols they place. +pub(crate) struct MapArt<'a> { + doc: &'a Document, + maps: Vec, + /// Shade Artwork: the mapped art takes the shading of its surface. + pub(crate) shade: bool, + /// Invisible Geometry: only the mapped art is drawn. + pub(crate) invisible: bool, +} + +impl<'a> MapArt<'a> { + /// The maps of 3D effect `id` with parameters `p`. `None` without a document, for an effect + /// that takes no maps and for one that has none. + pub(crate) fn of(doc: Option<&'a Document>, id: &str, p: &Value) -> Option { + let maps = surface_maps(p); + let flag = |key: &str| p.get(key).and_then(Value::as_bool).unwrap_or(false); + (takes_map_art(id) && !maps.is_empty()).then_some(Self { doc: doc?, maps, shade: flag(MAP_SHADE), invisible: flag(MAP_INVISIBLE) }) + } + + fn map_of(&self, index: usize) -> Option<&SurfaceMap> { + self.maps.iter().find(|m| m.surface == index + 1) + } + + /// The mapped art that falls on each of `facets`, one solid's facets in drawing order, for an + /// object with id `id`: for each facet, the nodes to draw right after it. Only facets turned + /// toward the viewer carry art. `shade` gives a color as its facet shades it, for Shade + /// Artwork. A map whose symbol the document does not have, or whose art is past the limits of + /// a graphic's art, draws nothing. `None` when the art is past the limits the maps of one + /// object share, or the copies of its paints take `copies` past the object's allowance: the + /// solid then draws without mapped art. + pub(crate) fn parts( + &self, + id: NodeId, + facets: &[Facet], + layout: &SolidLayout, + shade: &dyn Fn(&Facet, Color) -> Color, + budget: &mut MapBudget, + copies: &mut usize, + ) -> Option>>> { + let mut out: Vec>> = vec![vec![]; facets.len()]; + let mut flat: HashMap> = HashMap::new(); + for (f, parts) in facets.iter().zip(out.iter_mut()) { + if f.away { + continue; + } + let recolor = |c: Color| if self.shade { shade(f, c) } else { c }; + if let Some(end) = f.end { + let Some(local) = layout.surfaces.iter().position(|s| s.kind == SurfaceKind::End(end)) else { continue }; + let (Some(m), Some(center)) = (self.map_of(layout.first + local), layout.surfaces.get(local).and_then(|s| s.center)) else { + continue; + }; + let Some((bounds, options, view)) = layout.ends else { continue }; + let Some(map) = vectorcraft_three_d::extrude_face_map(bounds, options, view, end) else { continue }; + parts.extend(self.end_art(id, m, (end, &map), center, f, &recolor, budget, copies)?); + } else if let Some(cell) = f.cell.as_deref() { + let (Some(m), Some(surface)) = (self.map_of(layout.first + cell.surface), layout.surfaces.get(cell.surface)) else { continue }; + if let std::collections::hash_map::Entry::Vacant(e) = flat.entry(cell.surface) { + e.insert(self.unrolled(m, surface, budget)?); + } + let Some(pieces) = flat.get(&cell.surface) else { continue }; + parts.extend(cell_art(id, pieces, cell, f, &recolor, budget, copies)?); + } + } + Some(out) + } + + /// The art of map `m` on planar end `end` of a solid, drawn on its facet `f` through `map`, + /// for an end whose bounds have center `center`: one clipping group, as a graphic on a cap is + /// drawn. `None` past the limits. + #[allow(clippy::too_many_arguments)] + fn end_art( + &self, + id: NodeId, + m: &SurfaceMap, + (end, map): (PlanarFace, &FaceMap), + center: Point, + f: &Facet, + recolor: &dyn Fn(Color) -> Color, + budget: &mut MapBudget, + copies: &mut usize, + ) -> Option>> { + let Some(symbol) = self.doc.symbols.iter().find(|s| s.name == m.symbol) else { return Some(vec![]) }; + let Ok(pieces) = pieces_of(self.doc, symbol) else { return Some(vec![]) }; + let Some(bounds) = pieces.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { return Some(vec![]) }; + let place = m.placement(bounds, center, end == PlanarFace::Back); + let affine = map.local_affine(center).filter(|_| map.is_affine()); + // Gradients follow the end's map as it is near the art's center, or near the middle of the + // part in front of the eye when the center is not. + let local = map.local_affine(place * bounds.center()).or_else(|| { + let part = map.mapped_part(place.transform_rect_bbox(bounds))?; + let sum = part.iter().fold(Point::ZERO, |s, p| s + p.to_vec2()); + map.local_affine(Point::new(sum.x / part.len() as f64, sum.y / part.len() as f64)) + }); + let Some(local) = local else { return Some(vec![]) }; + let gradient_map = local * place; + let mut children = vec![]; + for piece in pieces { + let placed = piece.path.transformed(place); + let least: usize = placed.subpaths.iter().map(|s| s.anchors.len()).sum(); + let before = budget.elements; + if before.saturating_add(least) > MAX_ELEMENTS { + return None; + } + let room = MAX_ELEMENTS - before; + let mut rule = piece.rule; + let mapped = match map_path(&placed, map, affine, room) { + Err(NotMapped::Behind) => { + // Part of it is at or behind the eye: the part in front is drawn. + let Some(part) = placed.bounds().and_then(|b| map.mapped_part(b)) else { continue }; + let Some(&first) = part.first() else { continue }; + let mut front = BezPath::new(); + front.move_to(first); + part.iter().skip(1).for_each(|p| front.line_to(*p)); + front.close_path(); + let cut = vectorcraft_pathops::boolean( + &placed, + piece.rule, + &PathData::from_bezpath(&front), + FillRule::NonZero, + vectorcraft_pathops::BoolOp::Intersect, + ); + rule = FillRule::NonZero; + map_path(&cut, map, affine, room) + } + done => done, + }; + let mapped = match mapped { + Ok(mapped) => mapped, + Err(NotMapped::Full) => return None, + Err(NotMapped::Behind) => continue, + }; + budget.elements = before.saturating_add(mapped.elements().len()); + if !crate::revolve::paint_copies_add(copies, 1, &piece.paint) { + return None; + } + children.push(Arc::new(piece_node(id, piece.paint, (piece.opacity, piece.blend), (mapped, rule), gradient_map, recolor, None))); + } + if children.is_empty() { + return Some(vec![]); + } + // An end's holes are contours of the same path wound against its outline, so turning the + // whole path keeps them holes under the nonzero rule. + let mut outline = f.path().to_bezpath(); + if vectorcraft_geom::kurbo::Shape::area(&outline) < 0.0 { + outline = outline.reverse_subpaths(); + } + let clip = Node::path(id, PathData::from_bezpath(&outline), Appearance::default()); + Some(vec![Arc::new(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, children))], clip: true }))]) + } + + /// The areas of map `m`'s symbol placed on `surface` laid out flat, cut into straight pieces. + /// Empty for a symbol the document does not have or whose art is past the limits of a + /// graphic's art. `None` when the pieces of the object's maps take more than + /// [`MAX_ELEMENTS`] points together. + fn unrolled(&self, m: &SurfaceMap, surface: &SolidSurface, budget: &mut MapBudget) -> Option> { + let Some(symbol) = self.doc.symbols.iter().find(|s| s.name == m.symbol) else { return Some(vec![]) }; + let Ok(art) = pieces_of(self.doc, symbol) else { return Some(vec![]) }; + let Some(bounds) = art.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { return Some(vec![]) }; + let place = m.placement(bounds, flat_center(surface), false); + let mut pieces = vec![]; + for piece in art { + let placed = place * piece.path.to_bezpath(); + let mut polygons = straight_pieces(&placed, &mut budget.input)?; + polygons.retain(|p| p.len() >= 3 && p.iter().all(|q| q.is_finite())); + let boxes: Vec = polygons.iter().filter_map(|polygon| box_of(polygon)).collect(); + let Some(bounds) = boxes.iter().copied().reduce(|a, b| a.union(b)) else { continue }; + pieces.push(Unrolled { + polygons, + boxes, + bounds, + rule: piece.rule, + paint: piece.paint, + opacity: piece.opacity, + blend: piece.blend, + place, + }); + } + Some(pieces) + } +} + +/// The center of `surface` laid out flat, which a map's offset is measured from: the middle of a +/// wall or a bevel, whose flat coordinates start at its corner, and the origin of Revolve's side, +/// whose flat coordinates start at its middle. +pub fn flat_center(surface: &SolidSurface) -> Point { + match surface.kind { + SurfaceKind::Side => Point::ZERO, + SurfaceKind::End(_) => surface.center.unwrap_or(Point::ZERO), + SurfaceKind::Wall | SurfaceKind::Bevel => Point::new(surface.width / 2.0, surface.height / 2.0), + } +} + +fn box_of(points: &[Point]) -> Option { + points.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) +} + +/// A map from a region of a flat surface onto the page. +enum Mapper { + Affine(Affine), + /// The projective map that takes the rectangle with corner `origin` and size `size` onto a + /// quadrilateral: `rows` are its coefficients on the unit square. + Quad { + origin: Point, + size: (f64, f64), + rows: [f64; 8], + }, +} + +impl Mapper { + fn at(&self, p: Point) -> Point { + match self { + Mapper::Affine(a) => *a * p, + Mapper::Quad { origin, size, rows: [a, b, c, d, e, f, g, h] } => { + let (u, v) = ((p.x - origin.x) / size.0, (p.y - origin.y) / size.1); + let w = g * u + h * v + 1.0; + Point::new((a * u + b * v + c) / w, (d * u + e * v + f) / w) + } + } + } + + /// The point of the flat surface this map takes to `p` on the page. `None` where there is none. + fn back(&self, p: Point) -> Option { + let q = match self { + Mapper::Affine(a) => a.inverse() * p, + Mapper::Quad { origin, size, rows: [a, b, c, d, e, f, g, h] } => { + // x (g u + h v + 1) = a u + b v + c, and the same for y, solved for u and v. + let (m00, m01, r0) = (a - g * p.x, b - h * p.x, p.x - c); + let (m10, m11, r1) = (d - g * p.y, e - h * p.y, p.y - f); + let det = m00 * m11 - m01 * m10; + let (u, v) = ((r0 * m11 - m01 * r1) / det, (m00 * r1 - r0 * m10) / det); + Point::new(origin.x + u * size.0, origin.y + v * size.1) + } + }; + q.is_finite().then_some(q) + } + + /// The affine map nearest this one around `p`, for gradients and patterns. + fn local(&self, p: Point, step: f64) -> Affine { + match self { + Mapper::Affine(a) => *a, + Mapper::Quad { .. } => { + let (o, x, y) = (self.at(p), self.at(Point::new(p.x + step, p.y)), self.at(Point::new(p.x, p.y + step))); + let (dx, dy) = ((x - o) / step, (y - o) / step); + Affine::new([dx.x, dx.y, dy.x, dy.y, o.x - dx.x * p.x - dy.x * p.y, o.y - dx.y * p.x - dy.y * p.y]) + } + } + } +} + +/// The projective map of `cell`, a cell whose flat corners are those of an upright rectangle, in +/// order along its edge nearest the origin and back: exact for a flat wall under a perspective. `None` +/// for any other cell and for a quadrilateral the map turns inside out. +fn quad_mapper(cell: &MapCell) -> Option<(Vec, Mapper)> { + let [mut u0, mut u1, mut u2, mut u3] = <[Point; 4]>::try_from(cell.uv.as_slice()).ok()?; + let [mut p0, mut p1, mut p2, mut p3] = <[Point; 4]>::try_from(cell.page.as_slice()).ok()?; + // A cell whose first edge runs from right to left is read from its other end. + if u1.x < u0.x { + (u0, u1, u2, u3) = (u1, u0, u3, u2); + (p0, p1, p2, p3) = (p1, p0, p3, p2); + } + let size = (u1.x - u0.x, u3.y - u0.y); + let upright = u1.y == u0.y && u2.x == u1.x && u2.y == u3.y && u3.x == u0.x && size.0 > 1e-9 && size.1 > 1e-9; + if !upright { + return None; + } + let (dx1, dx2, sx) = (p1.x - p2.x, p3.x - p2.x, p0.x - p1.x + p2.x - p3.x); + let (dy1, dy2, sy) = (p1.y - p2.y, p3.y - p2.y, p0.y - p1.y + p2.y - p3.y); + let den = dx1 * dy2 - dx2 * dy1; + let scale = dx1.abs() + dx2.abs() + dy1.abs() + dy2.abs(); + if den.is_nan() || den.abs() <= 1e-12 * scale * scale { + return None; + } + let (g, h) = ((sx * dy2 - dx2 * sy) / den, (dx1 * sy - sx * dy1) / den); + let rows = [p1.x - p0.x + g * p1.x, p3.x - p0.x + h * p3.x, p0.x, p1.y - p0.y + g * p1.y, p3.y - p0.y + h * p3.y, p0.y, g, h]; + let inside = g + 1.0 > 1e-6 && h + 1.0 > 1e-6 && g + h + 1.0 > 1e-6; + (inside && rows.iter().all(|v| v.is_finite())).then(|| (vec![u0, u1, u2, u3], Mapper::Quad { origin: u0, size, rows })) +} + +/// The regions of `cell` on its flat surface, each a convex polygon wound as [`clip_convex`] reads +/// it, with its map onto the page: the whole of an upright rectangle ([`quad_mapper`]), else the +/// triangles the cell is cut into. +fn regions(cell: &MapCell) -> Vec<(Vec, Mapper)> { + if let Some(quad) = quad_mapper(cell) { + return vec![quad]; + } + let triangles: &[[usize; 3]] = if cell.uv.len() == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] }; + triangles + .iter() + .filter_map(|corners| { + let pick = |of: &[Point]| corners.iter().map(|k| of.get(*k).copied()).collect::>>(); + let (uv, page) = (pick(&cell.uv)?, pick(&cell.page)?); + Some((counterclockwise(&uv)?.to_vec(), Mapper::Affine(triangle_map(&uv, &page)?))) + }) + .collect() +} + +/// The part of `polygon` inside the convex `window` (one step of Sutherland and Hodgman's clip for +/// each of its edges), wound so that its inside is on the positive side of each edge. +fn clip_convex(polygon: &[Point], window: &[Point]) -> Vec { + let mut out = polygon.to_vec(); + for (k, &a) in window.iter().enumerate() { + let Some(&b) = window.get((k + 1) % window.len()) else { continue }; + let side = |p: Point| (b - a).cross(p - a); + let input = std::mem::take(&mut out); + for (i, &p) in input.iter().enumerate() { + let Some(&q) = input.get((i + 1) % input.len()) else { continue }; + let (sp, sq) = (side(p), side(q)); + if sp >= 0.0 { + out.push(p); + } + if (sp >= 0.0) != (sq >= 0.0) { + out.push(p.lerp(q, sp / (sp - sq))); + } + } + if out.len() < 3 { + return vec![]; + } + } + out +} + +/// How far `p` lies outside the convex `polygon`, wound with its inside on the positive side of each +/// edge, across the edges for which `counts` holds: 0 or less when it lies inside them. +fn beyond(polygon: &[Point], p: Point, counts: &dyn Fn(Point, Point) -> bool) -> f64 { + let mut most = f64::NEG_INFINITY; + for (k, &a) in polygon.iter().enumerate() { + let Some(&b) = polygon.get((k + 1) % polygon.len()) else { continue }; + let length = (b - a).hypot(); + if length > 0.0 && counts(a, b) { + most = most.max(-(b - a).cross(p - a) / length); + } + } + most +} + +/// `regions` of `cell` ([`regions`]) with the edges they share with the cell's own outline moved out +/// on the flat surface, far enough that their maps reach the outline of facet `f` where its curved +/// edges bow out of the cell: each outline point is taken back onto the flat surface through the +/// region's own map. The edge between two triangles stays, so the regions do not overlap. A region +/// moves out at most four times the size of the cell, and one whose projective map would turn +/// inside out where it reaches stays as it is. Without a curved outline, or where the outline stays +/// inside the cell, the regions are returned unchanged. +fn reaching_outline(regions: Vec<(Vec, Mapper)>, cell: &MapCell, f: &Facet) -> Vec<(Vec, Mapper)> { + let Some(outline) = f.outline.as_ref() else { return regions }; + let Some(uv) = box_of(&cell.uv) else { return regions }; + // The cell on the page, wound with its inside on the positive side of each edge. + let mut around = cell.page.clone(); + let turn: f64 = around.iter().zip(around.iter().cycle().skip(1)).map(|(a, b)| a.to_vec2().cross(b.to_vec2())).sum(); + if turn < 0.0 { + around.reverse(); + } + // The points of the outline that lie outside the cell on the page, or near enough that the + // curve between them may: the curve strays from its flattened points by up to the tolerance, + // so each point counts as the corners of a square of that half width around it. + let mut out = vec![]; + let outline = outline.to_bezpath(); + let t = SURFACE_TOLERANCE; + vectorcraft_geom::kurbo::flatten(outline.elements().iter().copied(), t, |el| { + if let vectorcraft_geom::kurbo::PathEl::MoveTo(p) | vectorcraft_geom::kurbo::PathEl::LineTo(p) = el + && beyond(&around, p, &|_, _| true) > -2.0 * t + { + out.extend([(t, t), (t, -t), (-t, t), (-t, -t)].map(|(x, y)| p + vectorcraft_geom::Vec2::new(x, y))); + } + }); + if out.is_empty() { + return regions; + } + let most = 4.0 * uv.width().hypot(uv.height()); + let on_outline = |a: Point, b: Point| { + let at = |q: Point| cell.uv.iter().position(|u| *u == q); + let count = cell.uv.len(); + matches!((at(a), at(b)), (Some(i), Some(j)) if (i + 1) % count == j || (j + 1) % count == i) + }; + regions + .into_iter() + .map(|(window, mapper)| { + let reach = out.iter().filter_map(|p| mapper.back(*p)).map(|q| beyond(&window, q, &on_outline)).fold(0.0f64, f64::max); + if reach <= 0.0 { + return (window, mapper); + } + // A little past the farthest point, so the cut to the outline meets it. + let reach = (reach * 1.01 + 1e-9).min(most); + let grown = grown_window(&window, reach, &on_outline); + let holds = match &mapper { + Mapper::Affine(_) => true, + Mapper::Quad { origin, size, rows } => grown.iter().all(|p| { + let (u, v) = ((p.x - origin.x) / size.0, (p.y - origin.y) / size.1); + rows[6] * u + rows[7] * v + 1.0 > 1e-6 + }), + }; + (if holds && grown.len() == window.len() { grown } else { window }, mapper) + }) + .collect() +} + +/// The convex `window`, wound as [`clip_convex`] reads it, with each edge for which `moves` holds +/// moved out by `by`, and its corners where the moved edges meet. +fn grown_window(window: &[Point], by: f64, moves: &dyn Fn(Point, Point) -> bool) -> Vec { + let count = window.len(); + // Each edge as a point on its line and its direction, moved out where it moves. + let lines: Vec<(Point, vectorcraft_geom::Vec2)> = (0..count) + .filter_map(|k| { + let (a, b) = (*window.get(k)?, *window.get((k + 1) % count)?); + let d = b - a; + let length = d.hypot(); + let out = if moves(a, b) && length > 0.0 { vectorcraft_geom::Vec2::new(d.y, -d.x) * (by / length) } else { vectorcraft_geom::Vec2::ZERO }; + Some((a + out, d)) + }) + .collect(); + (0..count) + .filter_map(|k| { + let ((p1, d1), (p2, d2)) = (*lines.get((k + count - 1) % count)?, *lines.get(k)?); + let den = d1.cross(d2); + if den.abs() <= 1e-12 * d1.hypot() * d2.hypot() { + return Some(p2); + } + let t = (p2 - p1).cross(d2) / den; + let p = p1 + d1 * t; + p.is_finite().then_some(p) + }) + .collect() +} + +/// The parts of `pieces`, a map's art on its flat surface, that fall on `cell`, the cell of facet +/// `f`, drawn on the page. `None` past the limits. +fn cell_art( + id: NodeId, + pieces: &[Unrolled], + cell: &MapCell, + f: &Facet, + recolor: &dyn Fn(Color) -> Color, + budget: &mut MapBudget, + copies: &mut usize, +) -> Option>> { + if cell.uv.len() != cell.page.len() || !(3..=4).contains(&cell.uv.len()) { + return Some(vec![]); + } + let Some(reach) = box_of(&cell.uv) else { return Some(vec![]) }; + // A facet cut after it was built, or one whose edges follow the profile's curves, draws only the + // part of the art inside its own outline, which the regions reach where it bows out of the cell. + let whole = f.outline.is_none() && f.contours.first() == Some(&cell.page); + let regions = if whole { regions(cell) } else { reaching_outline(regions(cell), cell, f) }; + let within = regions.iter().filter_map(|(w, _)| box_of(w)).fold(reach, |a, b| a.union(b)); + let apart = |b: &Rect| b.x1 < within.x0 || b.x0 > within.x1 || b.y1 < within.y0 || b.y0 > within.y1; + let mut out = vec![]; + for piece in pieces.iter().filter(|p| !apart(&p.bounds)) { + // Each contour's bounds test counts as one point cut, whether or not the contour reaches + // the cell. + budget.cuts = budget.cuts.saturating_add(piece.boxes.len()); + if budget.cuts > MAX_SURFACE_CUTS { + return None; + } + let near: Vec<&Vec> = piece.polygons.iter().zip(&piece.boxes).filter(|(_, b)| !apart(b)).map(|(p, _)| p).collect(); + let mut path = BezPath::new(); + for (window, mapper) in ®ions { + for polygon in &near { + budget.cuts = budget.cuts.saturating_add(polygon.len()); + if budget.cuts > MAX_SURFACE_CUTS { + return None; + } + let cut = clip_convex(polygon, window); + let Some((first, rest)) = cut.split_first() else { continue }; + path.move_to(mapper.at(*first)); + rest.iter().for_each(|q| path.line_to(mapper.at(*q))); + path.close_path(); + budget.points = budget.points.saturating_add(cut.len()); + } + } + if budget.points > MAX_SURFACE_POINTS { + return None; + } + if path.elements().is_empty() { + continue; + } + let (path, rule) = if whole { + (path, piece.rule) + } else { + let cut = vectorcraft_pathops::boolean( + &PathData::from_bezpath(&path), + piece.rule, + &f.path(), + FillRule::NonZero, + vectorcraft_pathops::BoolOp::Intersect, + ); + (cut.to_bezpath(), FillRule::NonZero) + }; + if path.elements().is_empty() || !path.elements().iter().all(el_is_finite) { + continue; + } + let seam = takes_seam(piece); + if !crate::revolve::paint_copies_add(copies, 1 + usize::from(seam), &piece.paint) { + return None; + } + // Gradients and patterns follow the cell's map as it is at the cell's middle. + let middle = reach.center(); + let local = regions.first().map_or(Affine::IDENTITY, |(_, m)| m.local(middle, (reach.width().max(reach.height()) * 1e-3).max(1e-6))); + let node = piece_node( + id, + piece.paint.clone(), + (piece.opacity, piece.blend), + (path, rule), + local * piece.place, + recolor, + seam.then_some(SURFACE_SEAM), + ); + out.push(Arc::new(node)); + } + Some(out) +} + +fn el_is_finite(el: &vectorcraft_geom::kurbo::PathEl) -> bool { + use vectorcraft_geom::kurbo::PathEl; + match *el { + PathEl::MoveTo(p) | PathEl::LineTo(p) => p.is_finite(), + PathEl::QuadTo(a, p) => a.is_finite() && p.is_finite(), + PathEl::CurveTo(a, b, p) => a.is_finite() && b.is_finite() && p.is_finite(), + PathEl::ClosePath => true, + } +} + +/// One painted area of mapped art on the page: `path` filled under `rule` with `paint`, its +/// gradients and pattern tiles placed through `gradient_map`, its colors through `recolor`, and +/// with `seam` a stroke of that width in the same paint over the seams between neighboring parts. +fn piece_node( + id: NodeId, + mut paint: Paint, + (opacity, blend): (f32, vectorcraft_doc::color::BlendMode), + (path, rule): (BezPath, FillRule), + gradient_map: Affine, + recolor: &dyn Fn(Color) -> Color, + seam: Option, +) -> Node { + if let Paint::Pattern { xf, .. } = &mut paint { + *xf = gradient_map * *xf; + } + let mut fill = FillLayer::new(paint); + fill.opacity = opacity; + fill.blend = blend; + let mut appearance = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() }; + appearance.transform_gradients(gradient_map); + for item in appearance.items.iter_mut() { + if let AppearanceItem::Fill(f) = item { + // Pattern tiles keep their colors: the document's pattern draws them. + vectorcraft_doc::recolor::map_paint(&mut f.paint, recolor); + } + } + if let (Some(width), Some(AppearanceItem::Fill(f))) = (seam, appearance.items.first()) { + let mut stroke = vectorcraft_doc::StrokeLayer::new(f.paint.clone(), width); + stroke.join = vectorcraft_doc::LineJoin::Round; + appearance.items.push(AppearanceItem::Stroke(stroke)); + } + let mut node = Node::path(id, PathData::from_bezpath(&path), appearance); + if let NodeKind::Path { rule: r, .. } = &mut node.kind { + *r = rule; + } + node +} + +#[cfg(test)] +#[path = "tests_map_art.rs"] +mod tests; diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index b61634c844..518870dff2 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -801,6 +801,7 @@ fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() { surface: None, membrane: None, plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }), + cell: 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. diff --git a/crates/effects/src/solids/tests_graphics_side.rs b/crates/effects/src/solids/tests_graphics_side.rs index e5390d3a47..5afdadf30f 100644 --- a/crates/effects/src/solids/tests_graphics_side.rs +++ b/crates/effects/src/solids/tests_graphics_side.rs @@ -187,6 +187,7 @@ fn a_piece_cut_from_a_face_draws_its_own_part() { surface: Some(vectorcraft_three_d::SurfaceCell { page: square, uv, outward: true }), membrane: None, plane: Some(vectorcraft_three_d::DepthPlane { normal, offset, center: Point::ZERO, eye: None }), + cell: None, } }; let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0); diff --git a/crates/effects/src/solids/tests_map_art.rs b/crates/effects/src/solids/tests_map_art.rs new file mode 100644 index 0000000000..9ffb264627 --- /dev/null +++ b/crates/effects/src/solids/tests_map_art.rs @@ -0,0 +1,710 @@ +use serde_json::json; +use vectorcraft_doc::Symbol; +use vectorcraft_geom::shapes; + +use super::super::super::{CLASSIC_EXTRUDE, CLASSIC_ROTATE, MapSurface, map_surfaces_at, solid_art_in, validate_three_d_at_in, validate_three_d_in}; +use super::*; +use crate::CLASSIC_REVOLVE; + +const RED: Color = Color::Rgb { r: 1.0, g: 0.0, b: 0.0 }; +const GREEN: Color = Color::Rgb { r: 0.0, g: 1.0, b: 0.0 }; +const BLUE: Color = Color::Rgb { r: 0.0, g: 0.0, b: 1.0 }; + +fn square(id: u64, r: Rect, c: Color) -> Node { + Node::path(NodeId(id), shapes::rectangle(r), Appearance::basic(Paint::solid(c), Paint::None, 0.0)) +} + +/// A document with symbol "Mark", a red 10 × 10 square, and symbol "Corner", 30 × 30: a red square +/// at its top left, a blue one to the right of it and a green one below it. +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), RED)) }); + let corner = Node::group( + NodeId(0), + vec![ + Arc::new(square(0, Rect::new(0.0, 0.0, 10.0, 10.0), RED)), + Arc::new(square(0, Rect::new(20.0, 0.0, 30.0, 10.0), BLUE)), + Arc::new(square(0, Rect::new(0.0, 20.0, 10.0, 30.0), GREEN)), + ], + ); + d.symbols.push(Symbol { dynamic: false, name: "Corner".into(), art: Arc::new(corner) }); + d +} + +/// A gray 100 × 100 square at (0, 0) with effect `id`, its parameters `params` over a view +/// straight on with No Shading. +fn object(id: &str, params: Value) -> Node { + let mut p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "surface": "none"}); + 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), Color::rgb(0.5, 0.5, 0.5)); + n.appearance.effects.push(crate::new_effect(id, &p).unwrap()); + n +} + +/// The paths of `art` filled with color `c`, in drawing order. +fn filled(art: &Node, c: Color) -> Vec { + let mut out = vec![]; + art.walk(&mut |n| { + let fill = n.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Fill(f) => f.paint.color(), + AppearanceItem::Stroke(_) => None, + }); + if fill.is_some_and(|f| f.to_rgb().iter().zip(c.to_rgb()).all(|(a, b)| (a - b).abs() < 1e-4)) + && let Some(p) = n.path_data() + { + out.push(p.clone()); + } + }); + out +} + +fn bounds_of(paths: &[PathData]) -> Rect { + paths.iter().filter_map(|p| p.bounds()).reduce(|a, b| a.union(b)).unwrap() +} + +fn close(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) +} + +fn surfaces(n: &Node) -> Vec { + map_surfaces_at(Some(&document()), n, None, 0).unwrap() +} + +/// Which way round the "Corner" symbol reads in `art`: positive when its blue square is to the +/// right of its red one and its green one below, as the symbol is drawn, at any turn; negative +/// when it is mirrored. +fn handedness(art: &Node) -> f64 { + let at = |c: Color| bounds_of(&filled(art, c)).center(); + (at(BLUE) - at(RED)).cross(at(GREEN) - at(RED)) +} + +#[test] +fn the_surfaces_are_the_caps_then_each_wall_then_each_bevel() { + let kinds = |n: &Node| surfaces(n).iter().map(|s| s.kind).collect::>(); + let (front, back) = (SurfaceKind::End(PlanarFace::Front), SurfaceKind::End(PlanarFace::Back)); + let solid = object(CLASSIC_EXTRUDE, json!({})); + assert_eq!(kinds(&solid), [vec![front, back], vec![SurfaceKind::Wall; 4]].concat()); + // Each wall runs from corner to corner of the square and is as deep as the solid. + for wall in surfaces(&solid).iter().skip(2) { + assert!((wall.width - 100.0).abs() < 1e-6 && (wall.height - 50.0).abs() < 1e-6, "{wall:?}"); + } + assert_eq!(kinds(&object(CLASSIC_EXTRUDE, json!({"cap": false}))), vec![SurfaceKind::Wall; 4]); + let beveled = object(CLASSIC_EXTRUDE, json!({"bevel": "classic"})); + assert_eq!(kinds(&beveled), [vec![front, back], vec![SurfaceKind::Wall; 4], vec![SurfaceKind::Bevel; 4]].concat()); + // With no depth the art is a plane, which has its front only. + assert_eq!(kinds(&object(CLASSIC_EXTRUDE, json!({"depth": 0}))), vec![front]); + // An outline with no corner has one wall. + let mut round = Node::path(NodeId(7), shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::basic(Paint::solid(RED), Paint::None, 0.0)); + round.appearance.effects.push(crate::new_effect(CLASSIC_EXTRUDE, &json!({})).unwrap()); + assert_eq!(kinds(&round), vec![front, back, SurfaceKind::Wall]); + // Revolve (Classic) has its side, and Rotate (Classic) takes no maps. + assert_eq!(kinds(&object(CLASSIC_REVOLVE, json!({}))), vec![SurfaceKind::Side]); + assert_eq!(map_surfaces_at(Some(&document()), &object(CLASSIC_ROTATE, json!({})), None, 0), None); + // Seen straight on, only the front cap is turned toward the viewer. + let seen: Vec = surfaces(&solid).iter().map(|s| s.visible).collect(); + assert_eq!(seen, [true, false, false, false, false, false]); +} + +#[test] +fn a_bevel_as_deep_as_the_solid_leaves_no_walls_and_its_bevels_take_their_maps() { + let (front, back) = (SurfaceKind::End(PlanarFace::Front), SurfaceKind::End(PlanarFace::Back)); + let solid = |maps: Value| object(CLASSIC_EXTRUDE, json!({"depth": 10, "bevel": "classic", "bevelHeight": 10, "mapArt": maps})); + let kinds: Vec = surfaces(&solid(json!([]))).iter().map(|s| s.kind).collect(); + assert_eq!(kinds, [vec![front, back], vec![SurfaceKind::Bevel; 4]].concat()); + // Seen straight on, the front bevels draw the art mapped onto them. + let bevels: Vec = (3..=6).map(|k| json!({"surface": k, "symbol": "Mark"})).collect(); + let art = solid_art_in(Some(&document()), &solid(json!(bevels))).unwrap(); + assert!(!filled(&art, RED).is_empty()); +} + +#[test] +fn a_map_on_the_front_cap_draws_the_symbol_at_its_offset_scales_and_turn() { + let d = document(); + let map = |m: Value| solid_art_in(Some(&d), &object(CLASSIC_EXTRUDE, json!({"mapArt": [m]}))).unwrap(); + // Without a map nothing red is drawn. + assert!(filled(&solid_art_in(Some(&d), &object(CLASSIC_EXTRUDE, json!({}))).unwrap(), RED).is_empty()); + // The art's center is at the center of the cap, its size the symbol's own. + let centered = filled(&map(json!({"surface": 1, "symbol": "Mark"})), RED); + assert!(close(bounds_of(¢ered), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds_of(¢ered)); + // An offset moves it, and each scale sizes one side. + let moved = filled(&map(json!({"surface": 1, "symbol": "Mark", "x": 10, "y": -5, "scaleX": 200, "scaleY": 300})), RED); + assert!(close(bounds_of(&moved), Rect::new(50.0, 30.0, 70.0, 60.0)), "{:?}", bounds_of(&moved)); + // A quarter turn swaps the sides. + let turned = filled(&map(json!({"surface": 1, "symbol": "Mark", "scaleX": 200, "rotation": 90})), RED); + assert!(close(bounds_of(&turned), Rect::new(45.0, 40.0, 55.0, 60.0)), "{:?}", bounds_of(&turned)); + // The art is clipped to the cap. + let past = filled(&map(json!({"surface": 1, "symbol": "Mark", "x": 50})), RED); + assert_eq!(past.len(), 1); + let art = map(json!({"surface": 1, "symbol": "Mark", "x": 50})); + let mut clipped = false; + art.walk(&mut |n| clipped |= matches!(&n.kind, NodeKind::Group { clip: true, .. })); + assert!(clipped); +} + +#[test] +fn a_map_on_a_side_wall_reads_the_right_way_round_from_outside() { + let d = document(); + let all_walls: Vec = (3..=6).map(|k| json!({"surface": k, "symbol": "Corner"})).collect(); + for turn in [-90.0, 90.0] { + // Seen from one side, one wall faces the viewer: it alone carries its map. + let n = object(CLASSIC_EXTRUDE, json!({"rotationY": turn, "mapArt": all_walls})); + let art = solid_art_in(Some(&d), &n).unwrap(); + assert_eq!(filled(&art, RED).len(), 1, "one wall is seen at {turn}"); + // The wall is 100 along the outline and 50 deep: the art keeps its size at its middle. + let whole = bounds_of(&[filled(&art, RED), filled(&art, BLUE), filled(&art, GREEN)].concat()); + assert!((whole.width() - 30.0).abs() < 1e-6 && (whole.height() - 30.0).abs() < 1e-6, "{whole:?}"); + assert!((whole.center().x - 50.0).abs() < 1e-6 && (whole.center().y - 50.0).abs() < 1e-6, "{whole:?}"); + assert!(handedness(&art) > 0.0, "the art is mirrored at {turn}"); + } + // The walls seen from above and below read the right way round too. + for turn in [-90.0, 90.0] { + let n = object(CLASSIC_EXTRUDE, json!({"rotationX": turn, "mapArt": all_walls})); + assert!(handedness(&solid_art_in(Some(&d), &n).unwrap()) > 0.0, "the art is mirrored at {turn}"); + } +} + +#[test] +fn a_wall_beside_a_bevel_is_laid_out_at_its_own_length() { + let d = document(); + // A bevel 10 wide added around the square sets each wall 10 out, so each wall is 120 long; a + // bevel takes the length of the wall it sits above. Carved in, the walls are the square's own. + for (inside, length) in [(false, 120.0), (true, 100.0)] { + let solid = object(CLASSIC_EXTRUDE, json!({"bevel": "classic", "bevelHeight": 10, "bevelInside": inside})); + for side in surfaces(&solid).iter().skip(2) { + assert!((side.width - length).abs() < 1e-6, "inside {inside}: {side:?}"); + } + // Seen from one side, the art on the wall that faces the viewer keeps its size. + let walls: Vec = (3..=6).map(|k| json!({"surface": k, "symbol": "Corner"})).collect(); + let n = object(CLASSIC_EXTRUDE, json!({"bevel": "classic", "bevelHeight": 10, "bevelInside": inside, "rotationY": 90, "mapArt": walls})); + let art = solid_art_in(Some(&d), &n).unwrap(); + let whole = bounds_of(&[filled(&art, RED), filled(&art, BLUE), filled(&art, GREEN)].concat()); + assert!((whole.width() - 30.0).abs() < 1e-6 && (whole.height() - 30.0).abs() < 1e-6, "inside {inside}: {whole:?}"); + } +} + +#[test] +fn art_on_a_facet_with_a_curved_edge_is_clipped_to_that_edge() { + let quad = vec![Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)]; + // The facet's top edge follows a curve that bows into the quad, down to y = 2. + let mut curved = BezPath::new(); + curved.move_to((0.0, 0.0)); + curved.curve_to((10.0 / 3.0, 8.0 / 3.0), (20.0 / 3.0, 8.0 / 3.0), (10.0, 0.0)); + curved.line_to((10.0, 10.0)); + curved.line_to((0.0, 10.0)); + curved.close_path(); + let facet = Facet { + contours: vec![quad.clone()], + depth: 0.0, + brightness: 1.0, + illumination: [1.0; 3], + normal: [0.0, 0.0, 1.0], + rgb_gradient: None, + outline: Some(PathData::from_bezpath(&curved)), + side: true, + away: false, + end: None, + plane: None, + surface: None, + membrane: None, + cell: None, + }; + let cell = MapCell { surface: 0, page: quad.clone(), uv: quad.clone() }; + let whole = Rect::new(0.0, 0.0, 10.0, 10.0); + let art = Unrolled { + polygons: vec![quad], + boxes: vec![whole], + bounds: whole, + rule: FillRule::NonZero, + paint: Paint::solid(RED), + opacity: 1.0, + blend: Default::default(), + place: Affine::IDENTITY, + }; + let (mut budget, mut copies) = (MapBudget::default(), 0); + let out = cell_art(NodeId(1), &[art], &cell, &facet, &|c| c, &mut budget, &mut copies).unwrap(); + let area: f64 = out.iter().filter_map(|n| n.path_data()).map(|p| vectorcraft_geom::kurbo::Shape::area(&p.to_bezpath()).abs()).sum(); + let want = vectorcraft_geom::kurbo::Shape::area(&curved).abs(); + assert!((area - want).abs() < 1e-2, "{area} drawn, {want} inside the curved edge"); +} + +#[test] +fn art_on_a_facet_whose_curved_edge_bows_out_covers_the_whole_facet() { + let quad = vec![Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)]; + // The facet's top edge follows a curve that bows out of the quad, up to y = -2. + let mut curved = BezPath::new(); + curved.move_to((0.0, 0.0)); + curved.curve_to((10.0 / 3.0, -8.0 / 3.0), (20.0 / 3.0, -8.0 / 3.0), (10.0, 0.0)); + curved.line_to((10.0, 10.0)); + curved.line_to((0.0, 10.0)); + curved.close_path(); + let facet = Facet { + contours: vec![quad.clone()], + depth: 0.0, + brightness: 1.0, + illumination: [1.0; 3], + normal: [0.0, 0.0, 1.0], + rgb_gradient: None, + outline: Some(PathData::from_bezpath(&curved)), + side: true, + away: false, + end: None, + plane: None, + surface: None, + membrane: None, + cell: None, + }; + let cell = MapCell { surface: 0, page: quad.clone(), uv: quad }; + // Art that covers the facet and more. + let cover = vec![Point::new(-5.0, -5.0), Point::new(15.0, -5.0), Point::new(15.0, 15.0), Point::new(-5.0, 15.0)]; + let whole = Rect::new(-5.0, -5.0, 15.0, 15.0); + let art = Unrolled { + polygons: vec![cover], + boxes: vec![whole], + bounds: whole, + rule: FillRule::NonZero, + paint: Paint::solid(RED), + opacity: 1.0, + blend: Default::default(), + place: Affine::IDENTITY, + }; + let (mut budget, mut copies) = (MapBudget::default(), 0); + let out = cell_art(NodeId(1), &[art], &cell, &facet, &|c| c, &mut budget, &mut copies).unwrap(); + let area: f64 = out.iter().filter_map(|n| n.path_data()).map(|p| vectorcraft_geom::kurbo::Shape::area(&p.to_bezpath()).abs()).sum(); + let want = vectorcraft_geom::kurbo::Shape::area(&curved).abs(); + assert!((area - want).abs() < 1e-2, "{area} drawn, {want} inside the curved edge"); +} + +#[test] +fn the_bounds_tests_of_contours_away_from_a_cell_count_as_cuts() { + let quad = vec![Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)]; + let facet = Facet { + contours: vec![quad.clone()], + depth: 0.0, + brightness: 1.0, + illumination: [1.0; 3], + normal: [0.0, 0.0, 1.0], + rgb_gradient: None, + outline: None, + side: true, + away: false, + end: None, + plane: None, + surface: None, + membrane: None, + cell: None, + }; + let cell = MapCell { surface: 0, page: quad.clone(), uv: quad }; + // Small contours on either side of the cell: the piece's bounds reach across it, but no + // contour's own bounds do. + let polygons: Vec> = (0..2000) + .map(|k| { + let x = if k % 2 == 0 { -1000.0 } else { 1000.0 }; + vec![Point::new(x, 0.0), Point::new(x + 1.0, 0.0), Point::new(x + 1.0, 1.0)] + }) + .collect(); + let boxes: Vec = polygons.iter().filter_map(|p| box_of(p)).collect(); + let art = Unrolled { + polygons, + boxes, + bounds: Rect::new(-1000.0, 0.0, 1001.0, 1.0), + rule: FillRule::NonZero, + paint: Paint::solid(RED), + opacity: 1.0, + blend: Default::default(), + place: Affine::IDENTITY, + }; + let mut budget = MapBudget { cuts: MAX_SURFACE_CUTS - 10, ..MapBudget::default() }; + assert!(cell_art(NodeId(1), &[art], &cell, &facet, &|c| c, &mut budget, &mut 0).is_none()); +} + +#[test] +fn a_map_on_the_back_cap_reads_the_right_way_round_from_behind() { + let d = document(); + let n = object(CLASSIC_EXTRUDE, json!({"rotationY": 180, "mapArt": [{"surface": 1, "symbol": "Mark"}, {"surface": 2, "symbol": "Corner"}]})); + let art = solid_art_in(Some(&d), &n).unwrap(); + // Only the back cap is seen, and it carries its own map's art. + assert_eq!(filled(&art, RED).len(), 1); + assert_eq!((filled(&art, BLUE).len(), filled(&art, GREEN).len()), (1, 1)); + assert!(handedness(&art) > 0.0); +} + +#[test] +fn art_past_the_shared_limits_leaves_out_the_mapped_art_of_every_solid() { + let mut d = document(); + // A zigzag of half the straight sides one 3D effect's mapped art may draw. + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + for i in 1..=MAX_ELEMENTS / 2 { + b.line_to((i as f64 * 0.00005, (i % 2) as f64)); + } + b.close_path(); + let half = Node::path(NodeId(0), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0)); + d.symbols.push(Symbol { dynamic: false, name: "Half".into(), art: Arc::new(half) }); + let gray = Color::rgb(0.5, 0.5, 0.5); + // A group of two squares: the first solid's front is surface 1, the second's surface 7. + let art = |maps: Value, invisible: bool| { + let members = + vec![Arc::new(square(8, Rect::new(0.0, 0.0, 100.0, 100.0), gray)), Arc::new(square(9, Rect::new(200.0, 0.0, 300.0, 100.0), gray))]; + let mut g = Node::group(NodeId(7), members); + let p = json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "surface": "none", "mapInvisible": invisible, "mapArt": maps}); + g.appearance.effects.push(crate::new_effect(CLASSIC_EXTRUDE, &p).unwrap()); + solid_art_in(Some(&d), &g).unwrap() + }; + // One solid's art fits. + assert!(!filled(&art(json!([{"surface": 1, "symbol": "Half"}]), false), RED).is_empty()); + // Both together are past the limit: no solid draws its art, and with Invisible Geometry every + // solid's faces draw. + let both = json!([{"surface": 1, "symbol": "Half"}, {"surface": 7, "symbol": "Half"}]); + assert!(filled(&art(both.clone(), false), RED).is_empty()); + let hidden = art(both, true); + assert!(filled(&hidden, RED).is_empty()); + let faces = bounds_of(&filled(&hidden, gray)); + assert!(faces.x0 < 1.0 && faces.x1 > 299.0, "{faces:?}"); +} + +#[test] +fn a_wall_under_a_perspective_maps_its_art_whole() { + let d = document(); + let all_walls: Vec = (3..=6).map(|k| json!({"surface": k, "symbol": "Mark"})).collect(); + let n = object(CLASSIC_EXTRUDE, json!({"rotationY": -60, "perspectiveAngle": 90, "mapArt": all_walls})); + let art = solid_art_in(Some(&d), &n).unwrap(); + // The wall is one flat face: the square maps onto it as one four-cornered area, not as two + // pieces that meet along the face's diagonal. + let marks = filled(&art, RED); + assert_eq!(marks.len(), 1); + let mark = &marks[0]; + assert_eq!((mark.subpaths.len(), mark.subpaths[0].anchors.len()), (1, 4), "{mark:?}"); + // Nearer the viewer the square's side is longer. + let side = |i: usize| mark.subpaths[0].anchors[i].p.distance(mark.subpaths[0].anchors[(i + 1) % 4].p); + let uneven = (side(0) - side(2)).abs().max((side(1) - side(3)).abs()); + assert!(uneven > 0.05, "{} {} {} {}", side(0), side(1), side(2), side(3)); +} + +#[test] +fn shade_artwork_and_invisible_geometry_change_what_is_drawn() { + let d = document(); + let params = |extra: Value| { + let mut p = json!({"surface": "diffuse", "rotationY": -60, "lightIntensity": 0, "ambient": 20, "mapArt": [{"surface": 1, "symbol": "Mark"}]}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + solid_art_in(Some(&d), &object(CLASSIC_EXTRUDE, p)).unwrap() + }; + // Unshaded, the art keeps its own color on a shaded face. + assert_eq!(filled(¶ms(json!({})), RED).len(), 1); + // Shaded, it darkens toward black with its face. + let shaded = params(json!({"mapShade": true})); + assert!(filled(&shaded, RED).is_empty()); + let mut darkest = 1.0f32; + shaded.walk(&mut |n| { + for item in &n.appearance.items { + if let AppearanceItem::Fill(f) = item + && let Some([r, g, b]) = f.paint.color().map(|c| c.to_rgb()) + && g < 1e-4 + && b < 1e-4 + && r > 0.0 + { + darkest = darkest.min(r); + } + } + }); + assert!(darkest < 0.999, "the art is as dark as its face: {darkest}"); + // With Invisible Geometry only the art is drawn. + let count = |art: &Node| { + let mut paths = 0; + art.walk(&mut |n| paths += usize::from(n.path_data().is_some() && !n.appearance.items.is_empty())); + paths + }; + assert!(count(¶ms(json!({}))) > 1); + assert_eq!(count(¶ms(json!({"mapInvisible": true}))), 1); + // Without a map Invisible Geometry leaves the solid as it is, and Wireframe draws no art. + let plain = object(CLASSIC_EXTRUDE, json!({"mapInvisible": true})); + assert!(count(&solid_art_in(Some(&d), &plain).unwrap()) > 0); + assert!(filled(¶ms(json!({"surface": "wireframe"})), RED).is_empty()); +} + +#[test] +fn a_map_past_the_surfaces_draws_nothing_and_a_missing_symbol_is_left_out() { + let d = document(); + let art = |maps: Value| solid_art_in(Some(&d), &object(CLASSIC_EXTRUDE, json!({"mapArt": maps}))).unwrap(); + assert!(filled(&art(json!([{"surface": 7, "symbol": "Mark"}])), RED).is_empty()); + assert!(filled(&art(json!([{"surface": 1, "symbol": "Gone"}])), RED).is_empty()); + // A hollow solid's first surface is its first wall, so the cap's map draws nothing there. + let hollow = object(CLASSIC_EXTRUDE, json!({"cap": false, "mapArt": [{"surface": 1, "symbol": "Mark"}]})); + assert!(filled(&solid_art_in(Some(&d), &hollow).unwrap(), RED).is_empty()); + assert_eq!(missing(&d, &json!({"mapArt": [{"surface": 1, "symbol": "Gone"}]})), Some("Gone".to_string())); + assert_eq!(missing(&d, &json!({"mapArt": [{"surface": 1, "symbol": "Mark"}]})), None); +} + +#[test] +fn the_points_drawn_on_earlier_surfaces_leave_the_next_symbol_its_own_allowance() { + let d = document(); + let art = MapArt::of(Some(&d), CLASSIC_EXTRUDE, &json!({"mapArt": [{"surface": 3, "symbol": "Mark"}]})).unwrap(); + let wall = SolidSurface { kind: SurfaceKind::Wall, width: 100.0, height: 50.0, center: None }; + // Earlier surfaces drew more points on their faces than one symbol may take cut into pieces. + let mut budget = MapBudget { points: MAX_ELEMENTS + 1, ..MapBudget::default() }; + let pieces = art.unrolled(&art.maps[0], &wall, &mut budget).expect("the symbol is cut into pieces"); + assert_eq!(pieces.len(), 1); +} + +#[test] +fn art_past_the_paint_copies_allowance_leaves_the_allowance_to_later_art() { + let d = document(); + let mut b = BezPath::new(); + b.move_to((100.0, 0.0)); + b.line_to((100.0, 100.0)); + let path = PathData::from_bezpath(&b); + let gray = Paint::solid(Color::rgb(0.5, 0.5, 0.5)); + let n = Node::path(NodeId(7), path.clone(), Appearance::basic(Paint::None, gray.clone(), 1.0)); + let p = crate::merged_params( + CLASSIC_REVOLVE, + &json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "surface": "none", "offset": 40, "mapArt": [{"surface": 1, "symbol": "Mark"}]}), + ); + let art = MapArt::of(Some(&d), CLASSIC_REVOLVE, &p).unwrap(); + let bounds = path.bounds().unwrap(); + let options = vectorcraft_three_d::Revolve { map_surface: true, ..crate::revolve::options_of(CLASSIC_REVOLVE, &p) }; + let (width, height) = vectorcraft_three_d::revolve_surface_size(&path, bounds, options).unwrap(); + let layout = SolidLayout { first: 0, surfaces: vec![SolidSurface { kind: SurfaceKind::Side, width, height, center: None }], ends: None }; + let facets = vectorcraft_three_d::revolve_facets(&path, bounds, options).unwrap(); + // The side's art, with the copies of its paint and its points counted from `copies` and + // `budget` already used. + let draw = |copies: &mut usize, budget: &mut MapBudget| { + let mapped = crate::solids::classic::Mapped { art: &art, layout: &layout, budget, copies }; + let blend = vectorcraft_doc::color::BlendMode::Normal; + crate::solids::classic::surface(&n, &facets, &gray, (1.0, blend), &p, Some(mapped), false).0 + }; + let (mut copies, mut budget) = (0, MapBudget::default()); + assert!(!filled(&draw(&mut copies, &mut budget), RED).is_empty()); + assert!(copies > 0 && budget != MapBudget::default()); + // With the allowance used up, the art is left out, and so are the copies and the points it + // would have taken. + let full = crate::revolve::MAX_PAINT_COPIES; + let (mut copies, mut budget) = (full, MapBudget::default()); + assert!(filled(&draw(&mut copies, &mut budget), RED).is_empty()); + assert_eq!(copies, full); + assert_eq!(budget, MapBudget::default()); +} + +fn missing(d: &Document, p: &Value) -> Option { + super::super::missing_symbol(d, p, None) +} + +#[test] +fn revolve_classic_wraps_its_map_around_the_side() { + let d = document(); + let mut b = BezPath::new(); + b.move_to((100.0, 0.0)); + b.line_to((100.0, 100.0)); + let mut n = Node::path(NodeId(7), PathData::from_bezpath(&b), Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.5, 0.5, 0.5)), 1.0)); + let view = + json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "surface": "none", "offset": 40, "mapArt": [{"surface": 1, "symbol": "Corner"}]}); + n.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, &view).unwrap()); + let art = crate::revolve_art_in(Some(&d), &n).unwrap(); + // The art is drawn at the middle of the side that faces the viewer, the right way round. + assert!(!filled(&art, RED).is_empty()); + assert!(handedness(&art) > 0.0); + let whole = bounds_of(&[filled(&art, RED), filled(&art, BLUE), filled(&art, GREEN)].concat()); + assert!((whole.center().y - 50.0).abs() < 1.0, "{whole:?}"); + // A map of another surface draws nothing. + n.appearance.effects[0].params["mapArt"] = json!([{"surface": 2, "symbol": "Corner"}]); + assert!(filled(&crate::revolve_art_in(Some(&d), &n).unwrap(), RED).is_empty()); +} + +#[test] +fn invisible_geometry_leaves_out_every_member_of_a_revolved_group() { + let d = document(); + let gray = Color::rgb(0.5, 0.5, 0.5); + let line = |id: u64, x: f64, height: f64| { + let mut b = BezPath::new(); + b.move_to((x, 0.0)); + b.line_to((x, height)); + Arc::new(Node::path(NodeId(id), PathData::from_bezpath(&b), Appearance::basic(Paint::None, Paint::solid(gray), 1.0))) + }; + // The map goes on the side of the longer member; the shorter one has none. + let art = |extra: Value| { + let mut p = + json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "surface": "none", "offset": 40, "mapArt": [{"surface": 1, "symbol": "Mark"}]}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let mut g = Node::group(NodeId(7), vec![line(8, 100.0, 100.0), line(9, 140.0, 30.0)]); + g.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, &p).unwrap()); + crate::revolve_art_in(Some(&d), &g).unwrap() + }; + let shown = art(json!({})); + assert!(!filled(&shown, RED).is_empty() && !filled(&shown, gray).is_empty()); + let hidden = art(json!({"mapInvisible": true})); + assert!(!filled(&hidden, RED).is_empty()); + assert!(filled(&hidden, gray).is_empty(), "no member's faces are drawn"); + // On Wireframe the members are drawn as they are without a map. + let wire = art(json!({"mapInvisible": true, "surface": "wireframe"})); + let mut strokes = 0; + wire.walk(&mut |n| strokes += usize::from(n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(_))))); + assert!(strokes > 0); +} + +#[test] +fn a_revolved_group_past_its_shared_limits_lists_no_surface() { + let gray = Color::rgb(0.5, 0.5, 0.5); + // Profiles of five anchors each; one alone fits Revolve's limits. + let profile = |id: u64, x: f64| { + let mut b = BezPath::new(); + b.move_to((x, 0.0)); + for i in 1..5 { + b.line_to((x + f64::from(i % 2), f64::from(i) * 10.0)); + } + Arc::new(Node::path(NodeId(id), PathData::from_bezpath(&b), Appearance::basic(Paint::None, Paint::solid(gray), 1.0))) + }; + let group = |count: u64| { + let mut g = Node::group(NodeId(7), (0..count).map(|k| profile(k + 8, 100.0 + k as f64 * 0.01)).collect()); + g.appearance.effects.push(crate::new_effect(CLASSIC_REVOLVE, &json!({})).unwrap()); + g + }; + let d = document(); + assert_eq!(map_surfaces_at(Some(&d), &group(2), None, 0).map(|s| s.len()), Some(1)); + // 4,000 of them together are past the anchors the members share. + assert!(map_surfaces_at(Some(&d), &group(4000), None, 0).is_none()); +} + +#[test] +fn an_extruded_group_past_the_faces_of_one_object_lists_no_surface() { + // Polygons of 1,000 corners: each solid alone has about 1,000 faces. + let polygon = |id: u64, x: f64| { + let mut b = BezPath::new(); + for i in 0..1000 { + let a = f64::from(i) * std::f64::consts::TAU / 1000.0; + let p = (x + 40.0 * a.cos(), 40.0 * a.sin()); + if i == 0 { b.move_to(p) } else { b.line_to(p) } + } + b.close_path(); + Arc::new(Node::path(NodeId(id), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0))) + }; + let group = |count: u64| { + let mut g = Node::group(NodeId(7), (0..count).map(|k| polygon(k + 8, k as f64 * 100.0)).collect()); + g.appearance.effects.push(crate::new_effect(CLASSIC_EXTRUDE, &json!({"drawHiddenFaces": true})).unwrap()); + g + }; + let d = document(); + assert!(map_surfaces_at(Some(&d), &group(2), None, 0).is_some()); + // 200 of them together have more faces than one object draws. + assert!(map_surfaces_at(Some(&d), &group(200), None, 0).is_none()); +} + +#[test] +fn bad_maps_are_refused() { + let d = document(); + let check = |id: &str, p: Value| { + let n = object(id, json!({})); + validate_three_d_in(Some(&d), &n, id, &crate::merged_params(id, &p)) + }; + assert_eq!(check(CLASSIC_EXTRUDE, json!({"mapArt": [{"surface": 3, "symbol": "Mark", "scaleX": 50}]})), Ok(())); + assert_eq!(check(CLASSIC_REVOLVE, json!({"mapArt": [{"surface": 1, "symbol": "Mark"}], "mapShade": true})), Ok(())); + for (p, error) in [ + (json!({"mapArt": {}}), "`mapArt` must be an array"), + (json!({"mapArt": [7]}), "each of `mapArt` must be an object"), + (json!({"mapArt": [{"symbol": "Mark"}]}), "needs `surface`"), + (json!({"mapArt": [{"surface": 0, "symbol": "Mark"}]}), "needs `surface`"), + (json!({"mapArt": [{"surface": 1.5, "symbol": "Mark"}]}), "needs `surface`"), + (json!({"mapArt": [{"surface": 100001, "symbol": "Mark"}]}), "needs `surface`"), + (json!({"mapArt": [{"surface": 1}]}), "needs `symbol`"), + (json!({"mapArt": [{"surface": 1, "symbol": "Mark", "face": "front"}]}), "not `face`"), + (json!({"mapArt": [{"surface": 1, "symbol": "Mark", "scaleX": 0}]}), "scaleX must be a number from 1 to 10000"), + (json!({"mapArt": [{"surface": 1, "symbol": "Mark", "rotation": 361}]}), "rotation must be a number from -360 to 360"), + (json!({"mapArt": [{"surface": 1, "symbol": "Mark", "x": "left"}]}), "x must be a number"), + (json!({"mapArt": [{"surface": 1, "symbol": "Mark"}, {"surface": 1, "symbol": "Corner"}]}), "maps surface 1 more than once"), + (json!({"mapShade": 1}), "`mapShade` must be true or false"), + (json!({"mapInvisible": "yes"}), "`mapInvisible` must be true or false"), + ] { + for id in [CLASSIC_EXTRUDE, CLASSIC_REVOLVE] { + let e = check(id, p.clone()).unwrap_err(); + assert!(e.contains(error), "{id} {p}: {e}"); + } + } + let many: Vec = (1..=65).map(|k| json!({"surface": k, "symbol": "Mark"})).collect(); + assert!(check(CLASSIC_EXTRUDE, json!({"mapArt": many})).unwrap_err().contains("at most 64 maps")); + // Rotate (Classic) has no surface to map onto. + let e = check(CLASSIC_ROTATE, json!({"mapArt": [{"surface": 1, "symbol": "Mark"}]})).unwrap_err(); + assert!(e.contains(MAP_ART_NOT_TAKEN), "{e}"); +} + +#[test] +fn a_mapped_symbol_past_the_limits_of_a_graphics_art_is_refused() { + let mut d = document(); + // A zigzag of more straight sides than one 3D effect's graphics may draw. + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + for i in 1..=MAX_ELEMENTS { + b.line_to((i as f64 * 0.001, (i % 2) as f64)); + } + b.close_path(); + let dense = Node::path(NodeId(0), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0)); + d.symbols.push(Symbol { dynamic: false, name: "Dense".into(), art: Arc::new(dense) }); + for id in [CLASSIC_EXTRUDE, CLASSIC_REVOLVE] { + let p = crate::merged_params(id, &json!({"mapArt": [{"surface": 1, "symbol": "Dense"}]})); + let e = validate_three_d_in(Some(&d), &object(id, json!({})), id, &p).unwrap_err(); + assert!(e.contains("too complex"), "{id}: {e}"); + } + // On a fill, as on the object. + let plain = square(7, Rect::new(0.0, 0.0, 100.0, 100.0), Color::rgb(0.5, 0.5, 0.5)); + let p = crate::merged_params(CLASSIC_REVOLVE, &json!({"mapArt": [{"surface": 1, "symbol": "Dense"}]})); + let e = validate_three_d_at_in(Some(&d), &plain, CLASSIC_REVOLVE, &p, (Some(0), 0)).unwrap_err(); + assert!(e.contains("too complex"), "{e}"); +} + +#[test] +fn a_mapped_symbol_whose_curves_cut_into_too_many_pieces_is_refused() { + let mut d = document(); + // Large circles: a few curves each, but many straight pieces once they are cut. + let loops = |name: &str, count: usize| { + let mut b = BezPath::new(); + for k in 0..count { + let r = 1e5; + let circle = vectorcraft_geom::kurbo::Circle::new((k as f64 * 2.1 * r, 0.0), r); + b.extend(vectorcraft_geom::kurbo::Shape::path_elements(&circle, 0.1)); + } + let art = Node::path(NodeId(0), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0)); + Symbol { dynamic: false, name: name.into(), art: Arc::new(art) } + }; + d.symbols.push(loops("Loop", 1)); + d.symbols.push(loops("Loops", 400)); + let check = |id: &str, surface: usize, symbol: &str| { + let p = crate::merged_params(id, &json!({"mapArt": [{"surface": surface, "symbol": symbol}]})); + validate_three_d_in(Some(&d), &object(id, json!({})), id, &p) + }; + // Extrude & Bevel's surface 3 is a wall, and Revolve's surface 1 its side. + for (id, surface) in [(CLASSIC_EXTRUDE, 3), (CLASSIC_REVOLVE, 1)] { + assert_eq!(check(id, surface, "Loop"), Ok(()), "{id}"); + let e = check(id, surface, "Loops").unwrap_err(); + assert!(e.contains("too complex"), "{id}: {e}"); + } + // A cap draws the curves as they are, without cutting them. + assert_eq!(check(CLASSIC_EXTRUDE, 1, "Loops"), Ok(())); +} + +#[test] +fn maps_are_set_cleared_and_renamed_with_their_symbols() { + let p = json!({"depth": 20}); + let map = + |surface: usize, symbol: &str| SurfaceMap { surface, symbol: symbol.into(), x: 0.0, y: 0.0, scale_x: 100.0, scale_y: 100.0, rotation: 0.0 }; + let p = with_surface_map(&p, 4, Some(&map(4, "Mark"))); + let p = with_surface_map(&p, 2, Some(&map(2, "Corner"))); + let p = with_surface_map(&p, 4, Some(&map(4, "Corner"))); + // One map for a surface, in the order of the surfaces; the other parameters stay. + assert_eq!(surface_maps(&p), vec![map(2, "Corner"), map(4, "Corner")]); + assert_eq!(p["depth"], json!(20)); + assert_eq!(surface_maps(&with_surface_map(&p, 2, None)), vec![map(4, "Corner")]); + // A file's maps: entries that are not valid and a surface's second map are left out. + let loaded = json!({"mapArt": [{"surface": 1, "symbol": "Mark"}, {"surface": 1, "symbol": "Corner"}, {"surface": 0, "symbol": "Mark"}, 3]}); + assert_eq!(surface_maps(&loaded), vec![map(1, "Mark")]); + // Renaming a symbol renames it in the maps of the effects that take them. + let mut n = object(CLASSIC_EXTRUDE, json!({"mapArt": [{"surface": 1, "symbol": "Mark"}]})); + assert_eq!(super::super::graphic_symbols(&n), vec!["Mark".to_string()]); + assert!(super::super::rename_graphic_symbol(&mut n, "Mark", "Logo")); + assert_eq!(surface_maps(&n.appearance.effects[0].params)[0].symbol, "Logo"); + // Scale to Fit fills the surface: each side by its own scale when the art is square to it. + assert_eq!(map(1, "Mark").fitting_scales(Rect::new(0.0, 0.0, 10.0, 10.0), (100.0, 50.0)), Some((1000.0, 500.0))); + let turned = SurfaceMap { rotation: 90.0, ..map(1, "Mark") }; + assert_eq!(turned.fitting_scales(Rect::new(0.0, 0.0, 10.0, 20.0), (100.0, 50.0)), Some((500.0, 500.0))); + let aslant = SurfaceMap { rotation: 45.0, ..map(1, "Mark") }; + let (sx, sy) = aslant.fitting_scales(Rect::new(0.0, 0.0, 10.0, 10.0), (100.0, 50.0)).unwrap(); + assert!((sx - sy).abs() < 1e-9 && (sx - 50.0 / (20.0 * 0.5f64.sqrt()) * 100.0).abs() < 1e-6, "{sx} {sy}"); + assert_eq!(map(1, "Mark").fitting_scales(Rect::new(0.0, 0.0, 0.0, 10.0), (100.0, 50.0)), None); +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index a8209b9b42..b9e21f6fab 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -41,6 +41,7 @@ vectorcraft-eps = { workspace = true } vectorcraft-metafile = { workspace = true } vectorcraft-plugins = { workspace = true } vectorcraft-affinity = { workspace = true } +vectorcraft-cdr = { workspace = true } vectorcraft-scriptcheck = { workspace = true } vectorcraft-js = { workspace = true } # The commands' parameter schemas (schemas.rs). @@ -95,6 +96,7 @@ craft-jxl = { workspace = true } hayro-ccitt = { workspace = true } craft-stream-codecs = { workspace = true } vectorcraft-affinity = { workspace = true, features = ["synth"] } +vectorcraft-cdr = { workspace = true, features = ["synth"] } crc32fast = { workspace = true } vectorcraft-testkit = { workspace = true } proptest = { workspace = true } diff --git a/crates/engine/examples/appearance_rows_bench.rs b/crates/engine/examples/appearance_rows_bench.rs new file mode 100644 index 0000000000..13606fb7e2 --- /dev/null +++ b/crates/engine/examples/appearance_rows_bench.rs @@ -0,0 +1,164 @@ +//! `cargo run --release -p vectorcraft-engine --example appearance_rows_bench` prints the time three Appearance row edits +//! take with every path of documents of 2,000, 10,000 and 20,000 squares selected, each square with one fill row and one +//! stroke row. For each size it first times the step that keeps the objects whose shown rows the edit wrote, on the same +//! ids, two ways: each id looked up in the list of written objects (a list of ids, and a list of ids with the kind of row, +//! as the commands held them), and each id looked up in a set built from that list. It checks that both ways keep the +//! same ids in the same order. Then it times the whole `appearance.setItem` (`index` 1, `weight` 2), +//! `appearance.duplicateItem` (`index` 0) and `stroke.set` (`item` 1, `weight` 2) commands, each on a fresh copy of the +//! document made before the clock starts. +//! 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. The two lookup +//! ways run in alternating order. +// 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}; +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) +} + +/// 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` closed 10 pt squares, each with a red fill row and a 1 pt black stroke row, and their ids in paint order. +fn document(n: usize) -> (Document, Vec) { + let mut doc = Document::new(4000.0, 4000.0); + let layer = doc.layers.first().map(|l| l.id); + let mut ids = Vec::with_capacity(n); + for i in 0..n { + let (x, y) = ((i % 200) as f64 * 12.0, (i / 200) 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(); + let looks = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::solid(Color::BLACK), 1.0); + doc.insert(layer, usize::MAX, Node::path(id, path, looks)).unwrap(); + ids.push(id); + } + (doc, ids) +} + +/// The ids among `ids` that `wrote` holds, each looked up in the list: the lookup the row edits made. +fn in_list(ids: Vec, wrote: &[NodeId]) -> Vec { + ids.into_iter().filter(|id| wrote.contains(id)).collect() +} + +/// [`in_list`] with each id looked up in a set built from `wrote`. +fn in_set(ids: Vec, wrote: &[NodeId]) -> Vec { + let wrote: HashSet = wrote.iter().copied().collect(); + ids.into_iter().filter(|id| wrote.contains(id)).collect() +} + +/// The ids among `ids` that `edited` holds with either kind of row, each looked up in the list, as `appearance.setItem` +/// did. +fn in_kind_list(ids: Vec, edited: &[(NodeId, bool)]) -> Vec { + ids.into_iter().filter(|id| edited.iter().any(|(e, _)| e == id)).collect() +} + +/// [`in_kind_list`] with each id looked up in a set built from the ids of `edited`. +fn in_kind_set(ids: Vec, edited: &[(NodeId, bool)]) -> Vec { + let wrote: HashSet = edited.iter().map(|(id, _)| *id).collect(); + ids.into_iter().filter(|id| wrote.contains(id)).collect() +} + +fn row(name: &str, ms: f64) { + println!(" {name:<52} {ms:>10.3} ms"); +} + +/// The medians of `old` and `new` over [`iters`] runs, alternating which goes first; each run filters `ids` `reps` times +/// on copies made before the clock starts and gives the time of one. +fn time_both(ids: &[NodeId], wrote: &W, old: fn(Vec, &W) -> Vec, new: fn(Vec, &W) -> Vec) -> (f64, f64) { + let reps = (200_000 / ids.len()).max(1); + let run = |f: fn(Vec, &W) -> Vec| { + let mut work: Vec> = (0..reps).map(|_| ids.to_vec()).collect(); + ms(|| { + for it in &mut work { + black_box(f(black_box(std::mem::take(it)), wrote)); + } + }) / reps as f64 + }; + let (mut a, mut b) = (vec![], vec![]); + for i in 0..iters() { + if i % 2 == 0 { + a.push(run(old)); + b.push(run(new)); + } else { + b.push(run(new)); + a.push(run(old)); + } + } + (median(a), median(b)) +} + +fn bench(n: usize) { + println!("{n} squares, all selected"); + let (doc, ids) = document(n); + // Every object's topmost stroke row was written, as when every selected object takes the edit. + let edited: Vec<(NodeId, bool)> = ids.iter().map(|id| (*id, false)).collect(); + // A list missing every other id, so lookups that fail are timed too. + let half: Vec = ids.iter().copied().step_by(2).collect(); + for wrote in [&ids, &half] { + assert_eq!(in_list(ids.clone(), wrote), in_set(ids.clone(), wrote), "both ways keep the same ids"); + } + assert_eq!(in_kind_list(ids.clone(), &edited), in_kind_set(ids.clone(), &edited), "both ways keep the same ids"); + let (old, new) = time_both(&ids, ids.as_slice(), in_list, in_set); + row("keep written ids, every id in the list", old); + row("keep written ids, every id in a set", new); + let (old, new) = time_both(&ids, half.as_slice(), in_list, in_set); + row("keep written ids, half the ids in the list", old); + row("keep written ids, half the ids in a set", new); + let (old, new) = time_both(&ids, edited.as_slice(), in_kind_list, in_kind_set); + row("keep written ids, (id, kind) list", old); + row("keep written ids, (id, kind) set", new); + + let all: Vec = ids.iter().map(|id| id.0).collect(); + let commands: [(&str, Value); 3] = [ + ("appearance.setItem", json!({"ids": all, "index": 1, "weight": 2})), + ("appearance.duplicateItem", json!({"ids": all, "index": 0})), + ("stroke.set", json!({"ids": all, "item": 1, "weight": 2})), + ]; + for (cmd, p) in &commands { + let runs = (0..iters()) + .map(|_| { + let mut s = Session::new(); + s.add_document(doc.clone(), None); + let t = ms(|| drop(black_box(s.execute(cmd, p).unwrap()))); + drop(black_box(s)); + t + }) + .collect(); + row(&format!("{cmd}, whole command"), median(runs)); + } +} + +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 cd29ab4154..e2f6b7624f 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -32,6 +32,7 @@ pub mod expand; pub(crate) mod fileinfo; pub mod fileio; pub mod findfiles; +pub mod flare; pub mod flatten; pub mod fontfiles; mod fonts; @@ -47,6 +48,7 @@ mod info; pub(crate) mod inline; mod interactivity; mod intertwine; +pub mod kinsokusets; pub(crate) mod layer; mod layerpanel; pub mod library; @@ -74,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; @@ -98,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; @@ -321,6 +325,8 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(pathops::specs()); v.extend(compoundshape::specs()); v.extend(typecmd::specs()); + v.extend(retype::specs()); + v.extend(retype::fonts::specs()); v.extend(menucmds::specs()); v.extend(live::specs()); v.extend(colorcmds::specs()); @@ -331,8 +337,10 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(textstyles::specs()); v.extend(fonts::specs()); v.extend(compositefonts::specs()); + v.extend(kinsokusets::specs()); v.extend(fontfiles::specs()); v.extend(help::specs()); + v.extend(toast::specs()); v.extend(threads::specs()); v.extend(textwrap::specs()); v.extend(graph::specs()); @@ -382,6 +390,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()); @@ -842,6 +851,7 @@ 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(crate) use paint::LIVE_PAINT_BUCKET; pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys}; pub use select::SIMILAR; pub(crate) use vectorcraft_doc::range::parse_range; @@ -874,10 +884,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`). @@ -901,6 +915,8 @@ pub(crate) use buildcmds::TracePresetChanges; /// The shapes a group selected alone gives the Pathfinder panel. pub use pathops::shape_count; +/// The tile counts Create Object Mosaic would use (the dialog's Use Ratio button sets them). +pub use menucmds::mosaic_counts; /// The Shape Mode commands' warning when a selected open path encloses no area. pub use pathops::SHAPE_MODE_OPEN_PATH_NO_AREA; @@ -911,6 +927,10 @@ pub use buildcmds::live_paint_gaps; /// Control bar enable it when it changes one). pub use brushsym::reset_transformation_changes; +/// Whether an object is a symbol set (the Symbolism Tools Options' Symbol Set Density applies to +/// the selected ones). +pub use brushsym::is_symbol_set; + /// The Symbols panel's current symbol, as `symbol.list` answers it (the panel reads it on every /// frame without running the command). pub use brushsym::current_symbol; diff --git a/crates/engine/src/cmd/addons/pathtools.rs b/crates/engine/src/cmd/addons/pathtools.rs index 2d1ded312f..586dc9947e 100644 --- a/crates/engine/src/cmd/addons/pathtools.rs +++ b/crates/engine/src/cmd/addons/pathtools.rs @@ -4,11 +4,12 @@ //! ([`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`]), Smooth Bridge ([`bridge`]), Common Tangents -//! ([`tangents`]) and Tangent Circle -//! ([`tangent_circle`]). +//! ([`tangents`]), Tangent Circle ([`tangent_circle`]) and Add Bounding Rectangle and Add +//! Bounding Circle ([`bounding`]). //! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's //! and the UI's. +mod bounding; mod bridge; mod corners; #[cfg(test)] @@ -188,6 +189,7 @@ pub fn specs() -> Vec { v.extend(bridge::specs()); v.extend(tangent_circle::specs()); v.extend(tangents::specs()); + v.extend(bounding::specs()); v } diff --git a/crates/engine/src/cmd/addons/pathtools/bounding.rs b/crates/engine/src/cmd/addons/pathtools/bounding.rs new file mode 100644 index 0000000000..954a4f829a --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/bounding.rs @@ -0,0 +1,376 @@ +//! Add Bounding Rectangle and Add Bounding Circle: a live rectangle on the selection's geometric +//! bounding box, or the smallest live circle around its outlines. The circle is the geometry crate's +//! ([`enclosing_circle`](vectorcraft_geom::shapes::enclosing_circle)). + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, LiveShape, Node, NodeId, NodeKind, SymbolBoxes}; +use vectorcraft_geom::kurbo::ParamCurveExtrema; +use vectorcraft_geom::{Affine, CubicBez, FillRule, ParamCurve, PathSeg, Point, Rect, shapes}; + +use super::super::super::edit::{no_symbol_part, selected_roots_to_transform}; +use super::super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or}; +use crate::sanity::rect_in_range; +use crate::{Result, Session}; + +#[cfg(test)] +mod tests; + +/// Add Bounding Rectangle's command. +pub(crate) const RECTANGLE: &str = "addon.pathtools.boundingRectangle"; +/// Add Bounding Circle's command. +pub(crate) const CIRCLE: &str = "addon.pathtools.boundingCircle"; + +/// How far a curve may stray from the points the circle is fitted to, in points. The circle's +/// radius grows by as much, so it holds the curves themselves. +const FLATNESS: f64 = 0.01; + +pub(super) fn specs() -> Vec { + vec![ + cmd!( + "addon.pathtools.boundingRectangle", + "Add Bounding Rectangle", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{each?: bool (default false: one rectangle around the whole selection; true: one around each selected object), offset?: pt (0 or more; default 0: added on every side)} draw a live rectangle on the geometric bounding box of the selected objects (strokes and effects left out; a path of a compound path selected on its own counts as an object), with the current paint, on top of the current layer or of the isolated group, as other new art; the rectangles are selected; one undo step. An object whose box has no width or no height (a straight horizontal or vertical line) gets no rectangle unless `offset` is more than 0, nor does an object with no bounds (an empty group); with `each` the result's `skipped` counts them. It is an error when no rectangle is left (\"the shape would have no size\" when a rectangle with no size was left out, else \"nothing to enclose\") and when an edge of a rectangle would lie more than 4,000,000 pt from the origin along either axis (\"the shape would reach past the edge of the canvas\"). The menu item Add Bounding Rectangle… opens a dialog with Offset and One per Object (`each`) and a Preview → {id: the first rectangle, ids, skipped?}", + whole_objects, + bounding_rectangle + ), + cmd!( + "addon.pathtools.boundingCircle", + "Add Bounding Circle", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{each?: bool (default false: one circle around the whole selection; true: one around each selected object), offset?: pt (0 or more; default 0: added to the radius)} draw the smallest live circle that holds the outlines of the selected objects (paths and compound paths by their curves, clip groups and sublayers that clip their contents by their clipping paths, other sublayers by their shown objects, images by their corners, type and other objects by the corners of their bounding box; strokes and effects left out; a path of a compound path selected on its own counts as an object), with the radius 0.01 pt larger so it holds the curves themselves, with the current paint, on top of the current layer or of the isolated group, as other new art; the circles are selected; one undo step. An object at a single point gets no circle unless `offset` is more than 0, nor does an object with no outline (an empty group); with `each` the result's `skipped` counts them. It is an error when no circle is left (\"the shape would have no size\" when a circle with no size was left out, else \"nothing to enclose\") and when an edge of a circle's bounding box would lie more than 4,000,000 pt from the origin along either axis (\"the shape would reach past the edge of the canvas\"). The menu item Add Bounding Circle… opens a dialog with Offset and One per Object (`each`) and a Preview → {id: the first circle, ids, skipped?}", + whole_objects, + bounding_circle + ), + ] +} + +/// Enabled with a selection that is not an object of a symbol instance's art, which +/// [`selected_roots_to_transform`] refuses. +fn whole_objects(s: &Session) -> std::result::Result<(), String> { + has_selection(s)?; + no_symbol_part(s) +} + +/// The shape a command draws. +#[derive(Clone, Copy, PartialEq)] +enum Kind { + Rectangle, + Circle, +} + +fn bounding_rectangle(s: &mut Session, p: &Value) -> Result { + add(s, p, Kind::Rectangle) +} + +fn bounding_circle(s: &mut Session, p: &Value) -> Result { + add(s, p, Kind::Circle) +} + +fn add(s: &mut Session, p: &Value, kind: Kind) -> Result { + let (c, label) = match kind { + Kind::Rectangle => (RECTANGLE, "Add Bounding Rectangle"), + Kind::Circle => (CIRCLE, "Add Bounding Circle"), + }; + let each = switch_or(p, "each", false, c)?; + let offset = number_or(p, "offset", 0.0, c)?; + if !(offset.is_finite() && offset >= 0.0) { + return Err(bad(c, "`offset` must be 0 or more")); + } + // The objects `object.transform` moves: a path of a compound path selected on its own is one. + let roots = selected_roots_to_transform(s)?; + let d = &s.doc()?.doc; + let symbols = d.symbol_boxes(); + let groups: Vec> = if each { roots.iter().map(|id| vec![*id]).collect() } else { vec![roots] }; + let mut made: Vec = vec![]; + // Objects that get no shape: no outline, or a shape with no size. + let mut skipped = 0; + let mut no_size = false; + // The shapes share the halvings, so the work stays bounded however many objects are selected. + let splits = split_share(groups.len()); + for ids in &groups { + match shape_around(d, &symbols, ids, kind, offset, splits) { + Around::Shape(live) => made.push(live), + Around::NoOutline => skipped += 1, + Around::NoSize => { + skipped += 1; + no_size = true; + } + Around::PastCanvas => return Err(bad(c, "the shape would reach past the edge of the canvas")), + } + } + if made.is_empty() { + return Err(bad(c, if no_size { "the shape would have no size" } else { "nothing to enclose" })); + } + let parent = s.doc()?.target_parent()?; + let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + let ids = s.edit(label, |d, sel| { + let mut ids = vec![]; + for live in made { + let kind = NodeKind::Path { path: live.to_path(), rule: FillRule::NonZero, live: Some(Box::new(live)), clipping: false, guide: false }; + let mut n = Node::new(d.alloc_id(), kind); + look.apply(d, &mut n); + ids.push(n.id); + d.insert(parent, usize::MAX, n)?; + } + sel.set(ids.iter().copied()); + Ok(ids) + })?; + let first = ids.first().map_or(0, |id| id.0); + let mut out = json!({ "id": first, "ids": ids.iter().map(|i| i.0).collect::>() }); + if skipped > 0 { + out["skipped"] = json!(skipped); + } + Ok(out) +} + +/// What [`shape_around`] finds. +enum Around { + Shape(LiveShape), + /// The objects have no bounds or no outline. + NoOutline, + /// The rectangle would have no width or no height, or the circle no radius. + NoSize, + /// An edge of the shape would lie more than [`MAX_COORD`](crate::MAX_COORD) from the origin + /// along either axis. + PastCanvas, +} + +/// The live rectangle or circle around `ids`, grown by `offset`. A circle halves its curves as +/// `splits` allows. +fn shape_around(d: &Document, symbols: &SymbolBoxes, ids: &[NodeId], kind: Kind, offset: f64, splits: Splits) -> Around { + match kind { + Kind::Rectangle => { + let Some(r) = d.bounds_of_with(ids, false, symbols) else { return Around::NoOutline }; + let r = r.inflate(offset, offset); + if !rect_in_range(r) { + return Around::PastCanvas; + } + if r.width() <= 0.0 || r.height() <= 0.0 { + return Around::NoSize; + } + Around::Shape(LiveShape::Rectangle { + w: r.width(), + h: r.height(), + radii: [0.0; 4], + kinds: Default::default(), + radii_relative: false, + xf: Affine::translate(r.origin().to_vec2()), + }) + } + Kind::Circle => { + let mut gathered = Gathered::new(); + gathered.splits = splits; + for n in ids.iter().filter_map(|id| d.node(*id)) { + outline_points(n, symbols, &mut gathered, 0); + gathered.compact(); + } + let Some((center, radius)) = shapes::enclosing_circle(&gathered.points) else { return Around::NoOutline }; + if radius + offset <= 0.0 { + return Around::NoSize; + } + let r = radius + FLATNESS + offset; + let b = Rect::new(center.x - r, center.y - r, center.x + r, center.y + r); + if !rect_in_range(b) { + return Around::PastCanvas; + } + Around::Shape(LiveShape::Ellipse { w: b.width(), h: b.height(), pie: (0.0, 360.0), xf: Affine::translate(b.origin().to_vec2()) }) + } + } +} + +/// Adds to `out` points on the outline of `n`, as its geometric bounds measure it: the points of +/// its paths ([`curve_points`]); the clipping path of a clip group or of a sublayer that clips its +/// contents; the shown contents of a sublayer (a layer that an opened file put inside a group); the +/// corners of an image; and the corners of the geometric bounding box of anything else. A group or +/// layer `depth` levels below the selected object that is nested deeper than a document holds +/// ([`vectorcraft_doc::MAX_DEPTH`]) counts by the corners of its geometric bounding box. +fn outline_points(n: &Node, symbols: &SymbolBoxes, out: &mut Gathered, depth: usize) { + let nests = matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. } | NodeKind::Compound { .. }); + if nests && depth >= vectorcraft_doc::MAX_DEPTH { + out.points.extend(n.geometric_bounds_with(symbols).map(corners).into_iter().flatten()); + return; + } + match &n.kind { + NodeKind::Path { path, .. } => { + // The anchors count too, so a path of one anchor, which has no segments, is held. + for p in path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)) { + out.points.push(p); + out.compact(); + } + for seg in path.to_bezpath().segments() { + match seg { + PathSeg::Line(l) => out.points.extend([l.p0, l.p1]), + _ => curve_points(seg.to_cubic(), 0, &mut out.points, &mut out.splits), + } + out.compact(); + } + } + NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => { + if let Some(c) = children.first() { + outline_points(c, symbols, out, depth + 1); + } + } + NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. } => { + let layer = matches!(n.kind, NodeKind::Layer { .. }); + for c in n.editing_children().iter().filter(|c| c.visible || !layer) { + outline_points(c, symbols, out, depth + 1); + out.compact(); + } + } + NodeKind::Image(im) => { + let r = Rect::new(0.0, 0.0, im.width as f64, im.height as f64); + out.points.extend(corners(r).map(|p| im.xf * p)); + } + _ => out.points.extend(n.geometric_bounds_with(symbols).map(corners).into_iter().flatten()), + } +} + +/// Adds to `out` points whose convex hull, grown by [`FLATNESS`], holds the curve `c`: the ends of +/// pieces whose control points lie within [`FLATNESS`] of their chord, and for pieces still curved +/// after [`MAX_SPLITS`] halvings, or when `splits` allows no more ([`Splits::take`]), the corners of +/// [`held`]. A flat piece that ends where it starts adds its control points too, so a small loop is +/// not taken for a single point. A curve with a point that is not finite adds nothing. +fn curve_points(c: CubicBez, depth: u32, out: &mut Vec, splits: &mut Splits) { + if ![c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.is_finite()) { + return; + } + let flat = [c.p1, c.p2].iter().all(|p| distance_to_segment(*p, c.p0, c.p3) <= FLATNESS); + if flat { + out.extend([c.p0, c.p3]); + if c.p0 == c.p3 { + out.extend([c.p1, c.p2]); + } + } else if depth >= MAX_SPLITS || !splits.take(depth) { + out.extend(held(c)); + } else { + let (a, b) = c.subdivide(); + curve_points(a, depth + 1, out, splits); + curve_points(b, depth + 1, out, splits); + } +} + +/// The corners of the convex hull of `c`'s control points cut down to `c`'s bounding box. Each of +/// the two holds the curve, so the part they share holds it too. When the cut leaves nothing, which +/// rounding can cause, it gives the box's corners. +fn held(c: CubicBez) -> Vec { + let b = ParamCurveExtrema::bounding_box(&c); + let mut poly = shapes::convex_hull(vec![c.p0, c.p1, c.p2, c.p3]); + for (x, bound, below) in [(true, b.x0, false), (true, b.x1, true), (false, b.y0, false), (false, b.y1, true)] { + poly = clip(&poly, x, bound, below); + } + if poly.is_empty() { corners(b).to_vec() } else { poly } +} + +/// The convex polygon `poly` cut at `bound` on the x axis (`x`) or the y axis: the part at or below +/// `bound` when `below`, else at or above it. +fn clip(poly: &[Point], x: bool, bound: f64, below: bool) -> Vec { + let v = |p: Point| if x { p.x } else { p.y }; + let inside = |p: Point| if below { v(p) <= bound } else { v(p) >= bound }; + let mut out = vec![]; + for (&a, &b) in poly.iter().zip(poly.iter().cycle().skip(1)) { + if inside(a) { + out.push(a); + } + if inside(a) != inside(b) { + let mut p = a.lerp(b, (bound - v(a)) / (v(b) - v(a))); + if x { + p.x = bound; + } else { + p.y = bound; + } + out.push(p); + } + } + out +} + +/// How many halvings [`curve_points`] makes for one command, over every curve it measures, before +/// it halves each further curve [`MIN_SPLITS`] times only; with `each`, every shape gets an equal +/// share ([`split_share`]). +const TOTAL_SPLITS: usize = 1 << 20; + +/// How many more halvings [`curve_points`] makes for one command once [`TOTAL_SPLITS`] is used up, +/// each within the first [`MIN_SPLITS`] halvings of a curve; with `each`, shared as +/// [`TOTAL_SPLITS`] is. After that, curves count by [`held`] whole. +const EARLY_SPLITS: usize = 7 << 20; + +/// How many times [`curve_points`] halves a curve once [`TOTAL_SPLITS`] is used up: 8 pieces, which +/// keeps the circle fitted to a circle of four curves less than 0.3% larger than that circle. +const MIN_SPLITS: u32 = 3; + +/// The halvings [`curve_points`] may still make. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Splits { + /// Halvings at any depth. + any: usize, + /// Halvings within the first [`MIN_SPLITS`] of a curve, once `any` is used up. + early: usize, +} + +impl Splits { + /// Takes one halving of a piece `depth` halvings into its curve; false when none is left. + fn take(&mut self, depth: u32) -> bool { + if self.any > 0 { + self.any -= 1; + } else if depth < MIN_SPLITS && self.early > 0 { + self.early -= 1; + } else { + return false; + } + true + } +} + +/// The halvings each of `shapes` shapes may make: an equal share of [`TOTAL_SPLITS`] and of +/// [`EARLY_SPLITS`]. +fn split_share(shapes: usize) -> Splits { + let n = shapes.max(1); + Splits { any: TOTAL_SPLITS / n, early: EARLY_SPLITS / n } +} + +/// How many points [`outline_points`] gathers before it keeps only the corners of their convex hull. +const COMPACT_AT: usize = 1 << 16; + +/// Points gathered for a circle, kept down to the corners of their convex hull whenever they grow +/// past `limit`: only the hull decides the circle. The points held stay within about twice the +/// hull's corners, and grow only with the anchors and objects measured and the halvings +/// ([`TOTAL_SPLITS`] and [`EARLY_SPLITS`]). +struct Gathered { + points: Vec, + limit: usize, + /// The halvings [`curve_points`] may still make (one shape's whole share at first). + splits: Splits, +} + +impl Gathered { + fn new() -> Self { + Self { points: vec![], limit: COMPACT_AT, splits: split_share(1) } + } + + /// Keeps only the hull's corners once there are more than `limit` points; the next time waits + /// until there are twice as many as the hull has, so each point is sorted a few times at most. + fn compact(&mut self) { + if self.points.len() > self.limit { + self.points = shapes::convex_hull(std::mem::take(&mut self.points)); + self.limit = (self.points.len() * 2).max(COMPACT_AT); + } + } +} + +/// How many times [`curve_points`] halves a curve at most: up to 1,024 pieces. +const MAX_SPLITS: u32 = 10; + +/// The distance from `p` to the segment from `a` to `b`. +fn distance_to_segment(p: Point, a: Point, b: Point) -> f64 { + let ab = b - a; + let len2 = ab.hypot2(); + let t = if len2 > 0.0 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 }; + (p - (a + ab * t)).hypot() +} + +fn corners(r: Rect) -> [Point; 4] { + [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)] +} diff --git a/crates/engine/src/cmd/addons/pathtools/bounding/tests.rs b/crates/engine/src/cmd/addons/pathtools/bounding/tests.rs new file mode 100644 index 0000000000..15d037aee3 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/bounding/tests.rs @@ -0,0 +1,557 @@ +//! Add Bounding Rectangle and Add Bounding Circle: the box and the smallest circle, the current +//! paint and placement on top of the current layer or the isolated group, `each` and `skipped`, +//! shapes of no size, clip groups and clipping sublayers, paths of compound paths, huge curves and +//! small loops, and the errors that leave the document as it was. + +use serde_json::{Value, json}; +use vectorcraft_doc::{LiveShape, Node, NodeId, NodeKind}; +use vectorcraft_geom::{CubicBez, Point, Rect, Vec2, shapes}; + +use super::{CIRCLE, COMPACT_AT, Gathered, RECTANGLE, Splits}; +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).unwrap().clone() +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn ids_of(v: &Value) -> Vec { + v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()) +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn object_count(s: &Session) -> usize { + let mut n = 0; + s.doc().unwrap().doc.walk(|_| n += 1); + n +} + +/// Whether two rectangles agree to within `tol` on every edge. +fn rect_near(b: Rect, want: Rect, tol: f64) -> bool { + [(b.x0, want.x0), (b.y0, want.y0), (b.x1, want.x1), (b.y1, want.y1)].iter().all(|(a, w)| (a - w).abs() < tol) +} + +/// The live shape of `id`. +fn live(s: &Session, id: NodeId) -> LiveShape { + match &node(s, id).kind { + NodeKind::Path { live: Some(live), .. } => live.as_ref().clone(), + other => panic!("not a live shape: {other:?}"), + } +} + +/// The geometric bounds of `id`. +fn bounds(s: &Session, id: NodeId) -> Rect { + s.doc().unwrap().doc.bounds_of(&[id], false).unwrap() +} + +/// The last child of `parent`, the top of its stacking order. +fn top_of(s: &Session, parent: NodeId) -> NodeId { + node(s, parent).children().unwrap().last().unwrap().id +} + +/// Runs `command` with `p` and checks that it fails and leaves the document as it was. +fn refused(s: &mut Session, command: &str, p: Value) -> String { + let (undo, objects) = (undo_len(s), object_count(s)); + let e = s.execute(command, &p).unwrap_err().to_string(); + assert_eq!((undo_len(s), object_count(s)), (undo, objects), "{p} changed the document"); + e +} + +/// A live rectangle on the selection's geometric bounding box, strokes left out, with the current +/// paint, on top of the current layer, selected; one undo removes it. +#[test] +fn a_bounding_rectangle_is_the_geometric_box_on_top_of_the_layer() { + let mut s = session(); + s.execute("stroke.set", &json!({"weight": 10})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let b = id_of(&s.execute("shape.ellipse", &json!({"x": 100, "y": 50, "width": 60, "height": 80})).unwrap()); + assert_eq!(node(&s, a).appearance.stroke_width(), 10.0, "the strokes reach past the geometric box"); + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let (before, undo) = (object_count(&s), undo_len(&s)); + let out = s.execute(RECTANGLE, &json!({})).unwrap(); + let id = id_of(&out); + assert_eq!(ids_of(&out), vec![id]); + assert!(out.get("skipped").is_none(), "{out}"); + assert!(matches!(live(&s, id), LiveShape::Rectangle { .. })); + assert!(rect_near(bounds(&s, id), Rect::new(10.0, 20.0, 160.0, 130.0), 1e-9), "{:?}", bounds(&s, id)); + let layer = s.doc().unwrap().current_layer().unwrap(); + assert_eq!(top_of(&s, layer), id); + assert_eq!(s.doc().unwrap().selection.objects, vec![id]); + assert_eq!(undo_len(&s), undo + 1); + assert_eq!(object_count(&s), before + 1); + // The current paint, as a shape drawn now gets it. + let reference = rect(&mut s, 300.0, 300.0, 5.0, 5.0); + let (n, r) = (node(&s, id), node(&s, reference)); + assert_eq!((n.appearance.fill_paint(), n.appearance.stroke_paint()), (r.appearance.fill_paint(), r.appearance.stroke_paint())); + assert_eq!(n.appearance.stroke_width(), r.appearance.stroke_width()); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(object_count(&s), before); +} + +/// A bounding circle around a right triangle stands on its hypotenuse; around a circle it is that +/// circle, grown by at most the flattening allowance; `offset` grows the radius, and a rectangle's +/// sides, by that much. +#[test] +fn a_bounding_circle_is_the_smallest_circle_around_the_outlines() { + let mut s = session(); + let tri = + id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 80, "y": 0}, {"x": 0, "y": 60}], "closed": true})).unwrap()); + s.execute("select.set", &json!({"ids": [tri.0]})).unwrap(); + let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap()); + match live(&s, c) { + LiveShape::Ellipse { w, h, pie, .. } => { + assert!((w - 100.02).abs() < 1e-9 && (h - 100.02).abs() < 1e-9 && pie == (0.0, 360.0), "{w} {h}"); + } + other => panic!("not a circle: {other:?}"), + } + assert!(rect_near(bounds(&s, c), Rect::new(-10.01, -20.01, 90.01, 80.01), 1e-9), "{:?}", bounds(&s, c)); + + // A circle of radius 50 and a dot inside it: the bounding circle is the circle itself. + let round = id_of(&s.execute("shape.ellipse", &json!({"x": 200, "y": 200, "width": 100, "height": 100})).unwrap()); + let dot = rect(&mut s, 240.0, 240.0, 2.0, 2.0); + s.execute("select.set", &json!({"ids": [round.0, dot.0]})).unwrap(); + let c = id_of(&s.execute(CIRCLE, &json!({"offset": 5})).unwrap()); + let got = bounds(&s, c); + let want = Rect::new(195.0, 195.0, 305.0, 305.0); + assert!(rect_near(got, want, 0.03), "{got:?}"); + assert!(got.x0 <= want.x0 + 1e-9 && got.x1 >= want.x1 - 1e-9 && got.y0 <= want.y0 + 1e-9 && got.y1 >= want.y1 - 1e-9, "{got:?}"); + + s.execute("select.set", &json!({"ids": [tri.0]})).unwrap(); + let r = id_of(&s.execute(RECTANGLE, &json!({"offset": 4})).unwrap()); + assert!(rect_near(bounds(&s, r), Rect::new(-4.0, -4.0, 84.0, 64.0), 1e-9)); +} + +/// A shape with no size is not drawn: a straight horizontal line gets no rectangle and a path of +/// one anchor no circle, unless `offset` gives them room; with `each` they are counted in +/// `skipped`, and alone they are an error. +#[test] +fn shapes_of_no_size_are_skipped_unless_offset_gives_them_room() { + let mut s = session(); + let line = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 10, "y": 50}, {"x": 90, "y": 50}]})).unwrap()); + let lone = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 50, "y": 70}]})).unwrap()); + let box_ = rect(&mut s, 200.0, 200.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [line.0]})).unwrap(); + assert!(refused(&mut s, RECTANGLE, json!({})).contains("the shape would have no size")); + let r = id_of(&s.execute(RECTANGLE, &json!({"offset": 2})).unwrap()); + assert!(rect_near(bounds(&s, r), Rect::new(8.0, 48.0, 92.0, 52.0), 1e-9), "{:?}", bounds(&s, r)); + // The line has length, so its circle has size. + s.execute("select.set", &json!({"ids": [line.0]})).unwrap(); + let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap()); + assert!(rect_near(bounds(&s, c), Rect::new(9.99, 9.99, 90.01, 90.01), 1e-9), "{:?}", bounds(&s, c)); + + s.execute("select.set", &json!({"ids": [lone.0]})).unwrap(); + assert!(refused(&mut s, CIRCLE, json!({})).contains("the shape would have no size")); + let c = id_of(&s.execute(CIRCLE, &json!({"offset": 3})).unwrap()); + assert!(rect_near(bounds(&s, c), Rect::new(46.99, 66.99, 53.01, 73.01), 1e-9), "{:?}", bounds(&s, c)); + + s.execute("select.set", &json!({"ids": [line.0, lone.0, box_.0]})).unwrap(); + let out = s.execute(RECTANGLE, &json!({"each": true})).unwrap(); + assert_eq!((ids_of(&out).len(), out["skipped"].as_u64()), (1, Some(2)), "{out}"); + assert!(rect_near(bounds(&s, id_of(&out)), Rect::new(200.0, 200.0, 210.0, 210.0), 1e-9)); + s.execute("select.set", &json!({"ids": [line.0, lone.0, box_.0]})).unwrap(); + let out = s.execute(CIRCLE, &json!({"each": true})).unwrap(); + assert_eq!((ids_of(&out).len(), out["skipped"].as_u64()), (2, Some(1)), "{out}"); +} + +/// With `each`, every selected object gets a shape of its own, all in one undo step, on top of the +/// layer in the selection's stacking order, and the new shapes are selected. +#[test] +fn each_draws_one_shape_around_each_object() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 100.0, 0.0, 20.0, 30.0); + s.execute("select.set", &json!({"ids": [b.0, a.0]})).unwrap(); + let undo = undo_len(&s); + let out = s.execute(RECTANGLE, &json!({"each": true})).unwrap(); + let ids = ids_of(&out); + assert_eq!(ids.len(), 2); + assert!(rect_near(bounds(&s, ids[0]), Rect::new(0.0, 0.0, 10.0, 10.0), 1e-9)); + assert!(rect_near(bounds(&s, ids[1]), Rect::new(100.0, 0.0, 120.0, 30.0), 1e-9)); + let layer = s.doc().unwrap().current_layer().unwrap(); + let order: Vec = node(&s, layer).children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(order, vec![a, b, ids[0], ids[1]]); + assert_eq!(s.doc().unwrap().selection.objects.len(), 2); + assert_eq!(undo_len(&s), undo + 1); +} + +/// An object with no outline (an empty group) gets no shape and the result counts it; with only +/// such objects selected the command draws nothing. +#[test] +fn each_counts_the_objects_without_an_outline() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let empty = s + .edit("Group", |d, _| { + let id = d.alloc_id(); + d.insert(d.default_layer(), 0, Node::group(id, vec![]))?; + Ok(id) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [a.0, empty.0]})).unwrap(); + let out = s.execute(CIRCLE, &json!({"each": true})).unwrap(); + assert_eq!((ids_of(&out).len(), out["skipped"].as_u64()), (1, Some(1)), "{out}"); + s.execute("select.set", &json!({"ids": [a.0, empty.0]})).unwrap(); + let out = s.execute(CIRCLE, &json!({})).unwrap(); + assert!(out.get("skipped").is_none(), "{out}"); + s.execute("select.set", &json!({"ids": [empty.0]})).unwrap(); + assert!(refused(&mut s, RECTANGLE, json!({"each": true})).contains("nothing to enclose")); +} + +/// Curves over a hundred thousand points across are held by their circle: every point along the +/// curves is inside the circle, whose radius is the 0.01 pt allowance larger than the circle around +/// the flattened points. The farthest point of the lopsided arc lies between two flattened points, +/// about 0.001 pt outside the circle around them, so it needs that allowance. +#[test] +fn the_circle_holds_huge_curves() { + let mut s = session(); + let d = "M 0 0 C 0 -90000 120000 -90000 120000 0 C 60000 40000 30000 70000 0 0 Z"; + let blob = id_of(&s.execute("path.create", &json!({"d": d})).unwrap()); + let arc = id_of(&s.execute("path.create", &json!({"d": "M 0 0 C 20 400 380 500 400 0"})).unwrap()); + for big in [blob, arc] { + s.execute("select.set", &json!({"ids": [big.0]})).unwrap(); + let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap()); + let LiveShape::Ellipse { w, xf, .. } = live(&s, c) else { panic!("not a circle") }; + let (center, r) = (xf * Point::new(w / 2.0, w / 2.0), w / 2.0); + let path = node(&s, big).path_data().unwrap().to_bezpath(); + let mut farthest: f64 = 0.0; + for seg in path.segments() { + for i in 0..=4000 { + let p = vectorcraft_geom::ParamCurve::eval(&seg, f64::from(i) / 4000.0); + farthest = farthest.max(p.distance(center)); + } + } + assert!(farthest <= r + 1e-6, "a point {farthest} from the center is outside the circle of radius {r}"); + } +} + +/// Clip groups count by their clipping paths; for art inside one, the shape goes on top of the +/// current layer, never into the clip group. +#[test] +fn clip_groups_count_by_their_clipping_paths() { + let mut s = session(); + let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let clip = id_of(&s.execute("shape.ellipse", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()); + s.execute("select.set", &json!({"ids": [art.0, clip.0]})).unwrap(); + let group = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap()); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + let id = id_of(&s.execute(CIRCLE, &json!({})).unwrap()); + let b = bounds(&s, id); + assert!((b.width() / 2.0 - 25.01).abs() < 0.03 && b.center().distance(Point::new(35.0, 35.0)) < 0.03, "{b:?}"); + let layer = s.doc().unwrap().current_layer().unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(layer)); + s.execute("select.set", &json!({"ids": [clip.0]})).unwrap(); + let id = id_of(&s.execute(RECTANGLE, &json!({})).unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(layer)); + assert!(rect_near(bounds(&s, id), Rect::new(10.0, 10.0, 60.0, 60.0), 1e-6)); +} + +/// A sublayer that clips its contents counts by its clipping path, and the hidden objects of a +/// sublayer are left out; a sublayer inside a selected group (as an opened file can put one there) +/// counts the same way. +#[test] +fn sublayers_count_by_their_clipping_path_and_shown_art() { + let mut s = session(); + let top = s.doc().unwrap().current_layer().unwrap(); + let sub = id_of(&s.execute("layer.newSublayer", &json!({"parent": top.0})).unwrap()); + s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap(); + let art = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let hidden = rect(&mut s, 300.0, 300.0, 10.0, 10.0); + assert_eq!(s.doc().unwrap().doc.parent_of(art), Some(sub), "the art is in the sublayer"); + s.execute("select.set", &json!({"ids": [hidden.0]})).unwrap(); + s.execute("object.hide", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + let (sub_node, symbols) = (d.node(sub).unwrap().clone(), d.symbol_boxes()); + let mut g = Gathered::new(); + super::outline_points(&sub_node, &symbols, &mut g, 0); + let (center, r) = shapes::enclosing_circle(&g.points).unwrap(); + assert!(center.distance(Point::new(50.0, 50.0)) < 1e-9 && (r - 50.0 * 2f64.sqrt()).abs() < 1e-9, "{center:?} {r}"); + + // The top object of the sublayer becomes its clipping path. + s.execute("select.none", &json!({})).unwrap(); + let clip = rect(&mut s, 20.0, 20.0, 10.0, 10.0); + assert_eq!(s.doc().unwrap().doc.parent_of(clip), Some(sub)); + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("layer.clippingMask.toggle", &json!({"id": sub.0})).unwrap()["clip"].as_bool().unwrap()); + let d = &s.doc().unwrap().doc; + let sub_node = d.node(sub).unwrap().clone(); + let mut g = Gathered::new(); + super::outline_points(&sub_node, &d.symbol_boxes(), &mut g, 0); + let (center, r) = shapes::enclosing_circle(&g.points).unwrap(); + assert!(center.distance(Point::new(25.0, 25.0)) < 1e-9 && (r - 5.0 * 2f64.sqrt()).abs() < 1e-9, "{center:?} {r}"); + + let group = s + .edit("Group", |d, _| { + let layer = d.remove(sub)?; + let id = d.alloc_id(); + d.insert(Some(top), usize::MAX, Node::group(id, vec![layer]))?; + Ok(id) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap()); + let b = bounds(&s, c); + assert!(b.center().distance(Point::new(25.0, 25.0)) < 1e-9 && (b.width() / 2.0 - (5.0 * 2f64.sqrt() + 0.01)).abs() < 1e-9, "{b:?}"); +} + +/// A path of a compound path selected on its own is an object, as `object.transform` moves it: +/// the shape goes around that path only, and with `each` each selected path gets a shape. The +/// compound path selected whole is one object. +#[test] +fn a_path_of_a_compound_path_selected_on_its_own_is_an_object() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 10.0, 10.0); + let b = rect(&mut s, 120.0, 100.0, 10.0, 20.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + let members: Vec = node(&s, compound).children().unwrap().iter().map(|n| n.id).collect(); + assert_eq!(members.len(), 2); + for kind in [RECTANGLE, CIRCLE] { + s.execute("select.set", &json!({"ids": [members[0].0]})).unwrap(); + let id = id_of(&s.execute(kind, &json!({})).unwrap()); + let (got, want) = (bounds(&s, id), bounds(&s, members[0])); + if kind == RECTANGLE { + assert!(rect_near(got, want, 1e-9), "{got:?} on {want:?}"); + } else { + let d = want.width().hypot(want.height()) + 0.02; + assert!(got.center().distance(want.center()) < 1e-9 && (got.width() - d).abs() < 1e-9, "{got:?} around {want:?}"); + } + s.execute("select.set", &json!({"ids": [members[0].0, members[1].0]})).unwrap(); + assert_eq!(ids_of(&s.execute(kind, &json!({"each": true})).unwrap()).len(), 2, "{kind}"); + s.execute("select.set", &json!({"ids": [compound.0]})).unwrap(); + assert_eq!(ids_of(&s.execute(kind, &json!({"each": true})).unwrap()).len(), 1, "{kind}"); + } +} + +/// A small closed curve whose handles lie within the 0.01 pt allowance of its one anchor is not a +/// single point: it gets a circle. +#[test] +fn a_small_loop_gets_a_circle() { + let mut s = session(); + let lp = id_of(&s.execute("path.create", &json!({"d": "M 0 0 C 0.005 0 0 0.005 0 0"})).unwrap()); + s.execute("select.set", &json!({"ids": [lp.0]})).unwrap(); + let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap()); + let LiveShape::Ellipse { w, .. } = live(&s, c) else { panic!("not a circle") }; + assert!(w > 0.02, "{w}"); +} + +/// Once the command has used up both kinds of halvings, a curve counts by its control points' hull +/// cut down to its bounding box: the points stay inside both and reach no farther than the curve +/// along either axis, while its handles may. +#[test] +fn a_curve_past_the_halvings_counts_by_its_hull_inside_its_bounding_box() { + // With nothing left, `curve_points` takes no halving, so `none` stays as it is. + let mut none = Splits { any: 0, early: 0 }; + let c = CubicBez::new((0.0, 0.0), (20.0, 400.0), (380.0, 500.0), (400.0, 0.0)); + let b = vectorcraft_geom::kurbo::ParamCurveExtrema::bounding_box(&c); + let mut out = vec![]; + super::curve_points(c, 0, &mut out, &mut none); + assert!(out.len() >= 4 && out.iter().all(|p| b.inflate(1e-9, 1e-9).contains(*p)), "{out:?} in {b:?}"); + assert!(out.iter().any(|p| (p.y - b.y1).abs() < 1e-9), "the curve's lowest point is reached: {out:?}"); + let (center, r) = shapes::enclosing_circle(&out).unwrap(); + for i in 0..=1000 { + let p = vectorcraft_geom::ParamCurve::eval(&c, f64::from(i) / 1000.0); + assert!(p.distance(center) <= r + 1e-9, "{p:?} outside"); + } + // The handle at x = 4,000,000 stays out: the curve reaches x = 16,000,000 / 9. + let reach = CubicBez::new((0.0, 0.0), (4.0e6, 0.0), (0.0, 0.0), (0.0, 0.0)); + out.clear(); + super::curve_points(reach, 0, &mut out, &mut none); + let far = out.iter().map(|p| p.x).fold(0.0, f64::max); + assert!((far - 16.0e6 / 9.0).abs() < 1e-6, "{far}"); + out.clear(); + let mut splits = Splits { any: 3, early: 0 }; + super::curve_points(c, 0, &mut out, &mut splits); + assert_eq!(splits, Splits { any: 0, early: 0 }); + assert!(out.len() > 4, "{out:?}"); +} + +/// The circle fitted to a circle of four curves: less than 0.3% larger with only the early halvings +/// left, and up to about 14% larger by the curves' hulls once those are used up too. +#[test] +fn a_circle_measured_past_the_halvings_stays_close() { + let fitted = |mut splits: Splits| { + let circle = shapes::ellipse(Rect::new(-100.0, -100.0, 100.0, 100.0)).to_bezpath(); + let mut out = vec![]; + for seg in circle.segments() { + super::curve_points(seg.to_cubic(), 0, &mut out, &mut splits); + } + shapes::enclosing_circle(&out).unwrap() + }; + let (center, r) = fitted(Splits { any: 0, early: 1000 }); + assert!(center.to_vec2().hypot() < 0.1 && (100.0..100.3).contains(&r), "{center:?} {r}"); + let (_, r) = fitted(Splits { any: 0, early: 0 }); + assert!((110.0..115.0).contains(&r), "{r}"); +} + +/// Past the halvings at any depth, only the first [`super::MIN_SPLITS`] halvings of a curve take +/// from the early ones; with `each`, every shape gets an equal share of both. +#[test] +fn early_halvings_are_taken_near_the_start_of_a_curve_and_shared() { + let mut s = Splits { any: 1, early: 1 }; + assert!(s.take(super::MIN_SPLITS + 1)); + assert!(!s.take(super::MIN_SPLITS)); + assert!(s.take(0)); + assert!(!s.take(0)); + let whole = Splits { any: super::TOTAL_SPLITS, early: super::EARLY_SPLITS }; + assert_eq!(super::split_share(0), whole); + assert_eq!(super::split_share(1), whole); + assert_eq!(super::split_share(4), Splits { any: super::TOTAL_SPLITS / 4, early: super::EARLY_SPLITS / 4 }); +} + +/// In an isolated group the shape goes on top of the group's art; in an isolated compound path it +/// goes beside the compound path, never into it. +#[test] +fn shapes_go_into_an_isolated_group_but_not_an_isolated_compound_path() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let group = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": group.0})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let id = id_of(&s.execute(RECTANGLE, &json!({})).unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(group)); + assert_eq!(top_of(&s, group), id); + s.execute("object.exitIsolation", &json!({})).unwrap(); + + let c = rect(&mut s, 100.0, 100.0, 10.0, 10.0); + let e = rect(&mut s, 120.0, 100.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [c.0, e.0]})).unwrap(); + let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": compound.0})).unwrap(); + let members: Vec = node(&s, compound).children().unwrap().iter().map(|n| n.id.0).collect(); + s.execute("select.set", &json!({"ids": members})).unwrap(); + let id = id_of(&s.execute(CIRCLE, &json!({})).unwrap()); + let d = &s.doc().unwrap().doc; + assert_ne!(d.parent_of(id), Some(compound), "the circle does not join the compound path"); + assert_eq!(d.parent_of(id), d.parent_of(compound)); + assert_eq!(node(&s, compound).children().unwrap().len(), 2); +} + +/// An offset or each that is not one the commands take is an error, and nothing is drawn; with +/// nothing selected the commands are not available. +#[test] +fn bad_params_and_an_empty_selection_draw_nothing() { + let mut s = session(); + assert!(s.execute(RECTANGLE, &json!({})).is_err(), "nothing selected"); + assert!(s.execute(CIRCLE, &json!({})).is_err(), "nothing selected"); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + for command in [RECTANGLE, CIRCLE] { + for p in [json!({"offset": -1}), json!({"offset": "5"}), json!({"each": "yes"})] { + refused(&mut s, command, p); + } + assert!(refused(&mut s, command, json!({"offset": -1})).contains("`offset` must be 0 or more")); + } +} + +/// An offset that would put an edge of the shape more than 4,000,000 pt from the origin along +/// either axis is an error that names the canvas edge, and nothing is drawn; the largest offsets +/// that stay inside are drawn, for the rectangle and for the circle. +#[test] +fn an_offset_past_the_canvas_edge_draws_nothing() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + for command in [RECTANGLE, CIRCLE] { + for offset in [1e308, 4.0e6] { + let e = refused(&mut s, command, json!({ "offset": offset })); + assert!(e.contains("the shape would reach past the edge of the canvas"), "{command} {offset}: {e}"); + } + } + let r = id_of(&s.execute(RECTANGLE, &json!({"offset": 3.99e6})).unwrap()); + assert!(rect_near(bounds(&s, r), Rect::new(-3.99e6, -3.99e6, 3.99e6 + 10.0, 3.99e6 + 10.0), 1e-3)); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let c = id_of(&s.execute(CIRCLE, &json!({"offset": 3.99e6})).unwrap()); + // The circle around the square from (0, 0) to (10, 10), 0.01 pt larger, then the offset. + let radius = 50.0f64.sqrt() + 0.01 + 3.99e6; + assert!(rect_near(bounds(&s, c), Rect::new(5.0 - radius, 5.0 - radius, 5.0 + radius, 5.0 + radius), 1e-3)); +} + +/// The limit holds along each axis on its own: a shape whose right edge would pass 4,000,000 pt is +/// refused although its other edges, and its distance along the other axis, are small. +#[test] +fn one_edge_past_the_canvas_edge_is_enough_to_refuse() { + let mut s = session(); + let a = rect(&mut s, 3_999_980.0, 0.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + for command in [RECTANGLE, CIRCLE] { + let e = refused(&mut s, command, json!({"offset": 20})); + assert!(e.contains("the shape would reach past the edge of the canvas"), "{command}: {e}"); + } + assert!(s.execute(RECTANGLE, &json!({"offset": 5})).is_ok(), "the right edge at 3,999,995 pt is inside"); +} + +/// A large circle close to the canvas edge, whose arcs stay curved after the most halvings, gets a +/// circle within 0.05 pt of the farthest point of its curves, which stays inside the edge. +#[test] +fn a_large_circle_near_the_canvas_edge_gets_a_close_circle() { + let mut s = session(); + let e = id_of(&s.execute("shape.ellipse", &json!({"x": 3_799_950.0, "y": 0.0, "width": 200_000.0, "height": 200_000.0})).unwrap()); + s.execute("select.set", &json!({"ids": [e.0]})).unwrap(); + let c = id_of(&s.execute(CIRCLE, &json!({})).unwrap()); + let LiveShape::Ellipse { w, xf, .. } = live(&s, c) else { panic!("not a circle") }; + let center = xf * Point::new(w / 2.0, w / 2.0); + let mut farthest: f64 = 0.0; + for seg in node(&s, e).path_data().unwrap().to_bezpath().segments() { + for i in 0..=4000 { + farthest = farthest.max(vectorcraft_geom::ParamCurve::eval(&seg, f64::from(i) / 4000.0).distance(center)); + } + } + assert!(w / 2.0 >= farthest && w / 2.0 < farthest + 0.05, "radius {} for curves reaching {farthest}", w / 2.0); +} + +/// The commands are dimmed while an object of a symbol instance's art is selected, which they +/// refuse, and available again once it is not. +#[test] +fn a_selected_symbol_part_dims_the_commands() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let enabled = |s: &Session, id: &str| (crate::find_command(id).unwrap().enabled)(s); + for command in [RECTANGLE, CIRCLE] { + assert!(enabled(&s, command).is_ok(), "{command}"); + } + s.doc_mut().unwrap().selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: a, path: vec![0] }); + for command in [RECTANGLE, CIRCLE] { + assert!(enabled(&s, command).is_err(), "{command} with a symbol part selected"); + } + s.doc_mut().unwrap().selection.symbol_part = None; + assert!(enabled(&s, RECTANGLE).is_ok()); +} + +/// Many points keep only their hull's corners, and the circle around them is the one around all +/// of the points. +#[test] +fn gathered_points_keep_their_hull_and_circle() { + let mut g = Gathered::new(); + let c = Point::new(500.0, 300.0); + for i in 0..200_000 { + let angle = f64::from(i) * 0.618; + let r = if i % 1000 == 0 { 250.0 } else { f64::from(i % 200) }; + g.points.push(c + Vec2::from_angle(angle) * r); + g.compact(); + } + assert!(g.points.len() <= COMPACT_AT + 1, "{} points kept", g.points.len()); + let (center, radius) = shapes::enclosing_circle(&g.points).unwrap(); + assert!(center.distance(c) < 1e-6 && (radius - 250.0).abs() < 1e-6, "{center:?} {radius}"); +} diff --git a/crates/engine/src/cmd/addons/pathtools/bridge.rs b/crates/engine/src/cmd/addons/pathtools/bridge.rs index 2120b040e7..4d4eb9cdf8 100644 --- a/crates/engine/src/cmd/addons/pathtools/bridge.rs +++ b/crates/engine/src/cmd/addons/pathtools/bridge.rs @@ -1,5 +1,6 @@ //! Smooth Bridge: two selected circles joined into one outline by two concave arcs that touch both -//! circles, replacing the circles or added above them. +//! circles, or three or more each joined the same way to the others within reach and united where +//! the bridges connect, replacing the circles or added above them. use serde_json::{Value, json}; use vectorcraft_doc::{NodeId, NodeKind}; @@ -20,6 +21,12 @@ const LABEL: &str = "Smooth Bridge"; /// The arcs' radius as a percentage of the smaller circle's radius: by default, and the range. const RADIUS: f64 = 100.0; const RADII: (f64, f64) = (1.0, 1000.0); +/// The gap (pt) added to the smaller circle's radius to give the arcs' radius: the range. +const GAPS: (f64, f64) = (0.0, 1000.0); +/// How far apart (pt) the outlines of two of three or more circles may be for a bridge between +/// them: by default, and the range. +const REACH: f64 = 10.0; +const REACHES: (f64, f64) = (0.0, 10000.0); pub(super) fn specs() -> Vec { vec![cmd!( @@ -27,16 +34,33 @@ pub(super) fn specs() -> Vec { "Smooth Bridge", ["Object", "Plug-ins", "Path Precision Tools"], None, - "{radius?: % 1..1000 (100; the radius of the bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), keepOriginals?: bool (false: the outline replaces the two circles, painted as the upper one; true: it goes directly above the upper one and the circles stay), ids?: [id, id] (default: the selection)} join two circles (paths whose outline is a circle, not hidden or locked) into one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. Overlapping and touching circles are joined too; one circle inside the other, or circles too far apart for the radius (the arcs would not reach both, or would cross), is an error, which suggests a larger radius when one up to 1000% would bridge them. One undo step; the outline is selected → {id}", + "{radius?: % 1..1000 (100; the radius of each bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), gap?: pt 0..1000 (instead of radius: the arcs' radius is the smaller circle's radius plus this gap, so each arc stays this gap away from a circle of the smaller circle's size about the arc's center; for equal circles this gap apart that is where a third circle this gap from both sits, as in a triangular grid, so the channels around an empty place in such a grid are one width; giving both is an error), reach?: pt 0..10000 (10; with three or more circles: how far apart two circles' outlines may be for a bridge between them, overlapping ones included; two circles are bridged at any distance), keepOriginals?: bool (false: each outline replaces its circles, painted as the topmost of them; true: it goes directly above that circle and the circles stay), ids?: [id] (default: the selection)} join circles (paths whose outline is a circle, not hidden or locked) into metaball (aka meatball) shapes. Two circles become one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. With three or more, every two circles within reach are bridged the same way, and the bridges that connect are united into one shape each (holes smaller than 1% of the smallest circle's area are filled); a pair within reach but too far apart for the radius gets no bridge, and so does one whose neck would be thinner than the precision its shape is united at, and a circle bridged to no other is left as it is. Overlapping and touching circles are joined too. One circle inside another (among three or more, any such pair within reach) is an error; so are two circles too far apart for the radius (the arcs would not reach both, or would cross), or three or more with no pair the arcs can join, which suggests a larger radius or gap when the largest one would bridge them; so are no two circles within reach, more than 2000 circles and more than 8000 bridges. One undo step; the outlines (and the circles left as they are) are selected → {ids, alone}, with {id} too for two circles", has_selection, bridge )] } fn bridge(s: &mut Session, p: &Value) -> Result { - let percent = given(p, "radius", Some(RADII), C)?.unwrap_or(RADIUS); + let percent = given(p, "radius", Some(RADII), C)?; + let gap = given(p, "gap", Some(GAPS), C)?; + let reach = given(p, "reach", Some(REACHES), C)?.unwrap_or(REACH); + if percent.is_some() && gap.is_some() { + // As the parameter check words it (`EXCLUSIVE_KEYS`), for a caller that skips that check. + let (key, other) = ("radius", "gap"); + return Err(bad(C, format!("give `{key}` or `{other}`, not both"))); + } + let arc = match gap { + Some(gap) => pt::ArcRadius::Gap(gap), + None => pt::ArcRadius::Share(percent.unwrap_or(RADIUS) / 100.0), + }; let keep = switch_or(p, "keepOriginals", false, C)?; - let roots = checked_ids_or_selection(s, p, C)?; + let mut roots = checked_ids_or_selection(s, p, C)?; + // An id given twice is one circle. + roots.sort_unstable(); + roots.dedup(); + if roots.len() > pt::MAX_BRIDGED_CIRCLES { + return Err(bad(C, "select at most 2000 circles to bridge")); + } let circles: Vec<(NodeId, pt::Circle)> = { let d = &s.doc()?.doc; let editable = d.editable(); @@ -48,48 +72,93 @@ fn bridge(s: &mut Session, p: &Value) -> Result { }) .collect() }; - let ([(below, a), (above, b)], 2) = (circles.as_slice(), roots.len()) else { - return Err(bad(C, "select two circles to bridge")); - }; - let (below, above) = (*below, *above); - let at = |percent: f64| pt::smooth_bridge(*a, *b, a.radius.min(b.radius) * percent / 100.0); - let outline = match at(percent) { - Ok(sp) => PathData::single(sp), - Err(pt::BridgeError::Inside) => return Err(bad(C, "one circle is inside the other")), - // A larger radius bridges circles a smaller one cannot, so only suggest one that is allowed. - Err(pt::BridgeError::TooFar) if at(RADII.1).is_ok() => { - return Err(bad(C, "the circles are too far apart for this radius: raise the radius")); + if circles.len() != roots.len() || circles.len() < 2 { + return Err(bad(C, "select two or more circles to bridge")); + } + let only: Vec = circles.iter().map(|(_, c)| *c).collect(); + // Each shape: the circles it joins, in paint order, and its outline. + let (shapes, alone): (Vec<(Vec, PathData)>, Vec) = match only.as_slice() { + [a, b] => match pt::smooth_bridge(*a, *b, arc.between(*a, *b)) { + Ok(sp) => (vec![(roots_of(&circles, &[0, 1]), PathData::single(sp))], vec![]), + Err(e) => return Err(refusal(e, arc, |largest| pt::smooth_bridge(*a, *b, largest.between(*a, *b)).is_ok())), + }, + _ => { + let made = pt::bridge_many(&only, arc, reach).map_err(|e| match e { + pt::ManyError::TooManyCircles => bad(C, "select at most 2000 circles to bridge"), + pt::ManyError::TooManyBridges => bad(C, "that makes too many bridges (at most 8000): lower the reach"), + pt::ManyError::NoneInReach => bad(C, "no two circles are within reach: raise the reach"), + pt::ManyError::TooComplex => bad(C, "the bridged circles are too complex to unite"), + // Under the many-circle rules: a pair the largest radius or gap bridges on its own + // can still have a neck too thin to unite among the others. + pt::ManyError::Pair(_, _, e) => refusal(e, arc, |largest| pt::bridges_any(&only, largest, reach)), + pt::ManyError::Bad => bad(C, "select two or more circles to bridge"), + })?; + let shapes = made.joined.into_iter().map(|j| (roots_of(&circles, &j.members), j.outline)).collect(); + (shapes, roots_of(&circles, &made.alone)) } - Err(pt::BridgeError::TooFar) => return Err(bad(C, "the circles are too far apart for this radius")), - Err(pt::BridgeError::Bad) => return Err(bad(C, "select two circles to bridge")), }; - let id = s.edit(LABEL, |d, sel| { - let id = if keep { - // A copy of the upper circle (its appearance) with the outline as its path, right above - // it; the circles stay as they are, live shapes included. - // Fresh ids throughout, its opacity mask's art included. - let upper = d.node(above).cloned().ok_or(EngineError::NoNode(above))?; - let mut n = d.reid(&upper); - if let NodeKind::Path { path, live, .. } = &mut n.kind { - *path = outline; - *live = None; + let made = s.edit(LABEL, |d, sel| { + let mut made = Vec::with_capacity(shapes.len()); + if keep { + // A copy of each shape's topmost circle (its appearance) with the outline as its path, + // right above it; the circles stay as they are, live shapes included. Fresh ids + // throughout, an opacity mask's art included. + let tops: Vec = shapes.iter().filter_map(|(members, _)| members.last().copied()).collect(); + let mut beside = Beside::above(d, &tops); + for ((_, outline), top) in shapes.into_iter().zip(tops) { + let upper = d.node(top).cloned().ok_or(EngineError::NoNode(top))?; + let mut n = d.reid(&upper); + if let NodeKind::Path { path, live, .. } = &mut n.kind { + *path = outline; + *live = None; + } + made.push(n.id); + beside.put(d, top, vec![n])?; } - let id = n.id; - let mut beside = Beside::above(d, &[above]); - beside.put(d, above, vec![n])?; beside.finish(d)?; - id } else { - // The upper circle becomes the outline (a plain path now) and the lower one goes. - if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(above).map(|n| &mut n.kind) { - *path = outline; - *live = None; + // Each shape's topmost circle becomes its outline (a plain path now) and the others go. + let mut gone = vec![]; + for (members, outline) in shapes { + let Some((&top, rest)) = members.split_last() else { continue }; + if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(top).map(|n| &mut n.kind) { + *path = outline; + *live = None; + } + made.push(top); + gone.extend_from_slice(rest); } - remove_each(d, &[below])?; - above - }; - sel.set([id]); - Ok(id) + remove_each(d, &gone)?; + } + sel.set(made.iter().chain(&alone).copied()); + Ok(made) })?; - Ok(json!({ "id": id.0 })) + let mut out = json!({ "ids": made.iter().map(|id| id.0).collect::>(), "alone": alone.iter().map(|id| id.0).collect::>() }); + if let ([id], 2) = (made.as_slice(), only.len()) { + out["id"] = json!(id.0); + } + Ok(out) +} + +/// The ids of `circles` at indices `at`, in paint order (the circles are listed in paint order). +fn roots_of(circles: &[(NodeId, pt::Circle)], at: &[usize]) -> Vec { + at.iter().filter_map(|&i| circles.get(i)).map(|(id, _)| *id).collect() +} + +/// The error for circles that arcs of `arc` can't bridge. A larger radius or gap bridges circles a +/// smaller one cannot, so it suggests one only when `bridges` says the largest allowed would. +fn refusal(e: pt::BridgeError, arc: pt::ArcRadius, bridges: impl FnOnce(pt::ArcRadius) -> bool) -> EngineError { + let largest = match arc { + pt::ArcRadius::Share(_) => pt::ArcRadius::Share(RADII.1 / 100.0), + pt::ArcRadius::Gap(_) => pt::ArcRadius::Gap(GAPS.1), + }; + let would = e == pt::BridgeError::TooFar && bridges(largest); + match (e, arc, would) { + (pt::BridgeError::Inside, ..) => bad(C, "one circle is inside the other"), + (pt::BridgeError::TooFar, pt::ArcRadius::Share(_), true) => bad(C, "the circles are too far apart for this radius: raise the radius"), + (pt::BridgeError::TooFar, pt::ArcRadius::Share(_), false) => bad(C, "the circles are too far apart for this radius"), + (pt::BridgeError::TooFar, pt::ArcRadius::Gap(_), true) => bad(C, "the circles are too far apart for this gap: raise the gap"), + (pt::BridgeError::TooFar, pt::ArcRadius::Gap(_), false) => bad(C, "the circles are too far apart for this gap"), + (pt::BridgeError::Bad, ..) => bad(C, "select two or more circles to bridge"), + } } diff --git a/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs index 01320c07c1..745f216b68 100644 --- a/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs @@ -1,5 +1,5 @@ -//! Smooth Bridge: the outline in place of the circles or above them, one undo step, the radius, -//! and what it refuses. +//! Smooth Bridge: the outline in place of the circles or above them, one undo step, the radius or +//! gap, many circles joined to their neighbors within reach, and what it refuses. use serde_json::{Value, json}; use vectorcraft_doc::{NodeId, NodeKind}; @@ -46,6 +46,8 @@ fn two_circles_become_one_outline_in_the_upper_ones_place() { let steps = s.doc().unwrap().history.undo.len(); let r = s.execute(BRIDGE, &json!({})).unwrap(); assert_eq!(r["id"], json!(b.0)); + assert_eq!(r["ids"], json!([b.0]), "the same result fields as for more circles"); + assert_eq!(r["alone"], json!([])); assert_eq!(top_level(&s), [b]); let d = &s.doc().unwrap().doc; let NodeKind::Path { path, live, .. } = &d.node(b).unwrap().kind else { panic!("a path") }; @@ -158,9 +160,11 @@ fn far_apart_nested_and_other_objects_are_refused() { assert!(e.ends_with("the circles are too far apart for this radius"), "{e}"); } assert!(err(&mut s, json!({"ids": [a.0, inner.0]})).contains("one circle is inside the other")); - for ids in [json!([a.0, square.0]), json!([a.0, oval.0]), json!([a.0]), json!([a.0, far.0, inner.0])] { - assert!(err(&mut s, json!({ "ids": ids })).contains("select two circles to bridge"), "{ids}"); + for ids in [json!([a.0, square.0]), json!([a.0, oval.0]), json!([a.0]), json!([a.0, far.0, square.0])] { + assert!(err(&mut s, json!({ "ids": ids })).contains("select two or more circles to bridge"), "{ids}"); } + // Three circles: each two within reach are bridged, and one inside another is refused there too. + assert!(err(&mut s, json!({"ids": [a.0, far.0, inner.0]})).contains("one circle is inside the other")); assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 0.5})).contains("`radius` must be from 1 to 1000")); assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 1001})).contains("`radius`")); assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": "big"})).contains("`radius` must be a number")); @@ -169,6 +173,174 @@ fn far_apart_nested_and_other_objects_are_refused() { assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step"); } +/// A 3 × 3 grid of circles of radius 10, 4 apart (centers 24 apart), in rows from (100, 100). +fn grid(s: &mut Session) -> Vec { + (0..9).map(|k| circle(s, 100.0 + 24.0 * (k % 3) as f64, 100.0 + 24.0 * (k / 3) as f64, 10.0)).collect() +} + +fn ids(v: &Value) -> Vec { + v.as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() +} + +fn path(s: &Session, id: NodeId) -> vectorcraft_geom::PathData { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone() +} + +#[test] +fn a_grid_of_circles_joins_each_to_its_neighbors_in_one_shape() { + let mut s = session(); + let g = grid(&mut s); + select(&mut s, &g); + let steps = s.doc().unwrap().history.undo.len(); + // Reach 5: the side neighbors (4 apart) are bridged, the diagonal ones (about 13.9 apart) not. + let r = s.execute(BRIDGE, &json!({"gap": 4, "reach": 5})).unwrap(); + assert_eq!(ids(&r["ids"]), [g[8]], "one shape, in the topmost circle's place"); + assert_eq!(ids(&r["alone"]), []); + assert_eq!(top_level(&s), [g[8]]); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [g[8]]); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + // Its outline and a hole in each square of four circles, which no diagonal bridge fills. + let outline = path(&s, g[8]); + assert_eq!(outline.subpaths.len(), 5, "{}", outline.subpaths.len()); + let inside = |p: &vectorcraft_geom::PathData, x: f64, y: f64| p.to_bezpath().winding(vectorcraft_geom::kurbo::Point::new(x, y)) != 0; + assert!(inside(&outline, 112.0, 100.0) && inside(&outline, 100.0, 112.0) && !inside(&outline, 112.0, 112.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(top_level(&s), g); + // Reach 15 takes in the diagonal neighbors, whose bridges fill the middle of each square. + select(&mut s, &g); + s.execute(BRIDGE, &json!({"gap": 4, "reach": 15})).unwrap(); + let outline = path(&s, g[8]); + assert_eq!(outline.subpaths.len(), 1); + assert!(inside(&outline, 112.0, 112.0)); +} + +#[test] +fn a_circle_with_no_neighbor_in_reach_stays_as_it_is() { + let mut s = session(); + let g = grid(&mut s); + let far = circle(&mut s, 300.0, 250.0, 10.0); + let pair = [circle(&mut s, 300.0, 40.0, 8.0), circle(&mut s, 320.0, 40.0, 8.0)]; + let mut all = g.clone(); + all.extend([far, pair[0], pair[1]]); + let r = s.execute(BRIDGE, &json!({"ids": all.iter().map(|i| i.0).collect::>(), "reach": 5})).unwrap(); + assert_eq!(ids(&r["ids"]), [g[8], pair[1]]); + assert_eq!(ids(&r["alone"]), [far]); + assert_eq!(top_level(&s), [g[8], far, pair[1]]); + assert!(matches!(&s.doc().unwrap().doc.node(far).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "untouched"); + let mut selected = s.doc().unwrap().selection.objects.to_vec(); + selected.sort(); + let mut want = vec![g[8], pair[1], far]; + want.sort(); + assert_eq!(selected, want, "the shapes and the circle left alone"); +} + +#[test] +fn keep_originals_adds_each_shape_above_its_topmost_circle() { + let mut s = session(); + let row: Vec = (0..3).map(|i| circle(&mut s, 100.0 + 25.0 * i as f64, 100.0, 10.0)).collect(); + let other = [circle(&mut s, 100.0, 200.0, 10.0), circle(&mut s, 122.0, 200.0, 10.0)]; + s.execute("paint.setFill", &json!({"ids": [row[2].0], "color": "#00ff00"})).unwrap(); + let all: Vec = row.iter().chain(&other).map(|i| i.0).collect(); + let r = s.execute(BRIDGE, &json!({"ids": all, "keepOriginals": true})).unwrap(); + let made = ids(&r["ids"]); + assert_eq!(made.len(), 2); + assert_eq!(top_level(&s), [row[0], row[1], row[2], made[0], other[0], other[1], made[1]]); + let d = &s.doc().unwrap().doc; + assert_eq!(d.node(made[0]).unwrap().appearance, d.node(row[2]).unwrap().appearance, "painted as the topmost circle"); + let b = d.node(made[0]).unwrap().path_data().unwrap().bounds().unwrap(); + assert!((b.x0 - 90.0).abs() < 1e-2 && (b.x1 - 160.0).abs() < 1e-2, "{b:?}"); +} + +#[test] +fn the_gap_form_gives_arcs_the_smaller_radius_plus_the_gap() { + let area_with = |p: Value| { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 10.0); + let b = circle(&mut s, 124.0, 100.0, 10.0); + let mut p = p; + p["ids"] = json!([a.0, b.0]); + let id = NodeId(s.execute(BRIDGE, &p).unwrap()["id"].as_u64().unwrap()); + area(&s, id) + }; + // Radius 10 plus a gap of 4 is 140% of 10. + let (gap, percent) = (area_with(json!({"gap": 4})), area_with(json!({"radius": 140}))); + assert!((gap - percent).abs() < 1e-9, "{gap} {percent}"); + assert!(area_with(json!({"gap": 0})) < gap && gap < area_with(json!({"gap": 20}))); +} + +#[test] +fn many_circle_and_gap_refusals() { + let mut s = session(); + let a = circle(&mut s, 50.0, 100.0, 10.0); + let b = circle(&mut s, 250.0, 100.0, 10.0); + let c = circle(&mut s, 330.0, 100.0, 10.0); + let far = circle(&mut s, 380.0, 100.0, 10.0); + let before = top_level(&s); + let steps = s.doc().unwrap().history.undo.len(); + assert!(err(&mut s, json!({"ids": [a.0, b.0], "radius": 100, "gap": 4})).contains("give `radius` or `gap`, not both")); + // Centers 200 apart: a gap of 0 does not bridge them, the largest (1000 pt) does. With centers + // 330 apart even that one closes the neck: it stays open only below 2 × √(10² + 2 × 10 × 1010) + // ≈ 285. + assert!(err(&mut s, json!({"ids": [a.0, b.0], "gap": 0})).ends_with("too far apart for this gap: raise the gap")); + assert!(err(&mut s, json!({"ids": [a.0, far.0], "gap": 0})).ends_with("the circles are too far apart for this gap")); + assert!(err(&mut s, json!({"ids": [a.0, b.0, c.0], "reach": 5})).contains("no two circles are within reach: raise the reach")); + // b and c are 60 apart: within a reach of 100, but too far for the default radius. + assert!(err(&mut s, json!({"ids": [a.0, b.0, c.0], "reach": 100})).ends_with("too far apart for this radius: raise the radius")); + assert!(err(&mut s, json!({"ids": [a.0, b.0, c.0], "reach": -1})).contains("`reach` must be from 0 to 10000")); + assert!(err(&mut s, json!({"ids": [a.0, b.0], "gap": 1001})).contains("`gap` must be from 0 to 1000")); + assert_eq!(top_level(&s), before); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step"); +} + +#[test] +fn a_larger_radius_is_suggested_only_when_it_bridges_among_the_other_circles() { + let mut s = session(); + // Centers 91.65 apart: the largest radius (1000%, 100 pt) bridges these two on their own, but + // with a neck about 0.0007 pt wide, too thin to unite among three or more circles. + let a = circle(&mut s, 20.0, 100.0, 10.0); + let b = circle(&mut s, 111.65, 100.0, 10.0); + let far = circle(&mut s, 380.0, 100.0, 10.0); + assert!(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": 1000})).is_ok()); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(err(&mut s, json!({"ids": [a.0, b.0]})).ends_with("too far apart for this radius: raise the radius")); + for radius in [100, 1000] { + let e = err(&mut s, json!({"ids": [a.0, b.0, far.0], "radius": radius, "reach": 100})); + assert!(e.ends_with("the circles are too far apart for this radius"), "{e}"); + } +} + +#[test] +fn too_many_circles_or_bridges_are_refused() { + let mut s = session(); + // 130 overlapping circles in a row: 8,385 pairs within reach. + let row: Vec = (0..130).map(|i| circle(&mut s, 20.0 + i as f64 * 0.2, 100.0, 10.0).0).collect(); + assert!(err(&mut s, json!({ "ids": row })).contains("that makes too many bridges (at most 8000): lower the reach")); + let many: Vec = (0..2001).map(|i| circle(&mut s, 20.0 + (i % 50) as f64 * 7.0, 150.0 + (i / 50) as f64 * 3.0, 1.0).0).collect(); + assert!(err(&mut s, json!({ "ids": many })).contains("select at most 2000 circles to bridge")); +} + +#[test] +fn an_id_given_twice_is_one_circle() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 150.0, 100.0, 20.0); + let r = s.execute(BRIDGE, &json!({"ids": [a.0, a.0, b.0]})).unwrap(); + assert_eq!(r["id"], json!(b.0), "two circles, bridged"); + assert_eq!(top_level(&s), [b]); +} + +#[test] +fn small_circles_at_the_default_reach_bridge_the_pairs_the_arcs_can_join() { + let mut s = session(); + // Radius 3: arcs of 3 pt (100%) join a and b (2 apart) but close before reaching c (6 from b, + // within the default reach of 10). + let (a, b, c) = (circle(&mut s, 100.0, 100.0, 3.0), circle(&mut s, 108.0, 100.0, 3.0), circle(&mut s, 120.0, 100.0, 3.0)); + let r = s.execute(BRIDGE, &json!({"ids": [a.0, b.0, c.0]})).unwrap(); + assert_eq!(ids(&r["ids"]), [b]); + assert_eq!(ids(&r["alone"]), [c]); + assert_eq!(top_level(&s), [b, c]); +} + #[test] fn locked_and_hidden_circles_are_not_bridged() { let mut s = session(); @@ -176,9 +348,9 @@ fn locked_and_hidden_circles_are_not_bridged() { let b = circle(&mut s, 150.0, 100.0, 20.0); select(&mut s, &[b]); s.execute("object.lock", &json!({})).unwrap(); - assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two circles to bridge")); + assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two or more circles to bridge")); s.execute("object.unlockAll", &json!({})).unwrap(); select(&mut s, &[a]); s.execute("object.hide", &json!({})).unwrap(); - assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two circles to bridge")); + assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two or more circles to bridge")); } diff --git a/crates/engine/src/cmd/addons/pathtools/tangents.rs b/crates/engine/src/cmd/addons/pathtools/tangents.rs index 8102777687..e47c009062 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 at most 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, at most 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/pathtools/tests.rs b/crates/engine/src/cmd/addons/pathtools/tests.rs index 7d11eedd1a..8cd83bacfd 100644 --- a/crates/engine/src/cmd/addons/pathtools/tests.rs +++ b/crates/engine/src/cmd/addons/pathtools/tests.rs @@ -7,7 +7,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{LiveCorners, LiveShape, NodeId}; use vectorcraft_geom::shapes::CornerKind; use vectorcraft_geom::{AnchorKind, PathData, Point, SubPath}; -use vectorcraft_tools::{PointerEvent, PointerKind}; +use vectorcraft_tools::{Action, Overlay, PointerEvent, PointerKind}; use crate::{Session, ViewInfo}; @@ -1055,6 +1055,37 @@ fn the_slide_tool_previews_and_commits_one_step() { assert_eq!(at(&s), Point::new(200.0, 100.0)); } +/// The Tangent Circle tool's release draws the circle and then tells the tool, which forgets the +/// first segment. When the command fails the session does not tell the tool, so the first segment +/// stays picked: the circle shows again over the second segment. The second click draws it in one +/// undo step. +#[test] +fn the_tangent_circle_tool_keeps_its_first_segment_when_drawing_fails() { + let mut s = session(); + line(&mut s, &[(100.0, 100.0), (300.0, 100.0)], false); + line(&mut s, &[(100.0, 140.0), (300.0, 140.0)], false); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("tangentCircle", view).unwrap(); + let at = |s: &mut Session, kind, x, y| s.pointer(&PointerEvent::new(kind, x, y), view); + let shown = |s: &mut Session| { + at(s, PointerKind::Move, 200.0, 139.0).unwrap(); + s.overlays(view).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("R: 20.00"))) + }; + at(&mut s, PointerKind::Down, 150.0, 101.0).unwrap(); + at(&mut s, PointerKind::Up, 150.0, 101.0).unwrap(); + assert!(shown(&mut s), "the first segment is picked"); + // The tool's release with a command that fails: three points on one line. + let n = steps(&s); + let failing = Action::Exec("shape.circleThroughPoints".into(), json!({"points": [[0, 0], [10, 0], [20, 0]]})); + assert!(s.apply_actions(vec![failing, Action::Notify("tangentCircle.drawn".into())]).is_err()); + assert_eq!(steps(&s), n, "nothing drawn"); + assert!(shown(&mut s), "the first segment is still picked"); + at(&mut s, PointerKind::Down, 200.0, 139.0).unwrap(); + at(&mut s, PointerKind::Up, 200.0, 139.0).unwrap(); + assert_eq!(steps(&s), n + 1, "one undo step"); + assert!(!shown(&mut s), "the first segment is forgotten once the circle is drawn"); +} + fn ids(v: &Value) -> Vec { v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() } diff --git a/crates/engine/src/cmd/addons/units.rs b/crates/engine/src/cmd/addons/units.rs index b5d844709a..4da4f68b79 100644 --- a/crates/engine/src/cmd/addons/units.rs +++ b/crates/engine/src/cmd/addons/units.rs @@ -10,7 +10,7 @@ mod tests; use serde_json::{Value, json}; -use vectorcraft_doc::{OrientedBox, Unit, decimal_point, finite_in_every_unit}; +use vectorcraft_doc::{OrientedBox, Unit, arithmetic_signs, decimal_point, finite_in_every_unit}; use vectorcraft_render::effects; use super::super::{CommandSpec, always, bad, cmd, has_selection}; @@ -22,8 +22,8 @@ const SELECTION_SIZE: &str = "addon.units.selectionSize"; const SHOWN_CHARS: usize = 64; /// The longest `value` or `unit` text `addon.units.convert` reads, in bytes. const MAX_TEXT_LEN: usize = 1024; -/// The most `+ - * /` signs `addon.units.convert` reads in one `value`: [`Unit::parse`] takes one -/// level of recursion per sign. +/// The most `+ - * /` signs `addon.units.convert` reads in one `value`, a multiplication sign +/// counted as a `*`: [`Unit::parse`] takes one level of recursion per sign. const MAX_OPERATORS: usize = 128; pub fn specs() -> Vec { @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Convert Units", [], None, - "{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}", + "{value: a length (a number, or text as a number field reads it, with a unit suffix and + - * / arithmetic, x, X or × multiplying as * does: \"10mm\", \"1in/2\", \"2p6\", \"3cm*50%\", \"2x3 mm\"; a decimal comma reads as a point: \"0,5 mm\"; at most 1024 bytes and 128 operators, each multiplication sign counted), unit?: the unit of a number without a suffix (a unit's name, suffix or key: points, picas, inches, millimeters, centimeters, pixels, feetInches, meters, yards, feet, q, ha; default: points)} the length in every unit of Preferences › Units › East Asian Type, written as the number fields write it (rounded to 3 decimals in pt, px, picas, Q and Ha and to 4 in the others; pixels are points). Nothing in the document changes → {points, units: [{unit (its key), label, number (no suffix), text (with the suffix)}]}", always, convert ), @@ -88,9 +88,9 @@ fn convert(_: &mut Session, p: &Value) -> Result { } /// Is `s` short enough to read: at most [`MAX_TEXT_LEN`] bytes and [`MAX_OPERATORS`] `+ - * /` -/// signs? +/// signs, a multiplication sign typed as `x`, `X` or `×` counted as a `*` ([`arithmetic_signs`])? fn readable(s: &str) -> bool { - s.len() <= MAX_TEXT_LEN && s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() <= MAX_OPERATORS + s.len() <= MAX_TEXT_LEN && arithmetic_signs(s) <= MAX_OPERATORS } /// `v` as an error message shows it: text cut at [`SHOWN_CHARS`] characters with "…", as JSON, diff --git a/crates/engine/src/cmd/addons/units/tests.rs b/crates/engine/src/cmd/addons/units/tests.rs index f914c53092..802fb5dfdf 100644 --- a/crates/engine/src/cmd/addons/units/tests.rs +++ b/crates/engine/src/cmd/addons/units/tests.rs @@ -76,6 +76,12 @@ fn values_read_as_number_fields_read_them() { assert!(near(pt(&mut s, json!({"value": "1,500+2", "unit": "mm"})), 3.5 * 72.0 / 25.4)); // A sum of 128 signs still reads. assert!(near(pt(&mut s, json!({"value": format!("1{}", "+1".repeat(128))})), 129.0)); + // x, X and × multiply as * does, and each counts toward the 128 signs. + assert!(near(pt(&mut s, json!({"value": "2x3 mm"})), 6.0 * 72.0 / 25.4)); + assert!(near(pt(&mut s, json!({"value": "10X2"})), 20.0)); + assert!(near(pt(&mut s, json!({"value": "0,5×4 in"})), 144.0)); + assert!(near(pt(&mut s, json!({"value": format!("1{}", "x1".repeat(128))})), 1.0)); + assert!(s.execute("addon.units.convert", &json!({"value": format!("1{}", "x1".repeat(129))})).is_err()); } #[test] diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 84596eb53c..6d2c7fd18f 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -278,6 +278,28 @@ impl ItemTarget { } } + /// [`ItemTarget::targets`] of a fill (`fill`) or a stroke edit: on the topmost fill or stroke, a + /// Live Paint group stands for its faces in a fill edit and for its edges in a stroke edit + /// ([`super::paint::live_paint_parts_skipped`]). + pub(crate) fn targets_for(self, s: &Session, p: &Value, fill: bool) -> Result> { + Ok(self.targets_and_skipped(s, p, fill)?.0) + } + + /// [`ItemTarget::targets_for`], and whether it left out any object inside a Live Paint group: a + /// group with no part of the edited kind was still given or selected, so the edit does not go + /// to new art. + pub(crate) fn targets_and_skipped(self, s: &Session, p: &Value, fill: bool) -> Result<(Vec, bool)> { + let mut ids = self.targets(s, p)?; + let mut skipped_any = false; + if self == ItemTarget::Top { + let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, fill); + let before = ids.len(); + ids.retain(|id| !skipped.contains(id)); + skipped_any = ids.len() != before; + } + Ok((ids, skipped_any)) + } + /// The target of a fill (`fill`) or stroke edit: the panel's active item stands only for edits /// of its own kind, so a fill row leaves stroke edits on the topmost stroke of the painted /// leaves (as without an active item) and vice versa. Explicit items are kept (and checked). @@ -772,7 +794,7 @@ fn edit_items_writing_then( // The objects whose rows `f` edited: on type, no row means its characters. let mut rows = Vec::new(); // The objects where `f` wrote the topmost visible row of its kind. - let mut wrote = Vec::new(); + let mut wrote = HashSet::new(); // The row of each object `f` wrote: its index, else the topmost row of the kind. let mut written = Vec::new(); for (id, item) in ids.iter().zip(&per) { @@ -785,7 +807,7 @@ fn edit_items_writing_then( rows.push(*id); } if index.is_none_or(|i| is_top_shown(n, i)) { - wrote.push(*id); + wrote.insert(*id); } written.extend(index.or_else(|| n.appearance.items.iter().rposition(|it| it.is_fill() == fill)).map(|at| (*id, at))); } @@ -1341,7 +1363,8 @@ fn set_item(s: &mut Session, p: &Value) -> Result { let mut rows = top_paint_changed(&before, d, &ids); rows.extend(painted_rows(d, written)); let painted = super::graph::capture_series_top_paints(d, &rows); - let reached = shown_rows_edited(&before, d, reached, |id| edited.iter().any(|(e, _)| *e == id)); + let wrote: HashSet = edited.iter().map(|(id, _)| *id).collect(); + let reached = shown_rows_edited(&before, d, reached, |id| wrote.contains(&id)); let labels = capture_row_edits(&before, d, &reached); // A graph line keeps what was written to its topmost visible row, also when it already showed it. let tops: Vec<(NodeId, usize)> = ids.iter().zip(&per).filter_map(|(id, at)| Some((*id, *at.first()?))).collect(); @@ -1503,7 +1526,7 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result { } super::graph::capture_series_opacity(d, &top_opacity_changed(&before, d, &ids)); let mut rows = top_paint_changed(&before, d, &ids); - let top_copies: Vec = added.iter().map(|(id, _)| *id).collect(); + let top_copies: HashSet = added.iter().map(|(id, _)| *id).collect(); rows.extend(painted_rows(d, added)); super::graph::capture_series_top_paints(d, &rows); capture_row_edits(&before, d, &shown_rows_edited(&before, d, reached, |id| top_copies.contains(&id))); diff --git a/crates/engine/src/cmd/assets.rs b/crates/engine/src/cmd/assets.rs index 05c2fda1d7..d253c4803f 100644 --- a/crates/engine/src/cmd/assets.rs +++ b/crates/engine/src/cmd/assets.rs @@ -80,7 +80,7 @@ pub fn specs() -> Vec { "Export 3D Assets", [], None, - "{assets?: [asset id…] (default every 3D asset), folder?, zip?, textureSize?: 128…4096 (default 1024: the pixels along the longer side of each face's texture)} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). The graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (threeD.mapGraphic) are a PNG texture of that face: its color with the graphics drawn over it, flat and unlit, on a mesh of the face's own with texture coordinates; glTF embeds it, USDZ stores it after the layer, and OBJ and USDA write it beside them as -texture-1.png… (whitespace, # and @ become _); a face that is not opaque keeps its opacity in the texture's alpha, and an OBJ also gets -texture-1-opacity.png…, the alpha as gray levels for its map_d. Graphics on Revolve's side are not exported. Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, or textures of more than 67,108,864 pixels in one export, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})", + "{assets?: [asset id…] (default every 3D asset), folder?, zip?, textureSize?: 128…4096 (default 1024: the pixels along the longer side of each face's texture)} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). The graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (threeD.mapGraphic) are a PNG texture of that face: its color with the graphics drawn over it, flat and unlit, on a mesh of the face's own with texture coordinates; glTF embeds it, USDZ stores it after the layer, and OBJ and USDA write it beside them as -texture-1.png… (whitespace, # and @ become _); a face that is not opaque keeps its opacity in the texture's alpha, and an OBJ also gets -texture-1-opacity.png…, the alpha as gray levels for its map_d. Graphics on Revolve's side (in a group, the side of the member with the longest profile) are a texture of the side unrolled as the canvas lays it out, on a mesh of the side's triangles; its end caps and cut sides stay plain. Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, or textures of more than 67,108,864 pixels in one export, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})", has_doc, export_3d ), 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..2d31c5af6e 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -12,10 +12,11 @@ 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}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, ImageBlob, ImageObject, Node, NodeId, NodeKind, PatternDef, Symbol}; use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect, SubPath, shapes}; use super::brushsym::{apply_brush, brush_targets, roots, stroke_paint}; @@ -172,13 +173,17 @@ 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 }, + BuiltinBrushLibrary { id: "stipple", name: "Stipple", make: stipple }, BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails }, 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 }, + BuiltinBrushLibrary { id: "image-brush", name: "Image Brush", make: image_brush }, ]; /// Built-in library `id`, made once. @@ -232,6 +237,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 +427,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 { @@ -479,6 +573,80 @@ fn scatter(name: &str, art: Node, s: Scatter) -> Brush { Brush { name: name.into(), kind: BrushKind::Scatter(Scatter { art, ..s }) } } +/// Four original raster stamps. Scatter brushes preserve their image art while placing a copy +/// along the path; art brushes bend their art and cannot bend an image. Each 24 px stamp is placed +/// 6 pt wide, the size of the Scatter Shapes art, so a 1 pt stroke on a 10 pt line shows a stamp. +fn image_brush() -> BrushLibrary { + const SIDE: u32 = 24; + const PT_PER_PX: f64 = 0.25; + let mut doc = Document::new(100.0, 100.0); + let mut brushes = Vec::new(); + for (index, name) in ["Soft Bloom", "Halftone Field", "Solar Grain", "Color Flecks"].into_iter().enumerate() { + let mut pixels = Vec::with_capacity((SIDE * SIDE * 4) as usize); + for y in 0..SIDE { + for x in 0..SIDE { + let (dx, dy) = (x as f64 - 11.5, y as f64 - 11.5); + let r = dx.hypot(dy); + let angle = dy.atan2(dx); + let rgba = match index { + 0 => { + let edge = 7.0 + 3.0 * (5.0 * angle).cos(); + [199, 69, 139, (220.0 * ((edge - r) / 2.5).clamp(0.0, 1.0)) as u8] + } + 1 => { + let (gx, gy) = ((x % 6) as f64 - 2.5, (y % 6) as f64 - 2.5); + [39, 139, 175, if r < 11.0 && gx.hypot(gy) < 1.9 { 225 } else { 0 }] + } + 2 => { + let ray = (9.0 * angle).cos().abs(); + [234, 144, 40, if r < 3.5 || (r < 10.5 && ray > 0.72) { 235 } else { 0 }] + } + _ => { + let seed = (x * 37 + y * 71 + x * y * 13) % 19; + [if seed % 2 == 0 { 67 } else { 114 }, 79, 167, if r < 11.0 && seed < 5 { 210 } else { 0 }] + } + }; + pixels.extend_from_slice(&rgba); + } + } + let Ok(image) = + craft_image_codecs::Image::from_raw(SIDE, SIDE, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, pixels) + else { + continue; + }; + let Ok(png) = craft_image_codecs::encode(&image, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()) else { + continue; + }; + let key = format!("image-brush-{index}"); + doc.images.insert(key.clone(), ImageBlob::png(png)); + let art = Node::new( + NodeId(0), + NodeKind::Image(Box::new(ImageObject { + key, + width: SIDE, + height: SIDE, + xf: Affine::scale(PT_PER_PX) * Affine::translate((-12.0, -12.0)), + link: None, + placement: Default::default(), + pixels: None, + })), + ); + brushes.push(scatter( + name, + art, + Scatter { + size: (90.0, 110.0), + spacing: (125.0, 155.0), + scatter: (-20.0, 20.0), + rotation: (-15.0, 15.0), + colorization: Colorization::None, + ..Default::default() + }, + )); + } + built("Image Brush", doc, brushes) +} + /// Scatter Shapes: scatter brushes of shapes drawn here; Sparkles scatters the library's own /// symbol, Sparkle. fn scatter_shapes() -> BrushLibrary { @@ -535,6 +703,44 @@ fn scatter_shapes() -> BrushLibrary { built("Scatter Shapes", doc, brushes) } +/// Stipple: original dot-based scatter brushes for fine and broad shading along a path. +fn stipple() -> BrushLibrary { + let dot = |x: f64, y: f64, r: f64, opacity: f32| { + Node::path( + NodeId(0), + shapes::ellipse(Rect::new(x - r, y - r, x + r, y + r)), + Appearance { + items: vec![AppearanceItem::Fill(FillLayer { opacity, ..FillLayer::new(Paint::solid(Color::BLACK)) })], + ..Default::default() + }, + ) + }; + let base = Scatter { colorization: Colorization::Tints, ..Default::default() }; + let brushes = vec![ + scatter( + "Fine Stipple", + dot(0.0, 0.0, 0.8, 1.0), + Scatter { size: (70.0, 110.0), spacing: (80.0, 130.0), scatter: (-100.0, 100.0), ..base.clone() }, + ), + scatter( + "Dense Stipple", + group(vec![dot(-1.7, -1.4, 1.0, 1.0), dot(1.5, 0.5, 0.8, 1.0), dot(-0.5, 1.8, 0.65, 1.0)]), + Scatter { size: (80.0, 120.0), spacing: (55.0, 90.0), scatter: (-70.0, 70.0), ..base.clone() }, + ), + scatter( + "Soft Stipple", + group(vec![dot(-1.2, -0.8, 1.0, 0.45), dot(1.2, 1.1, 0.7, 0.35)]), + Scatter { size: (55.0, 135.0), spacing: (80.0, 140.0), scatter: (-140.0, 140.0), ..base.clone() }, + ), + scatter( + "Bold Stipple", + group(vec![dot(-1.5, -1.0, 1.8, 1.0), dot(1.6, 1.3, 1.4, 1.0)]), + Scatter { size: (80.0, 125.0), spacing: (75.0, 115.0), scatter: (-95.0, 95.0), ..base }, + ), + ]; + built("Stipple", Document::new(100.0, 100.0), brushes) +} + /// Game Trails: art brushes for motion lines and impact streaks (original game HUD / VFX art). fn game_trails() -> BrushLibrary { let speed = { diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index c026a1086e..6c0f651c00 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -27,11 +27,15 @@ use crate::EngineError; /// Whether Reset Transformation changes a symbol instance. pub use symbols::reset_transformation_changes; +/// Whether an object is a symbol set. +pub use symbols::is_symbol_set; + /// The Symbols panel's current symbol, as `symbol.list` answers it. pub use symbols::current_symbol; mod brushes; mod dynamic; +mod symbolism; mod symbols; pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint}; @@ -41,6 +45,7 @@ use brushes::{ }; 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}; +use symbolism::symbol_set_density; use symbols::selected_instances; pub(crate) use symbols::{ expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol, @@ -165,7 +170,7 @@ pub fn specs() -> Vec { "Brush Options…", [], None, - "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", + "{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 ), @@ -220,7 +225,7 @@ pub fn specs() -> Vec { "Symbol Options…", [], None, - "{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic, alignToPixelGrid?: bool} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1), Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes) and Align to Pixel Grid (on: the horizontal and vertical straight segments of the paths in the symbol's art snap to whole points, or half points for an odd centered stroke, at the symbol's natural size, its stroke weights become whole points, and every instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after each move; a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's art, is left where it is; the art snaps again after it is edited); alignToPixelGrid alone with the value the symbol already has changes nothing and adds no undo step; default name: current → {name, registration, exportType, nineSlice, type, alignToPixelGrid}", + "{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic, alignToPixelGrid?: bool} rename a symbol (its instances and the graphics and Map Art maps on 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions in from each edge, each -16..16, with left + right < 1 and top + bottom < 1), Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes) and Align to Pixel Grid (on: the horizontal and vertical straight segments of the paths in the symbol's art snap to whole points, or half points for an odd centered stroke, at the symbol's natural size, its stroke weights become whole points, and every instance placed at that size, reflected across one axis or not, moves to whole points and goes back to them after each move; a scaled, rotated (a half turn included) or sheared instance, and an instance in another symbol's art, is left where it is; the art snaps again after it is edited); alignToPixelGrid alone with the value the symbol already has changes nothing and adds no undo step; default name: current → {name, registration, exportType, nineSlice, type, alignToPixelGrid}", has_doc, symbol_options ), @@ -338,7 +343,7 @@ pub fn specs() -> Vec { "Select All Unused", [], None, - "{} → {names: [the symbols nothing places, in panel order]} (the Symbols panel selects them): instances in the art (opacity masks included), graphics mapped onto 3D objects (threeD.mapGraphic), graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and brush art count, and so do instances in the art of a symbol that is used", + "{} → {names: [the symbols nothing places, in panel order]} (the Symbols panel selects them): instances in the art (opacity masks included), graphics and Map Art maps on 3D objects (threeD.mapGraphic, threeD.mapArt), graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and brush art count, and so do instances in the art of a symbol that is used", has_doc, symbol_unused ), @@ -357,16 +362,25 @@ pub fn specs() -> Vec { "Symbol Sprayer", [], None, - "{points: [[x,y]…], name?, radius?: 40, density?: 1..10 (5), scale?: 1, alt?: bool (remove instances)} spray instances into a symbol set → {id, count}", + "{points: [[x,y]…] (a third number is not used; one that isn't a number is an error), name?, radius?: 40, density?: 1..10 (5), scale?: 1, alt?: bool (remove instances), attributes?: {scrunch?, size?, spin?, screen?, stain?, style?: average|userDefined (average)}, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} spray instances into a symbol set → {id, count}. Each of `attributes` says what a new instance takes: average, the mean of the selected set's instances within `radius` of the stroke point (their spacing along the stroke, size, rotation, opacity, and the stain or style of the nearest one that has one at the mean amount), and with none there the symbol's size, no rotation, full opacity and no stain or style; or userDefined: spacing from the symbol's size and `density`, the symbol's size times `scale`, turned the way the stroke runs there (not turned for one point), full opacity, stained in full with `color` (default: the fill color), and the fill of graphic style `style` (default: the first style after the default one) in full; a `style` the document does not have is then an error. The stain and the style are both the instance's fill, and the style replaces the stain. Another key or value in `attributes` is an error", has_doc, symbol_spray ), + cmd!( + "symbol.setDensity", + "Symbol Set Density", + [], + None, + "{from: 1..10, to: 1..10, ids?|id?} space the instances of the selected symbol sets (or those in `ids`) as Symbol Set Density `to` packs them, from the density each set was created at or last given (`from` for a set without one, such as one grouped by hand): each instance moves along the line from the middle of its set's instances, to (1.15 − 0.1·to) / (1.15 − 0.1·from) of its distance from it (each factor at least 0.1), as one undo step, and every set then has density `to`, also one whose instances do not move (one instance, or each locked); a higher density packs them closer, and a locked or hidden instance stays where it is. No undo step is added when no instance moves and every set already has density `to`. A `from` or `to` left out, not a number or outside 1..10, an id naming no object, or no symbol set among the objects is an error → {ids: the sets changed, count: the instances moved}", + has_doc, + symbol_set_density + ), cmd!( "symbol.adjust", "Symbolism Tool", [], None, - "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y]…], radius?: 40, intensity?: 1..10 (5), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}", + "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it; average leaves an instance without a size (a scale of 0) as it is. With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the height; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. An instance counts only when it changes, and no undo step is added when none does (none under the brush, average with each already at the mean, or each already at the tool's limit). A `method` that is none of the three, or a pressure that isn't a number, is an error", has_doc, symbol_adjust ), diff --git a/crates/engine/src/cmd/brushsym/symbolism.rs b/crates/engine/src/cmd/brushsym/symbolism.rs new file mode 100644 index 0000000000..0199b7b13d --- /dev/null +++ b/crates/engine/src/cmd/brushsym/symbolism.rs @@ -0,0 +1,442 @@ +//! What the symbolism commands share: the Method and the Symbol Sprayer options of the Symbolism +//! Tools Options, what an instance shows of the values the tools change ([`Look`]), the mean of +//! those values under the brush ([`mean`]), and `symbol.setDensity`. + +use std::collections::HashMap; + +use super::symbols::{instance_center, is_symbol_set, stored_natural_size}; +use super::{ + Affine, Document, EngineError, HALF, Node, NodeId, NodeKind, Paint, Point, Result, Session, Value, Vec2, bad, ids_json, json, named_ids, +}; + +/// Method: how the Scruncher, Sizer, Spinner, Stainer, Screener and Styler adjust instances. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Method { + /// Gradually, in relation to the position of the pointer. + UserDefined, + /// Toward the mean of the instances under the brush. + Average, + /// By an amount that differs from instance to instance. + Random, +} + +/// The `method` of `symbol.adjust` (User Defined when left out or null). +pub(super) fn method_param(p: &Value, cmd: &str) -> Result { + match p.get("method") { + None | Some(Value::Null) => Ok(Method::UserDefined), + Some(Value::String(s)) if s == "userDefined" => Ok(Method::UserDefined), + Some(Value::String(s)) if s == "average" => Ok(Method::Average), + Some(Value::String(s)) if s == "random" => Ok(Method::Random), + Some(v) => Err(bad(cmd, format!("`method` must be userDefined, average or random, not {v}"))), + } +} + +/// The Symbol Sprayer options: whether each value of a new instance is the average of the +/// instances under the brush (true) or the User Defined value (false). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct SprayModes { + pub scrunch: bool, + pub size: bool, + pub spin: bool, + pub screen: bool, + pub stain: bool, + pub style: bool, +} + +impl SprayModes { + /// Whether any value is an average. + pub fn any_average(self) -> bool { + self.scrunch || self.size || self.spin || self.screen || self.stain || self.style + } +} + +/// The `attributes` of `symbol.spray`: `{scrunch?, size?, spin?, screen?, stain?, style?}`, each +/// `average` (also when left out or null) or `userDefined`. Another key or value is an error. +pub(super) fn spray_modes(p: &Value, cmd: &str) -> Result { + let mut m = SprayModes { scrunch: true, size: true, spin: true, screen: true, stain: true, style: true }; + let map = match p.get("attributes") { + None | Some(Value::Null) => return Ok(m), + Some(Value::Object(map)) => map, + Some(v) => return Err(bad(cmd, format!("`attributes` must be an object, not {v}"))), + }; + for (key, v) in map { + let slot = match key.as_str() { + "scrunch" => &mut m.scrunch, + "size" => &mut m.size, + "spin" => &mut m.spin, + "screen" => &mut m.screen, + "stain" => &mut m.stain, + "style" => &mut m.style, + _ => return Err(bad(cmd, format!("unknown attribute `{key}`"))), + }; + *slot = match v { + Value::Null => true, + Value::String(s) if s == "average" => true, + Value::String(s) if s == "userDefined" => false, + v => return Err(bad(cmd, format!("attribute `{key}` must be average or userDefined, not {v}"))), + }; + } + Ok(m) +} + +/// How far apart the Symbol Sprayer keeps instances at Symbol Set Density `density` (1..10), as a +/// share of the symbol's size: a denser set is packed closer. +pub(super) fn spacing(density: f64) -> f64 { + (1.15 - density * 0.1).max(0.1) +} + +/// The document key that holds each symbol set's Symbol Set Density: `{set id: density}`, written +/// when the Symbol Sprayer creates a set and when `symbol.setDensity` spaces it. +const SET_DENSITY_KEY: &str = "symbolSetDensity"; + +/// The Symbol Set Density symbol set `set` was created at or last given (None when not recorded). +fn set_density_of(d: &Document, set: NodeId) -> Option { + d.unknown.get(SET_DENSITY_KEY)?.get(set.0.to_string())?.as_f64().filter(|v| (1.0..=10.0).contains(v)) +} + +/// Record `density` as the Symbol Set Density of `sets`, and drop the records of ids that are no +/// longer symbol sets. +pub(super) fn record_set_density(d: &mut Document, sets: &[NodeId], density: f64) { + let mut map = match d.unknown.get(SET_DENSITY_KEY) { + Some(Value::Object(m)) => m.clone(), + _ => serde_json::Map::new(), + }; + for set in sets { + map.insert(set.0.to_string(), json!(density)); + } + map.retain(|k, _| k.parse::().ok().and_then(|id| d.node(NodeId(id))).is_some_and(is_symbol_set)); + if map.is_empty() { + d.unknown.remove(SET_DENSITY_KEY); + } else { + d.unknown.insert(SET_DENSITY_KEY.into(), Value::Object(map)); + } +} + +/// What a symbol instance shows of the values the symbolism tools change. +#[derive(Clone, Debug)] +pub(super) struct Look { + pub center: Point, + /// Its size on the page: the side of a square with its area, the same measure for every symbol. + pub size: f64, + /// Its rotation in radians. + pub angle: f64, + pub opacity: f64, + /// The fill the Symbol Stainer or the Symbol Styler gave it, with its amount (0..1). + pub fill: Option<(Paint, f64)>, +} + +/// The [`natural_side`] of each symbol measured so far in one command, so that one measure serves +/// every instance of the symbol. +pub(super) type Sides = HashMap; + +/// The [`Look`] of instance `n` (None for another object, or an instance without a size). +pub(super) fn look(d: &Document, n: &Node, sides: &mut Sides) -> Option { + let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return None }; + let [a, b, c, e, ..] = xf.as_coeffs(); + let natural = d.symbol_natural_xf(symbol).as_coeffs(); + let (sx, sy) = (natural[0].abs().max(1e-9), natural[3].abs().max(1e-9)); + let scale = ((a * e - b * c) / (sx * sy)).abs().sqrt(); + if !(scale.is_finite() && scale > 0.0) { + return None; + } + let side = match sides.get(symbol) { + Some(side) => *side, + None => *sides.entry(symbol.clone()).or_insert_with(|| natural_side(d, symbol)), + }; + let size = scale * side; + if !(size.is_finite() && size > 0.0) { + return None; + } + Some(Look { + center: instance_center(n)?, + size, + angle: b.atan2(a), + opacity: f64::from(n.opacity), + fill: n.appearance.fill().map(|f| (f.paint.clone(), f64::from(f.opacity))), + }) +} + +/// The [`Look::size`] of an instance of symbol `name` at the symbol's own size. A symbol without a +/// recorded size draws its art at the art's own size, so its art is measured. +pub(super) fn natural_side(d: &Document, name: &str) -> f64 { + let recorded = stored_natural_size(d, name).is_some_and(|(w, h)| w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0); + // Each side's root first, so that a huge size does not overflow. + let art = (!recorded).then(|| d.symbol_art_bounds(name)).flatten().map(|r| r.width().sqrt() * r.height().sqrt()); + if let Some(side) = art.filter(|s| s.is_finite() && *s > 0.0) { + return side; + } + let natural = d.symbol_natural_xf(name).as_coeffs(); + 2.0 * HALF * natural[0].abs().max(1e-9).sqrt() * natural[3].abs().max(1e-9).sqrt() +} + +/// The mean of the [`Look`]s of the instances under the brush. +#[derive(Clone, Debug)] +pub(super) struct Mean { + /// The geometric mean of the sizes ([`Look::size`]). + pub size: f64, + /// The mean direction of the rotations. + pub angle: f64, + pub opacity: f64, + /// The mean stain or style amount; an instance without one counts as 0. + pub amount: f64, + /// The stain or style of the instance nearest the brush's center that has one. + pub paint: Option, + /// The middle of the instances. + pub middle: Point, + /// Their mean distance from [`Mean::middle`]. + pub reach: f64, + /// The mean distance from each of them to the nearest of the others (None for one instance, or + /// when not asked for). + pub gap: Option, +} + +/// The x (`axis` 0) or y (`axis` 1) of `p`. +fn coord(p: Point, axis: usize) -> f64 { + if axis == 0 { p.x } else { p.y } +} + +/// Arrange `order` (indices into `pts`) as a k-d tree: the middle entry of each slice splits the +/// rest by x at even depths and by y at odd ones, the smaller values before it. +fn kd_build(order: &mut [usize], pts: &[Point], axis: usize) { + if order.len() <= 1 { + return; + } + let mid = order.len() / 2; + let at = |i: &usize| pts.get(*i).map_or(0.0, |p| coord(*p, axis)); + order.select_nth_unstable_by(mid, |a, b| at(a).total_cmp(&at(b))); + let (left, right) = order.split_at_mut(mid); + kd_build(left, pts, 1 - axis); + kd_build(right.get_mut(1..).unwrap_or_default(), pts, 1 - axis); +} + +/// The distance from `pts[i]` to the nearest of the others in k-d tree `order`, if nearer than +/// `best`. Instances on top of each other end the search: none can be nearer. +fn kd_nearest(order: &[usize], pts: &[Point], axis: usize, i: usize, best: &mut f64) { + let (Some(&j), Some(&p)) = (order.get(order.len() / 2), pts.get(i)) else { return }; + let Some(&q) = pts.get(j) else { return }; + if j != i { + *best = best.min(p.distance(q)); + } + if *best == 0.0 { + return; + } + let (left, right) = order.split_at(order.len() / 2); + let right = right.get(1..).unwrap_or_default(); + let diff = coord(p, axis) - coord(q, axis); + let (near, far) = if diff < 0.0 { (left, right) } else { (right, left) }; + kd_nearest(near, pts, 1 - axis, i, best); + // The other side holds nothing nearer than the split line. + if diff.abs() < *best { + kd_nearest(far, pts, 1 - axis, i, best); + } +} + +/// For each of `looks`, the distance to the nearest of the others (infinite for one alone), found +/// through a k-d tree of their centers. +fn nearest_gaps(looks: &[&Look]) -> Vec { + let pts: Vec = looks.iter().map(|l| l.center).collect(); + let mut order: Vec = (0..pts.len()).collect(); + kd_build(&mut order, &pts, 0); + (0..pts.len()) + .map(|i| { + let mut best = f64::INFINITY; + kd_nearest(&order, &pts, 0, i, &mut best); + best + }) + .collect() +} + +/// The [`Mean`] of `looks`, the instances under a brush centered on `at` (None for none), with +/// [`Mean::gap`] when `with_gap` is set. +pub(super) fn mean(looks: &[&Look], at: Point, with_gap: bool) -> Option { + if looks.is_empty() { + return None; + } + let n = looks.len() as f64; + let (mut log_size, mut sin, mut cos, mut opacity, mut amount, mut middle) = (0.0, 0.0, 0.0, 0.0, 0.0, Vec2::ZERO); + let mut paint: Option<(&Paint, f64)> = None; + for l in looks { + log_size += l.size.ln(); + sin += l.angle.sin(); + cos += l.angle.cos(); + opacity += l.opacity; + middle += l.center.to_vec2(); + if let Some((p, o)) = &l.fill { + amount += o; + let far = l.center.distance(at); + if paint.is_none_or(|(_, nearest)| far < nearest) { + paint = Some((p, far)); + } + } + } + let middle = (middle / n).to_point(); + // Rotations that cancel out have no mean direction: the first instance's stands for it. + let angle = if sin.hypot(cos) > 1e-9 { sin.atan2(cos) } else { looks[0].angle }; + // One instance under the brush has no spacing there. + let gap = (with_gap && looks.len() > 1).then(|| nearest_gaps(looks).iter().sum::() / n); + Some(Mean { + size: (log_size / n).exp(), + angle, + opacity: opacity / n, + amount: amount / n, + paint: paint.map(|(p, _)| p.clone()), + middle, + reach: looks.iter().map(|l| l.center.distance(middle)).sum::() / n, + gap, + }) +} + +/// `angle` (radians) brought into −π..π. +pub(super) fn wrap_angle(angle: f64) -> f64 { + let turn = std::f64::consts::TAU; + let a = angle.rem_euclid(turn); + if a > std::f64::consts::PI { a - turn } else { a } +} + +/// The instances of a symbol set by where they are, to find those under a brush without looking at +/// every one for every point of a stroke. +pub(super) struct Grid { + cell: f64, + looks: Vec, + cells: HashMap<(i64, i64), Vec>, +} + +fn key(p: Point, cell: f64) -> (i64, i64) { + ((p.x / cell).floor() as i64, (p.y / cell).floor() as i64) +} + +/// The indices in the cell of `at`, then in the eight around it. Saturating: a point far out on the +/// canvas has a key at the end of the range. +fn around(cells: &HashMap<(i64, i64), Vec>, at: Point, cell: f64) -> impl Iterator + '_ { + let (cx, cy) = key(at, cell); + let ring = (cx.saturating_sub(1)..=cx.saturating_add(1)) + .flat_map(move |x| (cy.saturating_sub(1)..=cy.saturating_add(1)).map(move |y| (x, y))) + .filter(move |c| *c != (cx, cy)); + std::iter::once((cx, cy)).chain(ring).flat_map(move |c| cells.get(&c).into_iter().flatten().copied()) +} + +impl Grid { + /// `looks` in cells `cell` points wide (the brush's radius). + pub fn new(looks: Vec, cell: f64) -> Self { + let cell = cell.max(1.0); + let mut cells: HashMap<(i64, i64), Vec> = HashMap::new(); + for (i, l) in looks.iter().enumerate() { + cells.entry(key(l.center, cell)).or_default().push(i); + } + Self { cell, looks, cells } + } + + /// The mean of the instances within `radius` (at most the cell width) of `at`, with + /// [`Mean::gap`] when `with_gap` is set. + pub fn mean(&self, at: Point, radius: f64, with_gap: bool) -> Option { + let near: Vec<&Look> = + around(&self.cells, at, self.cell).filter_map(|i| self.looks.get(i)).filter(|l| l.center.distance(at) <= radius).collect(); + mean(&near, at, with_gap) + } +} + +/// `symbol.setDensity {from, to, ids?|id?}`: space the instances of the selected symbol sets as +/// Symbol Set Density `to` packs them, from the density each set was created at or last given +/// (`from` for a set without one): each instance moves along the line from the middle of its set's +/// instances, to [`spacing`]`(to) / `[`spacing`]` of the set's density` of its distance from it. +/// Every selected set then has density `to`, also one whose instances do not move. One undo step, +/// and none when no instance moves and every set already has density `to`. +pub(super) fn symbol_set_density(s: &mut Session, p: &Value) -> Result { + const C: &str = "symbol.setDensity"; + let density = |key: &str| match p.get(key) { + Some(v) => v.as_f64().filter(|d| (1.0..=10.0).contains(d)).ok_or_else(|| bad(C, format!("`{key}` must be a number from 1 to 10, not {v}"))), + None => Err(bad(C, format!("missing `{key}`"))), + }; + let (from, to) = (density("from")?, density("to")?); + crate::cmd::edit::refuse_symbol_part(s)?; + let st = s.doc()?; + let d = &st.doc; + let named = named_ids(p)?; + let ids: Vec = named.clone().unwrap_or_else(|| st.selection.objects.clone()); + if let Some(missing) = named.iter().flatten().find(|id| d.node(**id).is_none()) { + return Err(EngineError::Other(format!("no object {}", missing.0))); + } + let editable = d.editable(); + let mut sets: Vec = vec![]; + for id in ids { + if d.node(id).is_some_and(is_symbol_set) && editable(id) && !sets.contains(&id) { + sets.push(id); + } + } + if sets.is_empty() { + return Err(EngineError::Other("no symbol set selected".into())); + } + let mut moves: Vec<(NodeId, Vec2)> = vec![]; + let mut changed: Vec = vec![]; + for set in &sets { + // A set packs from the density it was created at or last given, else from `from`. + let own = set_density_of(d, *set); + let ratio = spacing(to) / spacing(own.unwrap_or(from)); + // A set takes density `to` even when none of its instances moves (one instance, or each + // locked or on top of the others), so a later change packs it from `to`. + let restamp = own != Some(to); + let centers: Vec<(NodeId, Point)> = + d.node(*set).and_then(|n| n.children()).into_iter().flatten().filter_map(|c| Some((c.id, instance_center(c)?))).collect(); + if centers.len() < 2 { + if restamp { + changed.push(*set); + } + continue; + } + let middle = (centers.iter().fold(Vec2::ZERO, |sum, (_, c)| sum + c.to_vec2()) / centers.len() as f64).to_point(); + let before = moves.len(); + // A locked or hidden instance stays where it is. + moves.extend( + centers.iter().filter(|(id, _)| editable(*id)).map(|(id, c)| (*id, (*c - middle) * (ratio - 1.0))).filter(|(_, v)| v.hypot() > 1e-9), + ); + if moves.len() > before || restamp { + changed.push(*set); + } + } + drop(editable); + if !changed.is_empty() { + s.edit("Symbol Set Density", |d, _| { + for (id, v) in &moves { + if let Some(n) = d.node_mut(*id) { + n.transform(Affine::translate(*v), false); + } + } + record_set_density(d, &changed, to); + Ok(()) + })?; + } + Ok(json!({ "ids": ids_json(&changed), "count": moves.len() })) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn at(x: f64, y: f64) -> Look { + Look { center: Point::new(x, y), size: 20.0, angle: 0.0, opacity: 1.0, fill: None } + } + + /// The distance from each instance in `from` to the nearest other one in `refs`, measured + /// against every other instance. + fn brute(refs: &[&Look], from: impl Iterator) -> Vec { + from.map(|i| (0..refs.len()).filter(|j| *j != i).map(|j| refs[i].center.distance(refs[j].center)).fold(f64::INFINITY, f64::min)).collect() + } + + /// The gaps are each instance's distance to its nearest neighbor, measured against every other + /// instance: close pairs whose members are far apart in the order, instances on top of each + /// other, instances far from all others, many instances close together, and many on one line. + #[test] + fn nearest_gaps_match_measuring_every_pair() { + let mut looks: Vec = (0..300).map(|i| at(f64::from(i % 20) * 9.0, f64::from(i / 20) * 7.0)).collect(); + // The second member of each pair comes 300 places later. + looks.extend((0..300).map(|i| at(f64::from(i % 20) * 9.0 + 0.5, f64::from(i / 20) * 7.0))); + looks.extend([at(500.0, 500.0), at(500.0, 500.0), at(900.0, 40.0)]); + // 400 instances within one point of each other, and 200 on one upright line. + looks.extend((0..400).map(|i| at(700.0 + f64::from(i % 20) * 0.05, 700.0 + f64::from(i / 20) * 0.05))); + looks.extend((0..200).map(|i| at(-50.0, f64::from(i) * 1.5))); + let refs: Vec<&Look> = looks.iter().collect(); + assert_eq!(nearest_gaps(&refs), brute(&refs, 0..refs.len())); + assert_eq!(nearest_gaps(&refs[..1]), [f64::INFINITY]); + assert_eq!(nearest_gaps(&refs[..0]), Vec::::new()); + } +} diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index f5245bc9af..6f1b96b52f 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -1,4 +1,5 @@ use super::dynamic::{fit_overrides, type_id, type_param}; +use super::symbolism::{Grid, Mean, Method, Sides, look, mean, method_param, natural_side, record_set_density, spacing, spray_modes, wrap_angle}; use super::{ Affine, AppearanceItem, Arc, CURRENT_SYMBOL, Color, Document, EngineError, FillLayer, HALF, Node, NodeId, NodeKind, Paint, Point, Result, SIZES_KEY, Session, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, Value, Vec2, bad, brush, color_param, ids_json, json, @@ -906,16 +907,40 @@ pub(super) fn symbol_select_instances(s: &mut Session, p: &Value) -> Result Result> { + Ok(samples(p, cmd)?.into_iter().map(|(q, _)| q).collect()) +} + +/// The stroke's points, each with its pen pressure: the third number of `[x, y, pressure]`, kept +/// within 0..1, and 1 for a point that gives none (or null). A pressure that isn't a number is an +/// error. +fn samples(p: &Value, cmd: &str) -> Result> { let a = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "missing points [[x,y]…]"))?; - let v: Vec = a.iter().filter_map(|q| Some(Point::new(q.get(0)?.as_f64()?, q.get(1)?.as_f64()?))).collect(); - if v.is_empty() || v.iter().any(|q| !q.x.is_finite() || !q.y.is_finite()) { + let mut v = Vec::with_capacity(a.len()); + for q in a { + let (Some(x), Some(y)) = (q.get(0).and_then(Value::as_f64), q.get(1).and_then(Value::as_f64)) else { continue }; + let pressure = match q.get(2) { + None | Some(Value::Null) => 1.0, + Some(f) => f.as_f64().filter(|f| f.is_finite()).ok_or_else(|| bad(cmd, format!("a point's pressure must be a number, not {f}")))?, + }; + v.push((Point::new(x, y), pressure.clamp(0.0, 1.0))); + } + if v.is_empty() || v.iter().any(|(q, _)| !q.x.is_finite() || !q.y.is_finite()) { return Err(bad(cmd, "points must be finite [x,y] pairs")); } Ok(v) } +/// The fill of the graphic style `p` names with `style`, else of the document's first style after +/// the default one. +fn style_paint(d: &Document, p: &Value) -> Option { + match str_param(p, "style") { + Some(n) => d.graphic_styles.iter().find(|g| g.name == n).map(|g| g.appearance.fill_paint()), + None => d.graphic_styles.get(1).or(d.graphic_styles.first()).map(|g| g.appearance.fill_paint()), + } +} + /// Deterministic per-point jitter in [-1, 1]² (so previews re-applied on the snapshot agree). -fn jitter(i: usize, q: Point) -> (f64, f64, f64) { +pub(super) fn jitter(i: usize, q: Point) -> (f64, f64, f64) { let mut h: u64 = 0xcbf2_9ce4_8422_2325 ^ i as u64; for v in [(q.x * 16.0).round() as i64 as u64, (q.y * 16.0).round() as i64 as u64] { h ^= v; @@ -926,7 +951,8 @@ fn jitter(i: usize, q: Point) -> (f64, f64, f64) { (f(0), f(1), f(2)) } -fn is_symbol_set(n: &Node) -> bool { +/// Whether `n` is a symbol set: the group the Symbol Sprayer sprays instances into. +pub fn is_symbol_set(n: &Node) -> bool { matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.name.as_deref() == Some("Symbol Set") } @@ -939,6 +965,20 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result { let density = number_or(p, "density", 5.0, C)?.clamp(1.0, 10.0); let scale = number_or(p, "scale", 1.0, C)?.clamp(0.01, 100.0); let alt = switch_or(p, "alt", false, C)?; + let modes = spray_modes(p, C)?; + crate::cmd::paint::check_keep_model(p, C)?; + let stain = match color_param(p, "color", C)? { + Some(c) => crate::cmd::paint::new_color(s, p, c), + None => s.paint.fill.color().unwrap_or(Color::BLACK), + }; + if let Some(v) = p.get("style").filter(|v| !v.is_string()) { + return Err(bad(C, format!("`style` must be a graphic style's name, not {v}"))); + } + let style = style_paint(&st.doc, p); + // Style: User Defined uses the style `style` names, so one the document does not have is an error. + if let Some(n) = str_param(p, "style").filter(|_| !modes.style && style.is_none()) { + return Err(bad(C, format!("unknown graphic style `{n}`"))); + } let size = natural_size(&st.doc, &name); let set = st.selection.objects.first().copied().filter(|id| st.selection.len() == 1 && st.doc.node(*id).is_some_and(is_symbol_set)); // Only a new Symbol Set needs a layer that takes new art. @@ -965,26 +1005,82 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result { } return Ok(json!({ "count": n })); } - // Keep instances at least this far apart along the stroke (denser = closer). - let min_gap = size.0.max(size.1) * scale * (1.15 - density * 0.1).max(0.1); - let mut placed: Vec = vec![]; + let side = natural_side(&st.doc, &name); + // The symbol's longest side as drawn at its own size: its art's, when it has no recorded size. + let recorded = stored_natural_size(&st.doc, &name).filter(|(w, h)| w.is_finite() && h.is_finite() && *w > 0.0 && *h > 0.0); + let extent = match recorded { + Some((w, h)) => w.max(h), + None => { + let art = st.doc.symbol_art_bounds(&name).map(|r| r.width().max(r.height())); + art.filter(|e| e.is_finite() && *e > 0.0).unwrap_or(size.0.max(size.1)) + } + }; + // The scale a new instance is placed at, before the User Defined size jitter. Size: Average is + // the mean size on the page under the brush, of any symbol, or the symbol's own size with none + // there (not `scale`). + let placed_scale = |near: Option<&Mean>| { + if modes.size { near.map(|m| m.size / side).filter(|k| k.is_finite() && *k > 0.0).unwrap_or(1.0) } else { scale } + }; + // The instances the selected set has, for the values a new one takes as their average. + let existing = set.filter(|_| modes.any_average()).map(|g| { + let d = &st.doc; + let mut sides = Sides::new(); + let looks = d.node(g).and_then(|n| n.children()).into_iter().flatten().filter_map(|c| look(d, c, &mut sides)).collect(); + Grid::new(looks, radius) + }); + // Each instance to add: where, the mean of the set's instances under the brush there, and the + // direction of the stroke there (None while the pointer has not moved). + let mut placed: Vec<(Point, Option, Option)> = vec![]; for (i, q) in pts.iter().enumerate() { let (jx, jy, _) = jitter(i, *q); let c = Point::new(q.x + jx * radius * 0.5, q.y + jy * radius * 0.5); - if placed.last().is_some_and(|l| l.distance(c) < min_gap) && i > 0 { + let near = existing.as_ref().and_then(|g| g.mean(*q, radius, modes.scrunch)); + // Keep instances at least this far apart along the stroke (denser = closer), by the size + // the instance is placed at. + let min_gap = extent * placed_scale(near.as_ref()) * spacing(density); + // Scrunch: Average spaces new instances as the ones under the brush are spaced. + let gap = near.as_ref().and_then(|m| m.gap).filter(|_| modes.scrunch).unwrap_or(min_gap); + if placed.last().is_some_and(|(l, ..)| l.distance(c) < gap) && i > 0 { continue; } - placed.push(c); + let along = pts.get(i + 1).unwrap_or(q).to_vec2() - pts.get(i.saturating_sub(1)).unwrap_or(q).to_vec2(); + placed.push((c, near, (along.hypot() > 1e-9).then_some(along))); } let count = placed.len(); let reg = s.doc()?.doc.symbol_registration(&name); let id = s.edit("Symbol Sprayer", |d, sel| { let mut nodes = vec![]; - for (i, c) in placed.iter().enumerate() { + for (i, (c, near, along)) in placed.iter().enumerate() { let (_, _, js) = jitter(i + 7, *c); - let k = scale * (1.0 + js * 0.1); + let near = near.as_ref(); + // User Defined: the symbol's own size, turned the way the stroke runs, opaque, stained + // with the fill color and given the style, each in full. Size: Average has no size jitter. + let k = if modes.size { placed_scale(near) } else { scale * (1.0 + js * 0.1) }; + let angle = if modes.spin { near.map_or(0.0, |m| m.angle) } else { along.map_or(0.0, |v| v.atan2()) }; + let turn = Affine::translate(c.to_vec2()) * Affine::rotate(angle) * Affine::translate(-c.to_vec2()); let id = d.alloc_id(); - nodes.push(Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: place_xf(*c, size, reg) * Affine::scale(k) })); + let mut n = Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: turn * place_xf(*c, size, reg) * Affine::scale(k) }); + if modes.screen + && let Some(m) = near + { + n.opacity = (m.opacity as f32).clamp(0.0, 1.0); + } + // The stain and the style are both the instance's fill: the style, set last, replaces + // the stain, an averaged one too when the instances under the brush have a fill. + let averaged = near.filter(|m| m.amount > 0.0).and_then(|m| Some((m.paint.clone()?, m.amount as f32))); + let mut fill = if modes.stain { averaged.clone() } else { Some((Paint::solid(stain), 1.0)) }; + if modes.style { + fill = averaged.or(fill); + } else if let Some(paint) = style.as_ref().filter(|p| !matches!(p, Paint::None)) { + // A style without a fill (the default style) gives none. + fill = Some((paint.clone(), 1.0)); + } + if let Some((paint, amount)) = fill { + let mut f = FillLayer::new(paint); + f.opacity = amount.clamp(0.0, 1.0); + n.appearance.items.insert(0, AppearanceItem::Fill(f)); + } + nodes.push(n); } let gid = match set { Some(g) => { @@ -1001,13 +1097,18 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result { gid } }; + // A new set has the density it is sprayed at; more instances sprayed into a set leave the + // density the set has. + if set.is_none() { + record_set_density(d, &[gid], density); + } sel.set([gid]); Ok(gid) })?; Ok(json!({ "id": id.0, "count": count })) } -fn instance_center(n: &Node) -> Option { +pub(super) fn instance_center(n: &Node) -> Option { match &n.kind { NodeKind::SymbolInstance { xf, .. } => Some(*xf * Point::ZERO), _ => None, @@ -1021,10 +1122,15 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { return Err(bad(C, format!("unknown tool `{tool}`"))); } crate::cmd::paint::check_keep_model(p, C)?; - let pts = points(p, C)?; + let pts = samples(p, C)?; let radius = number_or(p, "radius", 40.0, C)?.clamp(1.0, 2000.0); let intensity = number_or(p, "intensity", 5.0, C)?.clamp(1.0, 10.0) / 10.0; let alt = switch_or(p, "alt", false, C)?; + let use_pressure = switch_or(p, "usePressure", false, C)?; + let proportional = switch_or(p, "proportional", true, C)?; + let affects_density = switch_or(p, "affectsDensity", false, C)?; + // The Symbol Shifter has no Method. + let method = if tool == "shift" { method_param(p, C).map(|_| Method::UserDefined)? } else { method_param(p, C)? }; // Refused while an object of a dynamic instance's art is selected: the instance stays as it is. crate::cmd::edit::refuse_symbol_part(s)?; let st = s.doc()?; @@ -1032,10 +1138,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { Some(c) => crate::cmd::paint::new_color(s, p, c), None => s.paint.fill.color().unwrap_or(Color::BLACK), }; - let style_paint = match str_param(p, "style") { - Some(n) => st.doc.graphic_styles.iter().find(|g| g.name == n).map(|g| g.appearance.fill_paint()), - None => st.doc.graphic_styles.get(1).or(st.doc.graphic_styles.first()).map(|g| g.appearance.fill_paint()), - }; + let style_paint = style_paint(&st.doc, p); let candidates: Vec = { let d = &st.doc; let mut v = vec![]; @@ -1065,62 +1168,165 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { "screen" => "Symbol Screener", _ => "Symbol Styler", }; - let count = s.edit(label, |d, _| { + // Random: each instance's share of the tool's change, from none of it to twice it, the same + // for the whole stroke (and for every preview of it). + let first = pts.first().map_or(Point::ZERO, |(q, _)| *q); + let share = |id: NodeId| if method == Method::Random { jitter(id.0 as usize, first).0 + 1.0 } else { 1.0 }; + // No undo step when no instance changes (none under the brush, or Average with each at the mean). + let count = crate::cmd::colorcmds::edit_if_changed(s, label, |orig, d| { let mut touched = std::collections::BTreeSet::new(); - for (j, q) in pts.iter().enumerate() { - let delta = if j > 0 { *q - pts[j - 1] } else { Vec2::ZERO }; + let mut sides = Sides::new(); + for (j, (q, pressure)) in pts.iter().enumerate() { + let delta = if j > 0 { *q - pts[j - 1].0 } else { Vec2::ZERO }; + // Use Pressure Pen: the pen's pressure at the point is the intensity there. + let strength = if use_pressure { *pressure } else { intensity }; + // Average: the mean of the instances under the brush, as they are at this point. + let target = (method == Method::Average) + .then(|| { + let under = |n: &&Node| instance_center(n).is_some_and(|c| c.distance(*q) <= radius); + let looks: Vec<_> = candidates.iter().filter_map(|id| d.node(*id).filter(under).and_then(|n| look(d, n, &mut sides))).collect(); + mean(&looks.iter().collect::>(), *q, false) + }) + .flatten(); for id in &candidates { - let Some(n) = d.node_mut(*id) else { continue }; - let Some(c) = instance_center(n) else { continue }; + let Some(c) = d.node(*id).and_then(instance_center) else { continue }; let dist = c.distance(*q); if dist > radius { continue; } - let w = intensity * (1.0 - dist / radius).max(0.0); + let w = strength * (1.0 - dist / radius).max(0.0); if w <= 0.0 { continue; } - touched.insert(*id); + // Average needs the instance's own values, so it leaves an instance without a size + // as it is; the other methods change it as before. + // The instance's own values are read for Average only. + let own = (method == Method::Average).then(|| d.node(*id).and_then(|n| look(d, n, &mut sides))).flatten(); + let avg = match (method, &target, own) { + (Method::Average, Some(t), Some(cur)) => Some((t, cur)), + // No mean under the brush (every instance there without a size), or none of + // its own. + (Method::Average, ..) => continue, + _ => None, + }; + // Average leaves an instance that already has the mean as it is. + let at_mean = avg.as_ref().is_some_and(|(t, cur)| match tool.as_str() { + "scrunch" => { + let out = (c - t.middle).hypot(); + out <= 1e-9 || (t.reach - out).abs() < 1e-9 + } + "size" => (t.size / cur.size - 1.0).abs() < 1e-9, + "spin" => wrap_angle(t.angle - cur.angle).abs() < 1e-9, + "stain" | "style" => { + (t.amount - cur.fill.as_ref().map_or(0.0, |f| f.1)).abs() < 1e-6 && (cur.fill.is_some() || t.paint.is_none()) + } + "screen" => (t.opacity - cur.opacity).abs() < 1e-6, + _ => false, + }); + if at_mean { + continue; + } + let Some(n) = d.node_mut(*id) else { continue }; + // Counted only when it changes: Random can give an instance no share of the change. + let before = n.clone(); let about = |m: Affine| Affine::translate(c.to_vec2()) * m * Affine::translate(-c.to_vec2()); + let share = share(*id); match tool.as_str() { "shift" => n.transform(Affine::translate(delta * w.min(1.0)), false), "scrunch" => { - let v = (*q - c) * (0.15 * w) * if alt { -1.0 } else { 1.0 }; + let v = match &avg { + // Toward the instances' mean distance from their middle. + Some((t, _)) => { + let out = c - t.middle; + if out.hypot() > 1e-9 { out * ((t.reach - out.hypot()) / out.hypot() * w.min(1.0)) } else { Vec2::ZERO } + } + None => (*q - c) * (0.15 * w * share) * if alt { -1.0 } else { 1.0 }, + }; n.transform(Affine::translate(v), false); } "size" => { - let k = 1.0 + 0.08 * w; - n.transform(about(Affine::scale(if alt { 1.0 / k } else { k })), false); + let k = match &avg { + Some((t, cur)) => (t.size / cur.size).powf(w.min(1.0)), + None => (1.0 + 0.08 * w).powf(if alt { -share } else { share }), + }; + // Without Proportional Resizing a drag resizes along its own direction: a + // level drag the width, an upright one the height. A click resizes both. + // The first point of a drag takes the direction to the second. + let along = if j > 0 { delta } else { pts.get(1).map_or(Vec2::ZERO, |(next, _)| *next - *q) }; + let (kx, ky) = if proportional || avg.is_some() || along.hypot() <= 1e-9 { + (k, k) + } else { + let level = along.x.abs() / (along.x.abs() + along.y.abs()); + (k.powf(2.0 * level), k.powf(2.0 * (1.0 - level))) + }; + n.transform(about(Affine::scale_non_uniform(kx, ky)), false); + // Resizing Affects Density: instances move away from the brush's center as + // they grow and toward it as they shrink. + if affects_density { + n.transform(Affine::translate((c - *q) * ((kx * ky).sqrt() - 1.0)), false); + } } "spin" => { - // Turn towards the drag direction; a click spins a little. - let a = if delta.hypot() > 1e-9 { (c - *q).cross(delta).signum() * 0.1 * w } else { 0.05 * w }; - n.transform(about(Affine::rotate(if alt { -a } else { a })), false); + let a = match (&avg, method) { + (Some((t, cur)), _) => wrap_angle(t.angle - cur.angle) * w.min(1.0), + // A turn either way, whichever way the drag runs. + (None, Method::Random) => 0.1 * w * (share - 1.0), + // Turn towards the drag direction; a click spins a little. + (None, _) if delta.hypot() > 1e-9 => (c - *q).cross(delta).signum() * 0.1 * w, + (None, _) => 0.05 * w, + }; + n.transform(about(Affine::rotate(if alt && avg.is_none() { -a } else { a })), false); } "stain" | "style" => { let paint = if tool == "style" { style_paint.clone().unwrap_or(Paint::solid(color)) } else { Paint::solid(color) }; - if tool == "style" && alt { - n.appearance.items.clear(); - continue; - } - let cur = n.appearance.fill().filter(|f| f.paint == paint).map(|f| f.opacity).unwrap_or(0.0); - let step = if tool == "style" { 1.0 } else { 0.15 * w as f32 }; - let o = if alt { (cur - step).max(0.0) } else { (cur + step).min(1.0) }; + let (paint, o) = match &avg { + // Toward the mean amount, keeping the stain or style the instance has. + Some((t, look)) => { + let (own, cur) = look.fill.clone().map_or((None, 0.0), |(p, o)| (Some(p), o)); + (own.or(t.paint.clone()).unwrap_or(paint), (cur + (t.amount - cur) * w.min(1.0)) as f32) + } + // Alt with the Symbol Styler removes the instance's appearance. + None if tool == "style" && alt => { + n.appearance.items.clear(); + (paint, 0.0) + } + None => { + let cur = n.appearance.fill().filter(|f| f.paint == paint).map(|f| f.opacity).unwrap_or(0.0); + let step = match (tool.as_str(), method) { + // Random: the instance's share of the style, scaled by the + // brush strength there. + ("style", Method::Random) => (share / 2.0 * w.min(1.0)) as f32, + ("style", _) => 1.0, + _ => (0.15 * w * share) as f32, + }; + (paint, if alt { cur - step } else { cur + step }) + } + }; n.appearance.items.retain(|i| !matches!(i, AppearanceItem::Fill(_))); if o > 0.0 { let mut f = FillLayer::new(paint); - f.opacity = o; + f.opacity = o.min(1.0); n.appearance.items.insert(0, AppearanceItem::Fill(f)); } } _ => { - let step = (0.1 * w) as f32; - n.opacity = if alt { (n.opacity + step).min(1.0) } else { (n.opacity - step).max(0.05) }; + let step = (0.1 * w * share) as f32; + n.opacity = match &avg { + // The mean may be below the 5% the Screener otherwise stops at. + Some((t, _)) => (n.opacity + ((t.opacity - f64::from(n.opacity)) * w.min(1.0)) as f32).clamp(0.0, 1.0), + None if alt => (n.opacity + step).min(1.0), + None => (n.opacity - step).max(0.05), + }; } } + if *n != before { + touched.insert(*id); + } } } - Ok(touched.len()) + // An instance the stroke moved away and back again is not counted. + touched.retain(|id| d.node(*id) != orig.node(*id)); + Ok((touched.len(), !touched.is_empty())) })?; Ok(json!({ "count": count })) } diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 739759afe6..904e80df61 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; @@ -145,7 +145,7 @@ pub fn specs() -> Vec { "Make", ["Object", "Image Trace"], None, - "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, split into at least colorDetail colors where the image has that many before colors that look alike merge (less than 5 apart in Oklab × 100 and thoroughly mixed, or less than 1.5 and mixed in patches), automatic: flat art with its own colours, else as many as the tones need without fullTone's least count, merging close RGB colors, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", + "{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, split into at least colorDetail colors where the image has that many before colors that look alike merge (less than 5 apart in Oklab × 100 and thoroughly mixed, or less than 1.5 and mixed in patches), automatic: flat art with its own colours, else as many as the tones need without fullTone's least count, merging close RGB colors, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult; the Split view keeps the traced object's divider, else 0.5, and imageTrace.setView sets it), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}", has_selection_or_ids, |s, p| trace_make(s, p, false) ), @@ -181,7 +181,7 @@ pub fn specs() -> Vec { "Image Trace View", [], None, - "{id?|ids?: Image Trace objects (default: selection), view: \"tracingResult\"|\"tracingResultWithOutlines\"|\"outlines\"|\"outlinesWithSourceImage\"|\"sourceImage\"} how they draw on screen; exports, printing and Expand keep the tracing result → {ids, view}", + "{id?|ids?: Image Trace objects (default: selection), view: \"tracingResult\"|\"tracingResultWithOutlines\"|\"outlines\"|\"outlinesWithSourceImage\"|\"sourceImage\"|\"split\" (the source image on the part of the image left of a divider across it, and the tracing result everywhere else), split?: 0-1 (the divider: the fraction of the source image's width, from its left edge, that shows the image; kept as it was when omitted, 0.5 for a new one)} how they draw on screen; exports, printing and Expand keep the tracing result, and tracing again keeps the view and the divider → {ids, view, split (view split: the first object's divider)}", has_selection_or_ids, trace_set_view ), diff --git a/crates/engine/src/cmd/buildcmds/live_paint.rs b/crates/engine/src/cmd/buildcmds/live_paint.rs index 2eea5c2c00..f943766452 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. @@ -37,7 +37,7 @@ fn check_live_paint_takes(d: &Document, roots: &[NodeId]) -> Result<()> { fn make_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result<(NodeId, usize, usize)> { check_live_paint_takes(d, roots)?; if roots.iter().any(|r| d.node(*r).is_some_and(is_live_paint)) { - return merge_live(d, sel, roots); + return merge_live(d, sel, roots, false); } let mut sources = vec![]; for r in roots { @@ -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()?; @@ -140,8 +178,10 @@ impl Carried { /// Add the other `roots` (back → front) to the first Live Paint group among them, which keeps its /// id, the paint of its faces and edges, and its own properties apart from the Gap Options, which -/// are merged; returns (group, faces, edges). -fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result<(NodeId, usize, usize)> { +/// are merged; returns (group, faces, edges). When the groups and paths hold no path outline +/// between them, `keep_empty` leaves the group with its paths in its sources group and no faces or +/// edges; without it, that is an error. +fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId], keep_empty: bool) -> Result<(NodeId, usize, usize)> { let target = roots .iter() .copied() @@ -149,11 +189,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![]; @@ -169,7 +214,14 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result // Merge applies the Gap Options' merge rules to the groups' options, bottom-most first. let groups: Vec = roots.iter().filter_map(|r| d.node(*r)).filter(|n| is_live_paint(n)).map(Node::gap_options).collect(); let options = merged_gap_options(&groups); - let (children, nf, ne) = build_children(d, sources, options.max_gap())?; + let (children, nf, ne) = if keep_empty && source_shapes(&sources).0.is_empty() { + let mut src = Node::group(d.alloc_id(), sources); + src.name = Some(SOURCES_NAME.into()); + src.visible = false; + (vec![Arc::new(src)], 0, 0) + } else { + build_children(d, sources, options.max_gap())? + }; // The group keeps its name, lock, visibility, transparency, appearance, opacity mask, graphic // style link and the rest; its children are made again and its Gap Options set to the merged ones. let mut g = old; @@ -223,23 +275,26 @@ pub(super) fn lp_merge(s: &mut Session, p: &Value) -> Result { if let Some(reply) = lone_live_group(s, &roots)? { return Ok(reply); } - let (id, faces, edges) = s.edit("Merge Live Paint", |d, sel| merge_live(d, sel, &roots))?; + let (id, faces, edges) = s.edit("Merge Live Paint", |d, sel| merge_live(d, sel, &roots, false))?; 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() } @@ -255,10 +310,227 @@ pub(crate) fn merge_drawn_in_isolation(s: &mut Session, g: NodeId) -> Result = std::iter::once(g).chain(drawn).collect(); - s.edit("Merge Live Paint", |d, sel| merge_live(d, sel, &roots))?; + s.edit("Merge Live Paint", |d, sel| merge_live(d, sel, &roots, false))?; Ok(true) } +/// Where a row sits for Live Paint: among the paths of a Live Paint group (in its sources group, +/// at any depth), directly in a Live Paint group, or neither. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Spot { + Source(NodeId), + In(NodeId), + Outside, +} + +/// The [`Spot`] of a row whose parent is `parent` (None: the top level). +fn spot_in(d: &Document, parent: Option) -> 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 +} + +/// Whether a shown row whose parent is `parent`, among Live Paint group `g`'s paths, gives `g` faces +/// and edges: every group between it and `g`'s sources group is shown. +fn shown_in_sources(d: &Document, parent: Option, g: NodeId) -> bool { + let src = d.node(g).and_then(b::sources).map(|s| s.id); + let mut at = parent; + while let Some(x) = at { + if Some(x) == src { + return true; + } + if !d.node(x).is_some_and(|n| n.visible) { + return false; + } + at = d.parent_of(x); + } + true +} + +/// 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 change no faces unless a shown row goes into or out +/// of a hidden group there; rows moved among a group's own children change no faces. A group's +/// sources group itself stays in the group. +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, and a group's sources group moved out of the + /// group. + pub(crate) fn plan(d: &Document, rows: &[NodeId], parent: Option, copy: bool) -> Result { + if !copy { + for r in rows { + if let Some(g) = d.parent_of(*r) + && parent != Some(g) + && d.node(g).filter(|n| is_live_paint(n)).and_then(b::sources).is_some_and(|s| s.id == *r) + { + return Err(EngineError::Other("a Live Paint group's sources group stays in the group: move the paths in it instead".into())); + } + } + } + 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 (r, f) in rows.iter().zip(&from) { + let Spot::Source(g) = *f else { continue }; + // A shown row that goes into or out of a hidden group among the same paths starts or + // stops giving the group faces and edges. + let shown_changes = + *f == to && d.node(*r).is_some_and(|n| n.visible) && shown_in_sources(d, d.parent_of(*r), g) != shown_in_sources(d, parent, g); + if (*f != to || shown_changes) && !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(); + // Rows that join a group with no path outline among them keep the move: the group + // is left with no faces or edges, as when its last path leaves it. + merge_live(d, sel, &roots, true)?; + } 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/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 203fd62338..90c505cfb6 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -58,6 +58,12 @@ fn view_param(cmd: &str, p: &Value) -> Result> { v.as_str().and_then(TraceView::from_id).map(Some).ok_or_else(|| bad(cmd, format!("view must be one of {}", ids()))) } +/// The `split` param (the Split view's divider, 0 to 1), if given. +fn split_param(cmd: &str, p: &Value) -> Result> { + let Some(v) = p.get("split").filter(|v| !v.is_null()) else { return Ok(None) }; + v.as_f64().filter(|f| (0.0..=1.0).contains(f)).map(Some).ok_or_else(|| bad(cmd, "split must be a number from 0 to 1")) +} + /// A saved Image Trace preset ([`crate::Prefs::trace_presets`]): a name and its settings. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] @@ -1026,9 +1032,14 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result Result> { pub(super) fn trace_set_view(s: &mut Session, p: &Value) -> Result { const C: &str = "imageTrace.setView"; let view = view_param(C, p)?.ok_or_else(|| bad(C, "view is required"))?; + let split = split_param(C, p)?; let targets = trace_targets(s, p)?; let d = &s.doc()?.doc; - if targets.iter().all(|g| d.node(*g).is_some_and(|n| n.trace_view() == view)) { - return Ok(json!({ "ids": ids_json(&targets), "view": view.id() })); + let result = |d: &vectorcraft_doc::Document| { + let mut r = json!({ "ids": ids_json(&targets), "view": view.id() }); + if view == TraceView::Split + && let Some(n) = targets.first().and_then(|g| d.node(*g)) + { + r["split"] = json!(split.unwrap_or_else(|| n.trace_split())); + } + r + }; + if targets.iter().all(|g| d.node(*g).is_some_and(|n| n.trace_view() == view && split.is_none_or(|f| n.trace_split() == f))) { + return Ok(result(d)); } s.edit("Image Trace View", |d, _| { for g in &targets { let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?; + if n.extras_if_any().and_then(|e| e.trace.as_deref()).is_none_or(|t| !t.is_object()) { + n.extras_mut().trace = Some(Box::new(json!({ "preset": "Custom" }))); + } if let Some(t) = n.extras_if_any().and_then(|e| e.trace.as_deref_mut()).and_then(Value::as_object_mut) { t.insert("view".into(), json!(view.id())); - } else { - n.extras_mut().trace = Some(Box::new(json!({ "preset": "Custom", "view": view.id() }))); + if let Some(f) = split { + t.insert("split".into(), json!(f)); + } } } Ok(()) })?; - Ok(json!({ "ids": ids_json(&targets), "view": view.id() })) + Ok(result(&s.doc()?.doc)) } pub(super) fn trace_release(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 4e086569ae..c42289ccc7 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -47,10 +47,19 @@ pub fn specs() -> Vec { "Swatch Conflicts", [], None, - "{} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none", + "{profileMismatch?: as edit.paste} → {swatches: [{name, document, clipboard, spot}]} the global or spot swatches the copied objects use whose name the active document gives another colour (`document`/`clipboard`: #rrggbb, the pasted colour as the paste brings it, converted when profileMismatch or the policy converts it): Paste asks Merge or Add for each (pass the answer as edit.paste* {swatchConflict}). Pasting back into the document the objects came from raises none, unless the paste converts its colours", has_doc, conflicts ), + cmd!( + query "clipboard.profileMismatch", + "Paste Profile Mismatch", + [], + None, + "{sourceDocument?, ids?: as edit.dropSelection, allArtboards?: false (true: for edit.pasteOnAllArtboards, which leaves the background colors of copied artboards behind)} → {mismatches: [{model: \"rgb\"|\"cmyk\", clipboard, document, default: \"preserveNumbers\"|\"convert\", convertible}]} the color models whose colors the copied objects (with sourceDocument and ids: the objects edit.dropSelection drops) use and whose profile in the document they were copied from (its assigned profile, else the working space then; an assigned profile removed since: the working space) is not the active document's: Paste keeps their numbers or converts them into the document's profile as edit.paste* and edit.dropSelection {profileMismatch} say, else as the model's policy of edit.colorSettings does (convert: converts; the others: keeps the numbers). convertible: false when either profile is not available (removed with color.removeProfile): the colors then keep their numbers whatever the choice, and default is preserveNumbers. With askMismatchPaste on, the desktop app asks first. Objects from outside an open document have none", + has_doc, + profile_mismatch + ), ]; v.extend(flavours::specs()); v @@ -100,6 +109,15 @@ pub struct Clipboard { /// The selected ruler guides copied with (or without) the objects (#3226), as canvas guides on /// no layer: pasting puts them on the layer new art goes to, moved as the objects are. pub guides: Vec, + /// The RGB and CMYK profiles the objects' colors showed through in the document they were + /// copied from (its assigned profiles, else the working spaces then), by name; none for objects + /// from outside an open document. Paste compares them with the destination's + /// ([`super::colormgmt::paste_mismatches`]). + pub source_profiles: Option<[String; 2]>, + /// The colors were converted for this paste ([`super::colormgmt::paste_profiles`]): back in the + /// source document its resources of the same names are compared with them, as another + /// document's are, while its layers are still found by id. + pub colors_converted: bool, } /// The layer an object was copied from, as Paste Remembers Layers finds it again: the top-level @@ -264,6 +282,7 @@ impl Clipboard { pub fn from_node(st: &DocState, node: Node) -> Self { let mut clip = Self::gather(&st.doc, vec![node]); clip.source_doc = Some(st.uid); + clip.source_profiles = Some(super::colormgmt::effective_profiles(&st.doc)); clip } @@ -335,6 +354,7 @@ impl Clipboard { source_artboard: board.and_then(|i| d.artboards.get(i)).map(|a| a.rect), source_layers, source_doc: Some(st.uid), + source_profiles: Some(super::colormgmt::effective_profiles(d)), ..Self::gather(d, nodes) } } @@ -369,7 +389,7 @@ impl Clipboard { /// The swatch name conflicts pasting into `st` raises, as (pasted, document) swatches: none /// back in the document the objects came from. pub fn swatch_conflicts<'a>(&'a self, st: &'a DocState) -> Vec<(&'a Swatch, &'a Swatch)> { - if self.source_doc == Some(st.uid) { + if self.source_doc == Some(st.uid) && !self.colors_converted { return vec![]; } self.conflicts(&st.doc, &self.used()) @@ -419,6 +439,56 @@ impl Clipboard { d } + /// The clipboard with every color of its objects and of the resources it carries (swatches, + /// symbols, patterns, graphic styles, brushes, character and paragraph styles, the background + /// colors of copied artboards) mapped by `conv`, as Document Color Mode maps a document's + /// ([`super::colormgmt::convert_art_and_style_colors`]). + /// Images keep their pixels. + pub(crate) fn with_colors(&self, conv: &dyn Fn(&vectorcraft_color::Color) -> vectorcraft_color::Color) -> Self { + let mut d = self.to_document(); + // Only what the clipboard carries: not the swatches, graphic styles and brushes every new + // document starts with. + d.swatches = self.swatches.clone().into(); + d.swatch_groups = Default::default(); + d.graphic_styles = self.graphic_styles.clone().into(); + vectorcraft_brush::store(&mut d, &self.brushes); + // Not the stand-in document's own artboard and Document Setup colors: only what the + // clipboard carries is mapped. + super::colormgmt::convert_art_and_style_colors(&mut d, conv); + // `to_document` puts the objects in its one layer. + let nodes = d.layers.first().and_then(|l| l.children()).map(|ch| ch.iter().map(|n| (**n).clone()).collect()).unwrap_or_default(); + Self { + nodes, + symbols: d.symbols.clone(), + patterns: d.patterns.clone(), + swatches: d.swatches.to_vec(), + graphic_styles: d.graphic_styles.to_vec(), + char_styles: d.char_styles.to_vec(), + para_styles: d.para_styles.to_vec(), + brushes: vectorcraft_brush::library(&d), + images: self.images.clone(), + symbol_options: self.symbol_options.clone(), + source_artboard: self.source_artboard, + source_layers: self.source_layers.clone(), + source_doc: self.source_doc, + // The background colors of copied artboards map too. + artboards: self + .artboards + .iter() + .map(|a| { + let mut a = a.clone(); + if let Some(c) = a.color.as_mut() { + *c = conv(c); + } + a + }) + .collect(), + guides: self.guides.clone(), + source_profiles: self.source_profiles.clone(), + colors_converted: self.colors_converted, + } + } + /// The objects as standalone SVG (`None` when there are none). pub fn svg(&self) -> Option { if !self.has_art() { @@ -486,17 +556,33 @@ fn import_svg(s: &mut Session, p: &Value) -> Result { Ok(json!({ "count": s.load_clipboard(clip, p)? })) } -fn conflicts(s: &mut Session, _: &Value) -> Result { +fn conflicts(s: &mut Session, p: &Value) -> Result { let hex = |w: &Swatch| w.paint.color().map(|c| c.to_hex()); - let list: Vec = s - .clipboard - .swatch_conflicts(s.doc()?) + // The swatches as the paste brings them: converted from another profile when it converts. + let profile = super::colormgmt::PasteProfile::param(p, "clipboard.conflicts")?; + let st = s.doc()?; + let (converted, _) = super::colormgmt::paste_profiles(&s.clipboard, &st.doc, profile, true); + let list: Vec = converted + .as_ref() + .unwrap_or(&s.clipboard) + .swatch_conflicts(st) .into_iter() .map(|(c, t)| json!({"name": c.name, "document": hex(t), "clipboard": hex(c), "spot": c.spot})) .collect(); Ok(json!({ "swatches": list })) } +fn profile_mismatch(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "clipboard.profileMismatch"; + // With `sourceDocument` and `ids`, the objects a drop brings, else the clipboard's. + let dropped = if p.get("sourceDocument").is_some() || p.get("ids").is_some() { Some(super::edit::drop_clip(s, p, CMD)?) } else { None }; + let clip = dropped.as_ref().unwrap_or(&s.clipboard); + // Paste on All Artboards leaves the copied artboards, and so their backgrounds, behind. + let all_artboards = super::switch_or(p, "allArtboards", false, CMD)?; + let list: Vec = super::colormgmt::paste_mismatches(clip, &s.doc()?.doc, !all_artboards).iter().map(|m| m.to_json()).collect(); + Ok(json!({ "mismatches": list })) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 0a98ddd9bc..583341f2a4 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -20,12 +20,14 @@ use std::sync::Arc; use serde_json::{Map, Value, json}; use vectorcraft_brush::Brush; use vectorcraft_color::{Color, Paint, Swatch}; +use vectorcraft_doc::text::{KINSOKU_NAME_MAX, KINSOKU_SETS_MAX}; use vectorcraft_doc::{ - Appearance, AppearanceItem, Document, Effect, GraphicStyle, Node, NodeKind, PatternDef, Symbol, SymbolExportType, SymbolNineSlice, - SymbolRegistration, TextStyleDef, + Appearance, AppearanceItem, Document, Effect, GraphicStyle, Kinsoku, KinsokuSet, Node, NodeKind, PatternDef, Symbol, SymbolExportType, + SymbolNineSlice, SymbolRegistration, TextStyleDef, }; use super::super::brushsym::{set_natural_size, stored_natural_size}; +use super::super::typecmd::refresh_bounds; use super::super::patterncmds::add_pattern; use super::super::{EngineError, Result, bad, unique_name}; @@ -517,6 +519,36 @@ fn copy_of(base: &str, name: &str) -> bool { name == base || name.strip_prefix(base).and_then(|r| r.strip_prefix(' ')).is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())) } +/// The `i`th numbered copy of a Kinsoku Shori set's name `base` ("name 2"), within +/// [`KINSOKU_NAME_MAX`]: when it would be too long, the number takes the place of the name's last +/// characters, and spaces left at the end of what remains are dropped. +fn numbered_kinsoku_name(base: &str, i: usize) -> String { + let number = format!(" {i}"); + let head: String = base.chars().take(KINSOKU_NAME_MAX.saturating_sub(number.chars().count())).collect(); + format!("{}{number}", head.trim_end()) +} + +/// [`unique_name`] for a pasted Kinsoku Shori set among `sets` (a document's custom sets, any +/// case), with names that fit [`KINSOKU_NAME_MAX`] ([`numbered_kinsoku_name`]). +fn unique_kinsoku_name(base: &str, sets: &[KinsokuSet]) -> String { + let taken = |n: &str| KinsokuSet::named(sets, n).is_some(); + if !taken(base) { + return base.to_string(); + } + (2..).map(|i| numbered_kinsoku_name(base, i)).find(|n| !taken(n)).unwrap_or_else(|| base.to_string()) +} + +/// Is `name` (any case) the Kinsoku Shori set name `base` or a numbered copy of it, as +/// [`unique_kinsoku_name`] names one? +fn kinsoku_copy_of(base: &str, name: &str) -> bool { + KinsokuSet::same_name(base, name) + || name.rsplit_once(' ').is_some_and(|(_, n)| { + !n.is_empty() + && n.bytes().all(|b| b.is_ascii_digit()) + && n.parse::().is_ok_and(|i| i >= 2 && KinsokuSet::same_name(&numbered_kinsoku_name(base, i), name)) + }) +} + /// The document's own resource for pasted resource `name`, among the document's `names`: the /// one of that name when `same` holds for it (or, pasting back into the source document, at all), /// else a numbered copy of it (added by an earlier paste) that is the same. `None`: add it. @@ -600,6 +632,9 @@ struct Relink { styles: BTreeMap, /// Swatch (its name in the document) → the colour linked colours show at 100 %. colors: BTreeMap, + /// A custom Kinsoku set the pasted paragraphs and paragraph styles hold → the document's set + /// they take, or none (Hard) when the document has no room for it ([`Clipboard::import_kinsoku_sets`]). + kinsoku: HashMap>>, /// Leave graphic style links as they are ([`Clipboard::show_merged_colors`]). keep_styles: bool, } @@ -646,11 +681,19 @@ impl Relink { } } } - // A 3D effect's mapped graphics follow their symbols' names in the document. Each name is - // looked up once, so renames that chain (A to B, B to C) do not apply twice. + // A 3D effect's mapped graphics and Map Art maps follow their symbols' names in the + // document. Each name is looked up once, so renames that chain (A to B, B to C) do not + // apply twice. let items = a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut()); - for e in a.effects.iter_mut().chain(items).filter(|e| vectorcraft_render::effects::takes_graphics(&e.id)) { - let list = e.params.get_mut(vectorcraft_render::effects::GRAPHICS).and_then(Value::as_array_mut); + for e in a.effects.iter_mut().chain(items) { + let key = if vectorcraft_render::effects::takes_graphics(&e.id) { + vectorcraft_render::effects::GRAPHICS + } else if vectorcraft_render::effects::takes_map_art(&e.id) { + vectorcraft_render::effects::MAP_ART + } else { + continue; + }; + let list = e.params.get_mut(key).and_then(Value::as_array_mut); for g in list.into_iter().flatten() { if let Some(Value::String(s)) = g.get_mut("symbol") { self.name(Res::Symbol, s); @@ -667,6 +710,17 @@ impl Relink { } } fn attrs(&self, a: &mut Map) { + if let Some(to) = + a.get("kinsoku_set").and_then(|v| serde_json::from_value::(v.clone()).ok()).and_then(|set| self.kinsoku.get(&set)) + { + match to { + Some(set) => a.insert("kinsoku_set".into(), json!(set)), + None => { + a.insert("kinsoku".into(), json!(Kinsoku::Hard)); + a.insert("kinsoku_set".into(), Value::Null) + } + }; + } for k in STYLE_PAINTS { let Some(before) = style_paint(a, k) else { continue }; let mut p = before.clone(); @@ -707,6 +761,10 @@ impl Relink { if let Some(s) = &mut pa.style_name { self.name(Res::ParaStyle, s); } + // A graph draws its labels again from the paragraph attributes it keeps for them. + if let Some(to) = pa.kinsoku_set.as_deref().and_then(|set| self.kinsoku.get(set)) { + pa.kinsoku_set = to.clone(); + } } for r in [&mut l.values_rows, &mut l.categories_rows, &mut l.legend_rows, &mut l.axis_rows, &mut l.ring_rows].into_iter().flatten() { r.paint.fill.iter_mut().chain(r.paint.stroke.iter_mut()).for_each(|p| self.paint(p)); @@ -721,10 +779,21 @@ impl Relink { self.name(Res::CharStyle, s); } } + // Lines break anew when a paragraph's set takes other characters or Hard. + let mut relaid = false; for pa in t.para_styles_mut() { if let Some(s) = &mut pa.style_name { self.name(Res::ParaStyle, s); } + if let Some(set) = pa.kinsoku_set.as_deref() + && let Some(to) = self.kinsoku.get(set) + { + relaid |= to.as_deref().is_none_or(|to| kinsoku_chars(to) != kinsoku_chars(set)); + pa.kinsoku_set = to.clone(); + } + } + if relaid { + refresh_bounds(t); } } NodeKind::Image(im) => self.name(Res::Image, &mut im.key), @@ -738,6 +807,11 @@ impl Relink { } } +/// The characters and sequences of Kinsoku set `s`, without its name. +fn kinsoku_chars(s: &KinsokuSet) -> (&[char], &[char], &[char], &[String]) { + (&s.cannot_start, &s.cannot_end, &s.hanging, &s.inseparable) +} + /// Is `ours` (a document definition's art) the art of `theirs` (a pasted one's) once that is /// relinked by `r`? Graphic style links don't count: they are relinked last. fn same_art(r: &Relink, ours: &[Arc], theirs: &[Arc]) -> bool { @@ -1121,8 +1195,11 @@ impl Clipboard { /// uses, as [`import_text_styles`] places them, so that a style that paints with a pattern added /// under a free name ("Dots 2") is compared and added with that name. An error, with `d` /// unchanged, when a pasted SVG filter finds no free name ([`Self::filter_links`]). + /// `same_doc`: `d` is the document the objects were copied from. With colors converted for the + /// paste ([`Self::colors_converted`]), its color-bearing resources are compared as another + /// document's are, while its image blobs are still the document's own under their keys. pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Result { - self.import_used(d, &self.used(), choices, same_doc) + self.import_used_with_images(d, &self.used(), choices, same_doc && !self.colors_converted, same_doc) } /// Give the objects' colors linked to a global or spot swatch whose conflict with `d` @@ -1155,10 +1232,24 @@ impl Clipboard { /// other is matched on its own ([`loop_groups`]). Pasted back into its own document /// (`same_doc`), each definition of a loop is the document's of its name. fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool) -> Result { + self.import_used_with_images(d, used, choices, same_doc, same_doc) + } + + /// [`Self::import_used`], with the image blobs matched as those of the document they came + /// from when `same_doc_images`. + fn import_used_with_images( + &self, + d: &mut Document, + used: &Used, + choices: &SwatchChoices, + same_doc: bool, + same_doc_images: bool, + ) -> Result { let mut out = Imported::default(); out.relink.filters = self.filter_links(d, same_doc)?; - self.import_images(d, used, same_doc, &mut out); + self.import_images(d, used, same_doc_images, &mut out); self.import_swatches(d, used, choices, same_doc, &mut out); + self.import_kinsoku_sets(d, used, same_doc, &mut out); let mut defs: Vec> = vec![]; for (r, list) in [(Res::CharStyle, &self.char_styles), (Res::ParaStyle, &self.para_styles)] { defs.extend(list.iter().filter(|s| used.has(r, &s.name)).map(|s| Def::Style(r, s))); @@ -1305,10 +1396,86 @@ impl Clipboard { && out.relink.filters.is_empty() && out.relink.styles.is_empty() && out.relink.colors.is_empty() + && out.relink.kinsoku.is_empty() && used.styles.is_empty()); Ok(out) } + /// Add the custom Kinsoku sets that the pasted paragraphs and the used paragraph styles hold + /// to `d`'s sets, and record in [`Relink::kinsoku`] which set of `d` each one takes. A set + /// takes `d`'s set of its name (in any case) when that has the same characters, or, pasted + /// back into its own document, in any case; else a numbered copy of it ("Tight 2") with the + /// same characters. Any other set is added under a free name that fits [`KINSOKU_NAME_MAX`] + /// ([`unique_kinsoku_name`]), so editing `d`'s set of that name leaves the pasted paragraphs + /// alone. When `d` already holds [`KINSOKU_SETS_MAX`] sets, or the pasted set's own name is + /// longer than a name can be, the paragraphs and styles take Hard. + fn import_kinsoku_sets(&self, d: &mut Document, used: &Used, same_doc: bool, out: &mut Imported) { + let mut found: Vec = vec![]; + let mut seen: HashSet = HashSet::new(); + let mut note = |set: &KinsokuSet| { + if !seen.contains(set) { + seen.insert(set.clone()); + found.push(set.clone()); + } + }; + let mut nodes = |n: &Node| { + // Opacity-mask art included. + vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { + if let NodeKind::Text(t) = &m.kind { + t.para_styles().filter_map(|p| p.kinsoku_set.as_deref()).for_each(&mut note); + } + // The paragraph attributes a graph keeps for its labels. + if let Some(spec) = m.extras().graph.as_deref() { + let l = &spec.label_styles; + [&l.values_para, &l.categories_para, &l.legend_para] + .into_iter() + .flatten() + .filter_map(|p| p.kinsoku_set.as_deref()) + .for_each(&mut note); + } + }); + }; + self.nodes.iter().for_each(&mut nodes); + self.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)).for_each(|s| nodes(s.art.as_ref())); + self.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)).flat_map(|p| p.art.iter()).for_each(|a| nodes(a.as_ref())); + self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name)).flat_map(Brush::art).for_each(&mut nodes); + let styles = self.para_styles.iter().filter(|s| used.has(Res::ParaStyle, &s.name)); + for set in styles.filter_map(|s| s.attrs.get("kinsoku_set")).filter_map(|v| serde_json::from_value::(v.clone()).ok()) { + note(&set); + } + for set in found { + let lower = set.name.to_lowercase(); + let mut copies: Vec<&KinsokuSet> = + d.kinsoku_sets.iter().filter(|x| copy_of(&lower, &x.name.to_lowercase()) || kinsoku_copy_of(&set.name, &x.name)).collect(); + // The set of its name first. + copies.sort_by_key(|x| !KinsokuSet::same_name(&x.name, &set.name)); + let own = copies.first().copied().filter(|x| same_doc && KinsokuSet::same_name(&x.name, &set.name)); + let to = match own.or_else(|| copies.iter().copied().find(|x| kinsoku_chars(x) == kinsoku_chars(&set))) { + Some(x) => { + if !KinsokuSet::same_name(&x.name, &set.name) { + out.renamed.push(json!({"kind": "kinsokuSet", "from": set.name, "to": x.name})); + } + Some(Arc::new(x.clone())) + } + None => { + let name = unique_kinsoku_name(&set.name, &d.kinsoku_sets); + (d.kinsoku_sets.len() < KINSOKU_SETS_MAX && name.chars().count() <= KINSOKU_NAME_MAX).then(|| { + let added = KinsokuSet { name: name.clone(), ..set.clone() }; + d.kinsoku_sets.push(added.clone()); + out.added += 1; + if name != set.name { + out.renamed.push(json!({"kind": "kinsokuSet", "from": set.name, "to": name})); + } + Arc::new(added) + }) + } + }; + if to.as_deref() != Some(&set) { + out.relink.kinsoku.insert(set, to); + } + } + } + /// How the pasted SVG filter effects relink ([`Relink::filters`]). Each names the document's /// filter of its name; one that draws another definition than that filter takes the document's /// filter when pasted back into the document it came from, and elsewhere keeps its own under a diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 18374f8302..0ac4f8c3b0 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -37,7 +37,7 @@ pub fn specs() -> Vec { "Color Settings…", ["Edit"], Some("Cmd+Shift+K"), - "{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\"} set the working spaces and the color management policies → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, profiles: [{name, kind, builtin}]}. A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults", + "{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool, rgbPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\", cmykPolicy?: \"off\"|\"preserveEmbedded\"|\"convert\"|\"preserveNumbers\", askMismatchOpen?: bool, askMismatchPaste?: bool, askMissingOpen?: bool (all false by default)} set the working spaces, the color management policies and the Ask boxes → {rgb, cmyk, intent, bpc, rgbPolicy, cmykPolicy, askMismatchOpen, askMismatchPaste, askMissingOpen, profiles: [{name, kind, builtin}]}. With askMismatchOpen or askMissingOpen on, the desktop app's File › Open asks what to do when the profile of a document's color mode is not the working space, or it has none (document.open takes the answer as profileChoice; it never asks); with askMismatchPaste on, Paste asks whether colors copied from a document with another profile keep their numbers or convert (edit.paste takes it as profileMismatch; see clipboard.profileMismatch). A policy decides what opening a document (document.open, file.newFromTemplate, file.revert) does with an RGB or CMYK profile it is tagged with that is not the working space: preserveEmbedded (default) keeps it; off and preserveNumbers take it off and keep the color numbers; convert converts the colors of that model into the working space with the intent and bpc and takes it off. The open reply's warnings name each profile taken off or converted, and a document a policy changed opens with unsaved changes. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults", always, color_settings ), @@ -183,6 +183,9 @@ fn settings_json(st: &ColorSettings) -> Value { "bpc": st.bpc, "rgbPolicy": st.rgb_policy.id(), "cmykPolicy": st.cmyk_policy.id(), + "askMismatchOpen": st.ask_mismatch_open, + "askMismatchPaste": st.ask_mismatch_paste, + "askMissingOpen": st.ask_missing_open, "profiles": cms::profiles().iter().map(|p| json!({"name": p.name, "kind": p.kind, "builtin": p.builtin})).collect::>(), }) } @@ -225,6 +228,9 @@ fn color_settings(s: &mut Session, p: &Value) -> Result { if let Some(v) = policy_param(p, "cmykPolicy", &Policy::CMYK, C)? { st.cmyk_policy = v; } + st.ask_mismatch_open = switch_or(p, "askMismatchOpen", st.ask_mismatch_open, C)?; + st.ask_mismatch_paste = switch_or(p, "askMismatchPaste", st.ask_mismatch_paste, C)?; + st.ask_missing_open = switch_or(p, "askMissingOpen", st.ask_missing_open, C)?; if st != before { cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?; // Saved for the next start when the app attached a settings file (#6335). @@ -659,39 +665,259 @@ fn convert_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Co /// by Off and Preserve Numbers and kept by Convert to Working Space, which has nothing to convert /// from. → a note for each profile, and whether `d` changed. pub(crate) fn apply_open_policies(d: &mut vectorcraft_doc::Document) -> (Vec, bool) { + // Without a choice nothing can fail. + apply_open_policies_choosing(d, None).unwrap_or_default() +} + +/// What opening a document can ask about its profile (Edit › Color Settings' Ask When Opening +/// boxes): the profile of its color mode differs from the working space, or it has none. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ProfileIssue { + /// Profile Mismatches: tagged with a profile other than the working space. + Mismatch, + /// Missing Profiles: not tagged with a profile. + Missing, +} + +impl ProfileIssue { + pub fn id(self) -> &'static str { + match self { + ProfileIssue::Mismatch => "mismatch", + ProfileIssue::Missing => "missing", + } + } +} + +/// The answer to a [`ProfileQuestion`] (`document.open`'s `profileChoice`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ProfileChoice { + /// Mismatch: keep the profile (as Preserve Embedded Profiles). + UseEmbedded, + /// Mismatch: convert the colors of that model into the working space and take the profile off + /// (as Convert to Working Space). + Convert, + /// Mismatch: take the profile off and keep the color numbers (as Off). + Discard, + /// Missing: leave the document untagged (it follows the working space). + Leave, + /// Missing: tag the document with the working space of its color mode. + AssignWorking, + /// Missing: tag the document with this profile. + Assign(String), +} + +impl ProfileChoice { + /// The ids `profileChoice` takes. + pub const IDS: [&'static str; 6] = ["useEmbedded", "convert", "discard", "leave", "assignWorking", "assign"]; + + pub fn id(&self) -> &'static str { + match self { + ProfileChoice::UseEmbedded => "useEmbedded", + ProfileChoice::Convert => "convert", + ProfileChoice::Discard => "discard", + ProfileChoice::Leave => "leave", + ProfileChoice::AssignWorking => "assignWorking", + ProfileChoice::Assign(_) => "assign", + } + } + + /// The question kind this choice answers. + pub fn issue(&self) -> ProfileIssue { + match self { + ProfileChoice::UseEmbedded | ProfileChoice::Convert | ProfileChoice::Discard => ProfileIssue::Mismatch, + _ => ProfileIssue::Missing, + } + } + + /// The choice `id` (`profile`, which only `assign` takes, for `assign`), or an error naming + /// `cmd`. + pub fn parse(id: &str, profile: Option<&str>, cmd: &str) -> Result { + let key = "profileChoice"; + let choice = match id { + "useEmbedded" => ProfileChoice::UseEmbedded, + "convert" => ProfileChoice::Convert, + "discard" => ProfileChoice::Discard, + "leave" => ProfileChoice::Leave, + "assignWorking" => ProfileChoice::AssignWorking, + "assign" => match profile.filter(|p| !p.is_empty()) { + Some(p) => ProfileChoice::Assign(cms::canonical_name(p).to_string()), + None => { + let path = "assignProfile"; + return Err(bad(cmd, format!("missing `{path}`"))); + } + }, + _ => return Err(bad(cmd, format!("`{key}` must be one of {}", Self::IDS.join(", ")))), + }; + // `assignProfile` goes with `assign` only. + if profile.is_some() && !matches!(choice, ProfileChoice::Assign(_)) { + let path = "assignProfile"; + return Err(bad(cmd, format!("`{path}` goes with `{key}`: \"assign\" only"))); + } + Ok(choice) + } + + /// `document.open`'s `profileChoice` and `assignProfile` in `p` (`None` when left out). + pub(crate) fn param(p: &Value, cmd: &str) -> Result> { + let profile = text_param(p, "assignProfile", cmd)?; + match text_param(p, "profileChoice", cmd)? { + Some(id) => Self::parse(id, profile, cmd).map(Some), + None if profile.is_some() => { + let path = "profileChoice"; + Err(bad(cmd, format!("missing `{path}`"))) + } + None => Ok(None), + } + } +} + +/// What opening document `d` could ask about the profile of its color mode, with the working +/// settings `st`: none when it is tagged with the working space. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ProfileQuestion { + pub issue: ProfileIssue, + /// The model of the document's color mode. + pub model: ColorMode, + /// The profile the document is tagged with (none when it is missing). + pub profile: Option, + /// The working space of that model. + pub working: String, + /// What the policy of that model does, the choice the prompt starts on. + pub default: ProfileChoice, +} + +impl ProfileQuestion { + /// The question for document `d` under the working settings `st` (whether or not they ask it). + pub fn of(d: &vectorcraft_doc::Document, st: &ColorSettings) -> Option { + let (rgb, cmyk) = doc_profiles(d); + let (tag, working, policy) = match d.color_mode { + ColorMode::Rgb => (rgb, cms::canonical_name(&st.rgb).to_string(), st.rgb_policy), + ColorMode::Cmyk => (cmyk, cms::canonical_name(&st.cmyk).to_string(), st.cmyk_policy), + }; + let (issue, default) = match &tag { + Some(t) if *t == working => return None, + Some(_) => ( + ProfileIssue::Mismatch, + match policy { + Policy::PreserveEmbedded => ProfileChoice::UseEmbedded, + Policy::Convert => ProfileChoice::Convert, + Policy::Off | Policy::PreserveNumbers => ProfileChoice::Discard, + }, + ), + // VectorCraft's own rule: Convert to Working Space starts on assigning the working + // space, the other policies on leaving the document as it is. + None => (ProfileIssue::Missing, if policy == Policy::Convert { ProfileChoice::AssignWorking } else { ProfileChoice::Leave }), + }; + Some(Self { issue, model: d.color_mode, profile: tag, working, default }) + } + + /// Do the settings `st` ask it (the Ask When Opening box of its kind is on)? + pub fn asked(&self, st: &ColorSettings) -> bool { + match self.issue { + ProfileIssue::Mismatch => st.ask_mismatch_open, + ProfileIssue::Missing => st.ask_missing_open, + } + } + + /// The model's name as the UI shows it ("RGB", "CMYK"). + pub fn model_label(&self) -> &'static str { + match self.model { + ColorMode::Rgb => "RGB", + ColorMode::Cmyk => "CMYK", + } + } + + pub fn to_json(&self) -> Value { + json!({ + "issue": self.issue.id(), + "model": self.model_label().to_ascii_lowercase(), + "profile": self.profile, + "working": self.working, + "default": self.default.id(), + }) + } +} + +/// [`apply_open_policies`] with the answer `choice` to the document's [`ProfileQuestion`]: a +/// mismatch choice takes the place of the policy of the document's color mode, and a missing +/// choice tags the document after the policies ran. A choice for the other kind of question, or +/// for a document with none, is not used. → as [`apply_open_policies`]; an error when the profile +/// to assign is not a profile of that model. +pub(crate) fn apply_open_policies_choosing(d: &mut vectorcraft_doc::Document, choice: Option<&ProfileChoice>) -> Result<(Vec, bool)> { let working = cms::working_settings(); + let question = ProfileQuestion::of(d, &working); + let choice = choice.filter(|c| question.as_ref().is_some_and(|q| q.issue == c.issue())); + // A mismatch answer stands in for the policy of the document's color mode. + let chosen = |model: ColorMode, policy: Policy| -> (Policy, bool) { + match choice { + Some(c) if d.color_mode == model => match c { + ProfileChoice::UseEmbedded => (Policy::PreserveEmbedded, true), + ProfileChoice::Convert => (Policy::Convert, true), + ProfileChoice::Discard => (Policy::Off, true), + _ => (policy, false), + }, + _ => (policy, false), + } + }; + let (rgb_policy, rgb_chosen) = chosen(ColorMode::Rgb, working.rgb_policy); + let (cmyk_policy, cmyk_chosen) = chosen(ColorMode::Cmyk, working.cmyk_policy); + // The profile a missing answer assigns, checked before anything changes. + let assign = match (choice, &question) { + (Some(ProfileChoice::AssignWorking), Some(q)) => Some(q.working.clone()), + (Some(ProfileChoice::Assign(name)), Some(q)) => { + let kind = if q.model == ColorMode::Rgb { cms::ProfileKind::Rgb } else { cms::ProfileKind::Cmyk }; + let (key, n) = (q.model_label().to_ascii_lowercase(), name); + let info = cms::profile(name).filter(|p| p.kind == kind).ok_or_else(|| bad("document.open", format!("unknown {key} profile `{n}`")))?; + Some(info.name) + } + _ => None, + }; let (rgb, cmyk) = doc_profiles(d); let mut notes = Vec::new(); // What each model's policy does with its profile: `None` keeps it; `Some` takes it off, after - // converting the colors from the profile it holds. - let mut decide = |label: &str, tag: Option, working: &str, policy: Policy, kind: cms::ProfileKind| -> Option> { - let tag = tag.filter(|t| t != working)?; - let available = cms::profile(&tag).is_some_and(|p| p.kind == kind); - match policy { - Policy::PreserveEmbedded => None, - Policy::Off | Policy::PreserveNumbers => { - notes.push(format!( - "the {label} profile “{tag}” the file is tagged with was not used: Color Settings' {label} policy is {}", - policy.label() - )); - Some(None) - } - Policy::Convert if available => { - notes.push(format!( - "the {label} colors were converted from the profile “{tag}” the file is tagged with into the working space “{working}”" - )); - Some(Some(tag)) - } - Policy::Convert => { - notes.push(format!("the {label} profile “{tag}” the file is tagged with is not available, so its colors were not converted")); - None + // converting the colors from the profile it holds. `by_choice`: the prompt's answer decided. + let mut decide = + |label: &str, tag: Option, working: &str, policy: Policy, by_choice: bool, kind: cms::ProfileKind| -> Option> { + let tag = tag.filter(|t| t != working)?; + let available = cms::profile(&tag).is_some_and(|p| p.kind == kind); + match policy { + Policy::PreserveEmbedded => None, + Policy::Off | Policy::PreserveNumbers if by_choice => { + notes.push(format!("the {label} profile “{tag}” the file is tagged with was discarded, as chosen when it was opened")); + Some(None) + } + Policy::Off | Policy::PreserveNumbers => { + notes.push(format!( + "the {label} profile “{tag}” the file is tagged with was not used: Color Settings' {label} policy is {}", + policy.label() + )); + Some(None) + } + Policy::Convert if available => { + notes.push(format!( + "the {label} colors were converted from the profile “{tag}” the file is tagged with into the working space “{working}”" + )); + Some(Some(tag)) + } + Policy::Convert => { + notes.push(format!("the {label} profile “{tag}” the file is tagged with is not available, so its colors were not converted")); + None + } } + }; + let rgb_do = decide("RGB", rgb, &working.rgb, rgb_policy, rgb_chosen, cms::ProfileKind::Rgb); + let cmyk_do = decide("CMYK", cmyk, &working.cmyk, cmyk_policy, cmyk_chosen, cms::ProfileKind::Cmyk); + let mut changed = false; + if let (Some(name), Some(q)) = (assign, &question) { + let label = q.model_label(); + notes.push(format!("the document was assigned the {label} profile “{name}”, as chosen when it was opened")); + match q.model { + ColorMode::Rgb => d.color_profiles.rgb = Some(name), + ColorMode::Cmyk => d.color_profiles.cmyk = Some(name), } - }; - let rgb_do = decide("RGB", rgb, &working.rgb, working.rgb_policy, cms::ProfileKind::Rgb); - let cmyk_do = decide("CMYK", cmyk, &working.cmyk, working.cmyk_policy, cms::ProfileKind::Cmyk); + changed = true; + } if rgb_do.is_none() && cmyk_do.is_none() { - return (notes, false); + return Ok((notes, changed)); } let (from_rgb, from_cmyk) = (rgb_do.clone().flatten(), cmyk_do.clone().flatten()); if from_rgb.is_some() || from_cmyk.is_some() { @@ -713,7 +939,214 @@ pub(crate) fn apply_open_policies(d: &mut vectorcraft_doc::Document) -> (Vec Color) { + convert_colors(d, conv); + convert_style_colors(d, conv); +} + +/// The RGB and CMYK profiles the colors of `d` show through, by name: those it is assigned, else +/// the working spaces. An assigned profile that is not available (removed since) is the working +/// space, as the document draws through it ([`cms::for_document`]). +pub(crate) fn effective_profiles(d: &vectorcraft_doc::Document) -> [String; 2] { + let working = cms::working_settings(); + let (rgb, cmyk) = doc_profiles(d); + let available = |name: Option, kind: cms::ProfileKind| name.filter(|n| cms::profile(n).is_some_and(|p| p.kind == kind)); + [ + available(rgb, cms::ProfileKind::Rgb).unwrap_or_else(|| cms::canonical_name(&working.rgb).to_string()), + available(cmyk, cms::ProfileKind::Cmyk).unwrap_or_else(|| cms::canonical_name(&working.cmyk).to_string()), + ] +} + +/// What Paste does with the colors of a model when the document they were copied from showed them +/// through another profile than the document they go into (`profileMismatch`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PasteProfile { + /// The colors keep their numbers. + PreserveNumbers, + /// The colors convert from the source profile into the destination's, which keeps their + /// appearance. + Convert, +} + +impl PasteProfile { + pub fn id(self) -> &'static str { + match self { + PasteProfile::PreserveNumbers => "preserveNumbers", + PasteProfile::Convert => "convert", + } + } + + /// What a model's policy does to pasted colors (VectorCraft's own mapping): Convert to Working + /// Space converts them, the other policies keep their numbers. + pub fn of(policy: Policy) -> Self { + if policy == Policy::Convert { PasteProfile::Convert } else { PasteProfile::PreserveNumbers } + } + + /// The `profileMismatch` param of paste command `cmd` (`None` when left out): one choice for + /// both models, or `{rgb?, cmyk?}` with a choice for each (a model left out follows its policy). + pub(crate) fn param(p: &Value, cmd: &str) -> Result> { + let key = "profileMismatch"; + let refuse = || bad(cmd, format!("`{key}` must be one of {}", "preserveNumbers, convert, {rgb?, cmyk?} of those")); + let one = |v: &Value| match v.as_str() { + Some("preserveNumbers") => Ok(PasteProfile::PreserveNumbers), + Some("convert") => Ok(PasteProfile::Convert), + _ => Err(refuse()), + }; + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Object(o)) => { + if o.keys().any(|k| k != "rgb" && k != "cmyk") { + return Err(refuse()); + } + let model = |m: &str| o.get(m).map(&one).transpose(); + Ok(Some(PasteChoice { rgb: model("rgb")?, cmyk: model("cmyk")? })) + } + Some(v) => { + let c = one(v)?; + Ok(Some(PasteChoice { rgb: Some(c), cmyk: Some(c) })) + } + } + } +} + +/// What Paste does with the mismatched colors of each model (`profileMismatch`); a model without a +/// choice follows its policy ([`PasteProfile::of`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PasteChoice { + pub rgb: Option, + pub cmyk: Option, +} + +impl PasteChoice { + /// The choice for the colors of `model`, if any. + pub fn of(&self, model: ColorMode) -> Option { + match model { + ColorMode::Rgb => self.rgb, + ColorMode::Cmyk => self.cmyk, + } + } +} + +/// A model whose colors a paste brings from another profile than the destination's. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PasteMismatch { + pub model: ColorMode, + /// The profile the colors showed through where they were copied. + pub from: String, + /// The profile they show through in the document they go into. + pub to: String, + /// What the model's policy does with them; Preserve Numbers when they can't convert. + pub default: PasteProfile, + /// Both profiles are available, so the colors can convert; otherwise they keep their numbers + /// whatever the choice. + pub convertible: bool, +} + +impl PasteMismatch { + pub fn to_json(&self) -> Value { + let model = if self.model == ColorMode::Rgb { "rgb" } else { "cmyk" }; + json!({ "model": model, "clipboard": self.from, "document": self.to, "default": self.default.id(), "convertible": self.convertible }) + } +} + +/// The models whose colors pasting `clip` into `d` brings from another profile: RGB, CMYK or both, +/// each only when the copied objects or the resources they carry hold a color of that model. The +/// background colors of copied artboards count only with `boards` (Paste on All Artboards doesn't +/// paste the artboards). +pub(crate) fn paste_mismatches(clip: &super::clipboard::Clipboard, d: &vectorcraft_doc::Document, boards: bool) -> Vec { + let Some([from_rgb, from_cmyk]) = &clip.source_profiles else { return vec![] }; + let [to_rgb, to_cmyk] = effective_profiles(d); + let working = cms::working_settings(); + let mut out: Vec = + [(ColorMode::Rgb, from_rgb, to_rgb, working.rgb_policy), (ColorMode::Cmyk, from_cmyk, to_cmyk, working.cmyk_policy)] + .into_iter() + .filter(|(_, from, to, _)| cms::canonical_name(from) != cms::canonical_name(to)) + .map(|(model, from, to, policy)| { + let kind = if model == ColorMode::Rgb { cms::ProfileKind::Rgb } else { cms::ProfileKind::Cmyk }; + // Both profiles must be here to convert between them. + let here = |name: &str| cms::profile(name).is_some_and(|p| p.kind == kind); + let convertible = here(from) && here(&to); + let default = if convertible { PasteProfile::of(policy) } else { PasteProfile::PreserveNumbers }; + PasteMismatch { model, from: from.clone(), to, default, convertible } + }) + .collect(); + if out.is_empty() { + return out; + } + // Without the artboards when their backgrounds don't paste. + let without_boards; + let clip = if !boards && !clip.artboards.is_empty() { + without_boards = super::clipboard::Clipboard { artboards: vec![], ..clip.clone() }; + &without_boards + } else { + clip + }; + // Which models the pasted colors use. + let seen = std::cell::Cell::new((false, false)); + let _ = clip.with_colors(&|c: &Color| { + let (rgb, cmyk) = seen.get(); + seen.set((rgb || matches!(c, Color::Rgb { .. }), cmyk || matches!(c, Color::Cmyk { .. }))); + *c + }); + let (rgb, cmyk) = seen.get(); + out.retain(|m| if m.model == ColorMode::Rgb { rgb } else { cmyk }); + out +} + +/// The clipboard `clip` as pasting it into `d` brings it: for each mismatched model +/// ([`paste_mismatches`]), its colors keep their numbers or convert from the source profile into +/// the destination's with the working intent, as `choice` says for that model (default: the +/// model's policy, [`PasteProfile::of`]). A source or destination profile that is not available +/// keeps the numbers. `boards`: as [`paste_mismatches`]. +/// → the converted clipboard (`None` when nothing converts; its resources paste as another +/// document's) and a line for each mismatched model (`{model, clipboard, document, choice}`). +pub(crate) fn paste_profiles( + clip: &super::clipboard::Clipboard, + d: &vectorcraft_doc::Document, + choice: Option, + boards: bool, +) -> (Option, Vec) { + let mismatches = paste_mismatches(clip, d, boards); + let mut report = Vec::new(); + let (mut rgb_on, mut cmyk_on) = (false, false); + for m in &mismatches { + let picked = if m.convertible { choice.and_then(|c| c.of(m.model)).unwrap_or(m.default) } else { PasteProfile::PreserveNumbers }; + if picked == PasteProfile::Convert { + match m.model { + ColorMode::Rgb => rgb_on = true, + ColorMode::Cmyk => cmyk_on = true, + } + } + let mut line = m.to_json(); + if let Some(o) = line.as_object_mut() { + o.remove("default"); + o.remove("convertible"); + o.insert("choice".into(), json!(picked.id())); + } + report.push(line); + } + if !rgb_on && !cmyk_on { + return (None, report); + } + let Some([from_rgb, from_cmyk]) = &clip.source_profiles else { return (None, report) }; + let source = cms::for_document(Some(from_rgb), Some(from_cmyk)); + let dest = doc_cms(d); + let intent = cms::working_settings().intent; + let conv = |c: &Color| match c { + Color::Rgb { .. } if rgb_on => source.convert_into(&dest, c, intent), + Color::Cmyk { .. } if cmyk_on => source.convert_into(&dest, c, intent), + _ => *c, + }; + let mut converted = clip.with_colors(&conv); + // Converted colors are not the source document's own: its resources of the same names are + // compared with them, as another document's are. + converted.colors_converted = true; + (Some(converted), report) } /// The colors of `d` outside its art that [`convert_colors`] leaves, converted with `conv`: each @@ -726,6 +1159,11 @@ fn convert_setting_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Colo for c in &mut d.setup.grid_colors { *c = conv(c); } + convert_style_colors(d, conv); +} + +/// The fill and stroke colors of `d`'s character and paragraph styles, converted with `conv`. +fn convert_style_colors(d: &mut vectorcraft_doc::Document, conv: &dyn Fn(&Color) -> Color) { // A tint of a global swatch is the converted swatch's color at its tint, which // [`convert_colors`] already gave it. let bases = global_bases(d); diff --git a/crates/engine/src/cmd/compoundshape.rs b/crates/engine/src/cmd/compoundshape.rs index bc93b399a5..b1c610d8bd 100644 --- a/crates/engine/src/cmd/compoundshape.rs +++ b/crates/engine/src/cmd/compoundshape.rs @@ -8,6 +8,8 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind, ShapeMode}; +use vectorcraft_geom::{FillRule, PathData, SubPath}; +use vectorcraft_pathops as po; use vectorcraft_render::effects; use super::edit::{roots_of, selected_roots}; @@ -16,6 +18,10 @@ use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_multi}; const MODE_NAMES: [&str; 4] = ["add", "subtract", "intersect", "exclude"]; +/// Make Compound Shape's warning, which the status bar shows, when a member holds a line or another +/// open path that encloses no area once closed, and so contributes no area to the shape. +pub const OPEN_PATHS_ADD_NO_AREA: &str = "a line or other open path that encloses no area contributes no area to the compound shape; to include it, apply Object › Path › Outline Stroke to it first"; + pub fn specs() -> Vec { vec![ cmd!( @@ -23,7 +29,7 @@ pub fn specs() -> Vec { "Make Compound Shape", ["Window", "Pathfinder"], None, - "{ids?: [id…] (selected first; default: the selection), mode?: \"add\"|\"subtract\"|\"intersect\"|\"exclude\" (default add; Alt-clicking a Shape Mode button gives its mode)} the two or more selected objects (paths, compound paths, groups, compound shapes, type, blends, envelopes) become the members of one compound shape, each with the shape mode, in their stacking order where the frontmost was: it draws as the area they make from the backmost up (open paths closed; a blend as its steps, an envelope as its distorted art, an object with a warp or other geometry effect as it draws), painted with the appearance and transparency of the topmost member in Add, Intersect or Exclude mode (with every member in Subtract, the backmost), and the members stay editable (Direct Selection, Layers panel, isolation mode) → {id}", + "{ids?: [id…] (selected first; default: the selection), mode?: \"add\"|\"subtract\"|\"intersect\"|\"exclude\" (default add; Alt-clicking a Shape Mode button gives its mode)} the two or more selected objects (paths, compound paths, groups, compound shapes, type, blends, envelopes) become the members of one compound shape, each with the shape mode, in their stacking order where the frontmost was: it draws as the area they make from the backmost up (open paths closed; a blend as its steps, an envelope as its distorted art, an object with a warp or other geometry effect as it draws), painted with the appearance and transparency of the topmost member in Add, Intersect or Exclude mode (with every member in Subtract, the backmost), and the members stay editable (Direct Selection, Layers panel, isolation mode) → {id, warning?: when a member is or holds a line or another open path that encloses no area once closed, and so contributes no area}", has_multi, make ), @@ -157,6 +163,7 @@ fn make(s: &mut Session, p: &Value) -> Result { // all have `mode`, the topmost, or the backmost when they all subtract. let order: Vec<&Node> = if mode == ShapeMode::Subtract { members } else { members.into_iter().rev().collect() }; let hook = |c: &Node| effects::outline_object(Some(d), c); + let no_area = order.iter().any(|n| adds_no_area(d, n, &hook)); let style = order.into_iter().find_map(|n| top_style(d, n, &hook)); let id = s.edit("Make Compound Shape", |d, sel| { let gid = d.alloc_id(); @@ -179,7 +186,44 @@ fn make(s: &mut Session, p: &Value) -> Result { sel.set([id]); Ok(id) })?; - Ok(json!({ "id": id.0 })) + let mut out = json!({ "id": id.0 }); + if no_area { + out["warning"] = json!(OPEN_PATHS_ADD_NO_AREA); + } + Ok(out) +} + +/// Member `n` holds an open path that adds no area to a compound shape: one of the paths it takes +/// part as ([`effects::member_leaves`]), inside a group or a compound path too, has an open subpath +/// that encloses no area once closed (a straight line, or an evenodd contour traced twice), or it +/// has an open subpath and its subpaths, all closed, enclose no area together (open evenodd +/// subpaths that cancel one another or a closed subpath). The area is the one the path's fill rule +/// gives, which also keeps a self-crossing path whose signed area is zero (a bow tie) from the +/// warning, as Divide measures it. An area that can't be measured gives no warning. +fn adds_no_area(d: &Document, n: &Node, hook: effects::OutlineHook) -> bool { + effects::member_leaves(Some(d), n, Some(hook)).iter().any(|leaf| { + let (paths, rule): (Vec<&PathData>, FillRule) = match &leaf.kind { + NodeKind::Compound { children, rule } => (children.iter().filter_map(|c| c.path_data()).collect(), *rule), + NodeKind::Path { path, rule, .. } => (vec![path], *rule), + _ => return false, + }; + let subpaths: Vec<&SubPath> = paths.iter().flat_map(|p| &p.subpaths).collect(); + if subpaths.iter().all(|sp| sp.closed) { + return false; + } + let closed = |sp: &SubPath| { + let mut sp = sp.clone(); + sp.closed = true; + sp + }; + // An area that can't be measured counts as an area, so a failed measurement gives no warning. + let no_area = |p: PathData| po::try_area(&p, rule).is_ok_and(|a| a <= 0.0); + subpaths.iter().filter(|sp| !sp.closed).any(|sp| { + // The signed-area test alone only holds for nonzero: evenodd can fill nothing where + // the signed area is not zero (a contour traced twice). + !(rule == FillRule::NonZero && po::encloses_area(sp)) && no_area(PathData::single(closed(sp))) + }) || (subpaths.len() > 1 && no_area(PathData::new(subpaths.iter().map(|sp| closed(sp)).collect()))) + }) } /// The paint and transparency of the frontmost shape `n` adds to a compound shape's area, from the diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 803057885a..89752c1b33 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -1,14 +1,16 @@ //! Creating art: shapes, paths, text. use serde_json::{Value, json}; -use vectorcraft_doc::{Appearance, CharStyle, LiveShape, Node, NodeKind, TextObject}; +use vectorcraft_doc::{Appearance, CharStyle, LiveShape, MAX_COORD, Node, NodeKind, TextObject}; +use vectorcraft_geom::curvature::{self, NoCircle}; use vectorcraft_geom::{Affine, Anchor, AnchorKind, FillRule, PathData, Point, Rect, SubPath, shapes}; use super::newart::NewArt; use super::{ CommandSpec, NodeId, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, f64_or, f64_req, finite_numbers, has_doc, - number_or, str_param, switch_or, + index_opt, number_or, object_param, str_param, switch_or, }; +use crate::EngineError; pub fn specs() -> Vec { vec![ @@ -55,7 +57,16 @@ pub fn specs() -> Vec { None, "{cx, cy, diameter=100, opacity=50 (%), brightness=30 (%), growth=20 (%), fuzziness=50 (%), rays=15, longest=300 (%), rayFuzziness=100 (%), rotation=0 (deg, turns the rays clockwise), x2?, y2? (ring end; else pathLength at direction), pathLength=300, rings=10, largest=50 (%), direction=45 (deg counter-clockwise from 3 o'clock: where the rings run from the centre), seed?, ringSeed? (whole number below 2^53: deterministically places every ring along the path, including the first for small seed values, keeping their count and sizes)} → {id}", has_doc, - flare + super::flare::flare + ), + cmd!( + "shape.editFlare", + "Edit Flare", + [], + None, + "{ids?|id?: flares (default: the selected flares), cx?, cy? (the center, where it is drawn now), x2?, y2? (the rings' end point, where it is drawn now; else pathLength at direction from the center, both where it is drawn now, when either is given; else where it was), diameter?, opacity?, brightness?, growth?, fuzziness?, rays?, longest?, rayFuzziness?, rotation? (deg, turns the rays clockwise), pathLength?, rings?, largest?, direction? (as shape.flare: what is left out stays as it was)} draws each flare again in its place, moved, scaled, rotated, reflected or sheared as it has been since it was drawn, as one undo step (none when nothing changes); a flare whose parts were edited, or that is locked or hidden, is not one → {ids}", + has_doc, + super::flare::edit_flare ), cmd!( "shape.circleThroughPoints", @@ -66,6 +77,15 @@ pub fn specs() -> Vec { has_doc, circle_through_points ), + cmd!( + "shape.curvatureCircle", + "Curvature Circle", + [], + None, + "{id, subpath?=0, segment, t: 0..1, convex?=false} → {id, cx, cy, radius, nominal}: a circle with the current paint that touches path `id` at `t` on the segment and bends as the path bends there (its circle of curvature), on the side the path bends toward, or on the other side with convex; a segment that is the usual cubic of a circular arc of 90° or less gives a circle of that arc's own radius (nominal: true), on the concave side the arc's own circle; not pixel-aligned even while Align New Objects to Pixel Grid is on; a straight stretch, a cusp, a corner anchor (t 0 or 1 where two segments meet at an angle of more than half a degree and the anchor is not marked smooth with both handles pulled out, or where they turn by 90° or more; segments of no length between them are passed over, and an anchor reached past one is treated as not marked smooth), a guide, or a circle reaching past the canvas is an error, and nothing is drawn", + has_doc, + curvature_circle + ), cmd!("shape.line", "Line Segment", [], None, "{x1, y1, x2, y2, fill?: bool (Fill Line: the current fill, else none)} → {id}", has_doc, line), cmd!( "shape.spiral", @@ -476,6 +496,51 @@ fn selected_anchor_points(s: &Session) -> Result>> { Ok(matches!(points.len(), 2 | 3).then_some(points)) } +/// A live ellipse that touches a path at a point with the path's curvature there +/// ([`curvature::curvature_circle_on`]). One undo step, named as an Ellipse tool drag is. +fn curvature_circle(s: &mut Session, p: &Value) -> Result { + const C: &str = "shape.curvatureCircle"; + let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; + let si = index_opt(p, "subpath", C)?.unwrap_or(0); + let seg = index_opt(p, "segment", C)?.ok_or_else(|| bad(C, "missing segment"))?; + let t = f64_req(p, "t", C)?; + if !(0.0..=1.0).contains(&t) { + return Err(bad(C, "`t` must be from 0 to 1")); + } + let convex = switch_or(p, "convex", false, C)?; + let found = { + let st = s.doc()?; + let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?; + if node.is_guide() { + return Err(bad(C, "a guide has no curvature circle")); + } + let path = node.path_data().ok_or_else(|| bad(C, format!("object {id} is not a path")))?; + let sp = path.subpaths.get(si).ok_or_else(|| bad(C, "no such subpath"))?; + if seg >= sp.segment_count() { + return Err(bad(C, "no such segment")); + } + curvature::curvature_circle_on(sp, seg, t, convex) + }; + let circle = found.map_err(|e| match e { + NoCircle::Straight => bad(C, "the path is straight there, so no circle matches its curvature"), + NoCircle::Cusp => bad(C, "the path has a cusp there, so it has no single curvature"), + NoCircle::Corner => bad(C, "the path has a corner there, so it has no single curvature"), + })?; + let (center, radius) = (circle.center, circle.radius); + let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius); + if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.abs() <= MAX_COORD) { + return Err(bad(C, "the circle that matches the path there would reach past the canvas")); + } + let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; + // Not pixel-aligned: the circle stays on the path. + let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?; + out["cx"] = json!(center.x); + out["cy"] = json!(center.y); + out["radius"] = json!(radius); + out["nominal"] = json!(circle.nominal); + Ok(out) +} + /// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or /// null. A fraction, a negative, a non-finite or a non-number is an error rather than the default. fn count_or(p: &Value, key: &str, default: u64, cmd: &str) -> Result { @@ -515,149 +580,6 @@ fn star(s: &mut Session, p: &Value) -> Result { add_art_turned(s, "Star", path_kind(path, None), constrained_turn(s, rot)) } -/// Flare tool: a lens flare built from radial-gradient paths in Screen mode — a bright centre, a halo -/// ring, rays of varying length and rings along the path to the end point. -fn flare(s: &mut Session, p: &Value) -> Result { - use vectorcraft_color::{BlendMode, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint}; - let c = Point::new(f64_req(p, "cx", "shape.flare")?, f64_req(p, "cy", "shape.flare")?); - let numbers = [ - "diameter", - "opacity", - "brightness", - "growth", - "fuzziness", - "rays", - "longest", - "rayFuzziness", - "rotation", - "rings", - "largest", - "x2", - "y2", - "direction", - "pathLength", - "seed", - "ringSeed", - ]; - check_numbers(p, &numbers, "shape.flare")?; - let pct = |k: &str, d: f64| (f64_or(p, k, d) / 100.0).clamp(0.0, 10.0); - let r = (f64_or(p, "diameter", 100.0) / 2.0).max(0.5); - let opacity = pct("opacity", 50.0).min(1.0) as f32; - let brightness = pct("brightness", 30.0).min(1.0) as f32; - let growth = pct("growth", 20.0); - let fuzz = pct("fuzziness", 50.0).min(1.0); - let rays = p.get("rays").and_then(Value::as_u64).unwrap_or(15).min(50) as usize; - let longest = pct("longest", 300.0); - let ray_fuzz = pct("rayFuzziness", 100.0).min(1.0); - let ray_turn = f64_or(p, "rotation", 0.0).to_radians(); - let rings = p.get("rings").and_then(Value::as_u64).unwrap_or(10).min(50) as usize; - let largest = pct("largest", 50.0); - let end = match (p.get("x2").and_then(Value::as_f64), p.get("y2").and_then(Value::as_f64)) { - (Some(x), Some(y)) => Point::new(x, y), - _ => { - let a = f64_or(p, "direction", 45.0).to_radians(); - c + vectorcraft_geom::Vec2::new(a.cos(), -a.sin()) * f64_or(p, "pathLength", 300.0) - } - }; - // Deterministic pseudo-random sizes (same parameters → same flare). `ringSeed` places the rings - // along the path from a sequence of its own; their count and sizes and the other parts stay. - let seed_of = |key: &str| match p.get(key) { - None | Some(Value::Null) => Ok(None), - Some(v) => v.as_u64().map(Some).ok_or_else(|| bad("shape.flare", format!("`{key}` must be a whole number of at least 0, not {v}"))), - }; - // Xorshift64. Both streams start from a nonzero state. - let random = |mut state: u64| { - move || { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - (state >> 11) as f64 / (1u64 << 53) as f64 - } - }; - let mut rnd = random(seed_of("seed")?.unwrap_or(0x2545_f491_4f6c_dd1d) | 1); - // Each `ringSeed` below 2^53 (what a JSON number holds exactly) gets a state of its own. - let ring_seed = match seed_of("ringSeed")? { - Some(r) if r >= 1 << 53 => return Err(bad("shape.flare", format!("`ringSeed` must be below 2^53, not {r}"))), - r => r, - }; - let mut ring_at = ring_seed.map(|r| { - // SplitMix64 initializes the ring-position stream. - let mut z = r.wrapping_add(0x9e37_79b9_7f4a_7c15); - z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); - z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); - random(z ^ (z >> 31)) - }); - let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, vectorcraft_color::Color::WHITE) }; - let radial = |centre: Point, radius: f64, stops: Vec| { - let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops)); - g.geom = Some(GradientGeom { start: centre, end: centre + vectorcraft_geom::Vec2::new(radius, 0.0), aspect: 1.0, focal: None }); - Paint::Gradient(Box::new(g)) - }; - let circle = |centre: Point, radius: f64| shapes::ellipse(Rect::from_center_size(centre, (radius * 2.0, radius * 2.0))); - let mut parts: Vec<(&str, PathData, Paint, f32)> = vec![]; - // Halo: a soft ring just outside the centre. - let halo_r = r * (1.0 + growth) * 1.6; - let inner = (1.0 - fuzz as f32 * 0.6).clamp(0.05, 0.95); - parts.push(("Halo", circle(c, halo_r), radial(c, halo_r, vec![stop(0.0, 0.0), stop(inner * 0.75, 0.0), stop(inner, 0.5), stop(1.0, 0.0)]), 1.0)); - // Rays: thin spikes of random length (Longest = % of the centre radius), fading outwards. - // `rotation` turns them clockwise about the center. - if rays > 0 { - let mut bp = vectorcraft_geom::BezPath::new(); - let mut reach: f64 = 0.0; - for i in 0..rays { - let a = std::f64::consts::TAU * (i as f64 + rnd() * 0.6) / rays as f64 + ray_turn; - let len = r * longest * (1.0 - ray_fuzz * 0.75 * rnd()).max(0.1); - reach = reach.max(len); - let w = r * 0.035; - let dir = vectorcraft_geom::Vec2::new(a.cos(), a.sin()); - let n = vectorcraft_geom::Vec2::new(-dir.y, dir.x) * w; - bp.move_to(c + n); - bp.line_to(c + dir * len); - bp.line_to(c - n); - bp.line_to(c - dir * (w * 4.0)); - bp.close_path(); - } - parts.push(("Rays", PathData::from_bezpath(&bp), radial(c, reach, vec![stop(0.0, 0.9), stop(0.25, 0.35), stop(1.0, 0.0)]), 1.0)); - } - // Centre: bright core fading to transparent. - parts.push(("Center", circle(c, r), radial(c, r, vec![stop(0.0, 1.0), stop(0.25 + brightness * 0.5, 0.6), stop(1.0, 0.0)]), opacity)); - // Rings along the path to the end point (Largest = % of the average ring size). - for _ in 0..rings { - let t = rnd(); - let t = ring_at.as_mut().map_or(t, |next| next()); - let at = c + (end - c) * t; - let rr = (r * largest * (0.25 + rnd() * 0.75)).max(0.5); - let solid = rnd() < 0.5; - let stops = if solid { - vec![stop(0.0, 0.25), stop(0.8, 0.2), stop(1.0, 0.0)] - } else { - vec![stop(0.0, 0.0), stop(0.7, 0.05), stop(0.92, 0.35), stop(1.0, 0.0)] - }; - parts.push(("Ring", circle(at, rr), radial(at, rr, stops), 1.0)); - } - let parent = s.doc()?.target_parent()?; - let id = s.edit("Flare", |d, sel| { - let children = parts - .into_iter() - .map(|(name, pd, paint, op)| { - let mut n = Node::path(d.alloc_id(), pd, Appearance::basic(paint, Paint::None, 0.0)); - n.name = Some(name.into()); - n.blend = BlendMode::Screen; - n.opacity = op; - super::object::align_new_object(d, &mut n); - std::sync::Arc::new(n) - }) - .collect(); - let gid = d.alloc_id(); - let mut g = Node::group(gid, children); - g.name = Some("Flare".into()); - d.insert(parent, usize::MAX, g)?; - sel.set([gid]); - Ok(gid) - })?; - Ok(json!({ "id": id.0 })) -} - fn line(s: &mut Session, p: &Value) -> Result { let a = Point::new(f64_req(p, "x1", "shape.line")?, f64_req(p, "y1", "shape.line")?); let b = Point::new(f64_req(p, "x2", "shape.line")?, f64_req(p, "y2", "shape.line")?); diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index 0456a09321..bb22ae5c16 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, 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", + "{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), fontUses: [{font, type: truetype|opentype|unknown, uses}] (each font of fonts, in order: truetype or opentype by the outlines (glyf, or CFF or CFF2) of the face its type is drawn in, unknown for a font not installed in the family and style it names; uses: the text objects set in it, each once however many of its runs use the font, the type in a mask or in a symbol's or pattern's art once however many objects show it; the fonts category's rows give them as `TrueType; 2 uses`), 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 ), @@ -144,6 +144,45 @@ fn font_detail(used: &super::fonts::UsedFont) -> (Value, (String, String)) { (entry, (label, detail)) } +/// The type of a font as Fonts lists it: `truetype` or `opentype` by the outlines of the face the +/// type is drawn in (in the version the type names), `unknown` for a font that is not installed in +/// the family and style it names, or whose face holds neither kind of outline. +fn font_type(used: &super::fonts::UsedFont) -> &'static str { + let db = vectorcraft_text::FontDb::global(); + let (family, style, version) = used; + match db.resolve(family, style) { + Some((f, vectorcraft_text::FontMatch::Exact)) => match db.face_version(family, style, version.as_deref()).unwrap_or(f).outline_format() { + Some(vectorcraft_text::OutlineFormat::TrueType) => "truetype", + Some(vectorcraft_text::OutlineFormat::Cff) => "opentype", + None => "unknown", + }, + _ => "unknown", + } +} + +/// A font as Fonts lists it: its `fontUses` entry and its row, which gives the font's type and its +/// number of uses (`uses`: the text objects set in it). +fn font_use(used: &super::fonts::UsedFont, uses: usize) -> (Value, (String, String)) { + let label = super::fonts::font_label(used); + let kind = font_type(used); + let name = match kind { + "truetype" => "TrueType", + "opentype" => "OpenType", + _ => "unknown type", + }; + let count = if uses == 1 { "1 use".to_string() } else { format!("{uses} uses") }; + (json!({ "font": label, "type": kind, "uses": uses }), (label, format!("{name}; {count}"))) +} + +/// Counts text object `t` once for each font its runs are drawn in, a composite font's parts in +/// place of its name ([`super::fonts::run_fonts`]). +fn count_fonts(fonts: &mut BTreeMap, t: &vectorcraft_doc::TextObject) { + let own: BTreeSet = t.runs.iter().flat_map(super::fonts::run_fonts).collect(); + for font in own { + *fonts.entry(font).or_default() += 1; + } +} + /// An image object as Document Info lists it: (name, width, height, linked file). type ImageRow = (String, u32, u32, Option); @@ -221,16 +260,16 @@ fn selected_artboard_rows(d: &Document, picked: &[usize], active: usize) -> (Vec } /// The Document Info categories of `d` (only `category` when given) from `info` (what -/// `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. +/// `document.info` reports), the rows of the artboards the Artboard tool has selected, the rows of +/// 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, + fonts: &[(String, String)], font_details: &[(String, String)], images: &[ImageRow], brushes: &[(String, String)], @@ -296,7 +335,7 @@ fn sections( "patterns" => pattern_objects.to_vec(), "gradients" => gradient_objects.to_vec(), "symbols" => names("symbols"), - "fonts" => fonts.iter().map(|f| (super::fonts::font_label(f), String::new())).collect(), + "fonts" => fonts.to_vec(), "fontDetails" => font_details.to_vec(), "linkedImages" => { images.iter().filter_map(|(name, w, h, link)| Some((name.clone(), format!("{w} × {h} px — {}", link.as_ref()?)))).collect() @@ -627,7 +666,8 @@ fn info(s: &mut Session, p: &Value) -> Result { // The paths' total length, as Document Info › Objects shows it (the length of a cut line, a // strip of LEDs along the letters, #1958). let mut path_length = 0.0; - let mut fonts = BTreeSet::new(); + // Each font with the number of text objects set in it. + let mut fonts: BTreeMap = BTreeMap::new(); let mut images: BTreeMap = BTreeMap::new(); let mut image_rows: Vec = vec![]; // Whether the request being served may read each linked file (a relative path read from the @@ -702,9 +742,7 @@ fn info(s: &mut Session, p: &Value) -> Result { } NodeKind::Compound { .. } => Some("compoundPaths"), NodeKind::Text(t) => { - for run in &t.runs { - fonts.insert((run.style.font_family.clone(), run.style.font_style.clone(), run.style.font_version.clone())); - } + count_fonts(&mut fonts, t); Some("textObjects") } NodeKind::Image(im) => { @@ -787,12 +825,16 @@ fn info(s: &mut Session, p: &Value) -> Result { } } // The document's fonts include those of the type in opacity masks and in the art of its - // symbols and patterns, as Find Font lists them. + // symbols and patterns, as Find Font lists them. Each of those text objects counts once, however + // many objects show it. if !selection_only { - fonts.extend(super::fonts::art_texts_of(d).into_iter().flat_map(|(_, t, _)| t.runs.iter().map(|r| super::fonts::font_of(&r.style)))); + for (_, t, _) in super::fonts::art_texts_of(d) { + count_fonts(&mut fonts, t); + } } - let font_names: Vec = fonts.iter().map(super::fonts::font_label).collect(); - let (font_entries, font_rows): (Vec, Vec<(String, String)>) = fonts.iter().map(font_detail).unzip(); + let font_names: Vec = fonts.keys().map(super::fonts::font_label).collect(); + let (font_uses, font_use_rows): (Vec, Vec<(String, String)>) = fonts.iter().map(|(f, n)| font_use(f, *n)).unzip(); + let (font_entries, font_rows): (Vec, Vec<(String, String)>) = fonts.keys().map(font_detail).unzip(); // The image objects in walk order, as Linked Images and Embedded Images list them: `file` is a // linked image's row value (its path, or its file name alone when the request may not read it), // and null for an embedded one. @@ -820,6 +862,7 @@ fn info(s: &mut Session, p: &Value) -> Result { "objects": counts, "pathLength": path_length, "fonts": font_names, + "fontUses": font_uses, "fontDetails": font_entries, "images": images, "imageObjects": image_objects, @@ -850,7 +893,7 @@ fn info(s: &mut Session, p: &Value) -> Result { d, &out, &selected_rows, - &fonts, + &font_use_rows, &font_rows, &image_rows, &brush_rows, @@ -1083,6 +1126,92 @@ mod tests { assert_eq!(fonts(&mut s, json!({"selectionOnly": true})), json!(["Source Sans 3 Regular"])); } + /// Fonts gives each font's type and its number of uses: the text objects set in it, each once + /// however many of its runs use the font. The type in a symbol's art counts once however many + /// instances show it, and the type in an opacity mask once. With Selection Only it counts the + /// selected type alone. A font that is not installed has an unknown type. The rows, the report + /// and `fontUses` give the same facts, in the order of `fonts`. + #[test] + fn info_fonts_give_each_font_s_type_and_uses() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let id = |v: Value| NodeId(v["id"].as_u64().unwrap()); + let text = + |s: &mut Session, font: &str, y: f64| id(s.execute("text.create", &json!({"x": 10, "y": y, "text": "Hello", "font": font})).unwrap()); + // Two runs in Source Sans 3 Regular in one text object, a second object in it, and one in Inter. + let twice = text(&mut s, "Source Sans 3", 20.0); + s.execute("text.setRangeStyle", &json!({"id": twice.0, "start": 0, "end": 2, "size": 30})).unwrap(); + assert!(matches!(&s.doc().unwrap().doc.node(twice).unwrap().kind, NodeKind::Text(t) if t.runs.len() == 2)); + let other = text(&mut s, "Source Sans 3", 50.0); + text(&mut s, "Inter", 80.0); + text(&mut s, "Qx Absent Family", 110.0); + // A symbol whose art holds type in Inter, shown by two instances, and a mask holding type in Inter. + let in_symbol = text(&mut s, "Inter", 140.0); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [in_symbol.0]})).unwrap(); + s.execute("symbol.place", &json!({"name": "Mark", "x": 100, "y": 100})).unwrap(); + let masked = id(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()); + let in_mask = text(&mut s, "Inter", 170.0); + s.edit("Mask", |d, _| { + let art = d.remove(in_mask)?; + d.node_mut(masked).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true))); + Ok(()) + }) + .unwrap(); + let i = s.execute("document.info", &json!({"category": "fonts"})).unwrap(); + assert_eq!(i["fonts"], json!(["Inter Regular", "Qx Absent Family Regular", "Source Sans 3 Regular"])); + assert_eq!( + i["fontUses"], + json!([ + {"font": "Inter Regular", "type": "truetype", "uses": 3}, + {"font": "Qx Absent Family Regular", "type": "unknown", "uses": 1}, + {"font": "Source Sans 3 Regular", "type": "truetype", "uses": 2}, + ]) + ); + assert_eq!( + i["sections"][0]["rows"], + json!([ + ["Inter Regular", "TrueType; 3 uses"], + ["Qx Absent Family Regular", "unknown type; 1 use"], + ["Source Sans 3 Regular", "TrueType; 2 uses"], + ]) + ); + let report = s.execute("document.info", &json!({"category": "fonts", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string(); + assert!(report.contains("\nFONTS\nInter Regular: TrueType; 3 uses\nQx Absent Family Regular: unknown type; 1 use\n"), "{report}"); + // Selection Only: the selected type's fonts and uses. + s.execute("select.set", &json!({"ids": [other.0]})).unwrap(); + let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "fonts"})).unwrap(); + assert_eq!(i["fontUses"], json!([{"font": "Source Sans 3 Regular", "type": "truetype", "uses": 1}])); + assert_eq!(i["sections"][0]["rows"], json!([["Source Sans 3 Regular", "TrueType; 1 use"]])); + s.execute("select.none", &json!({})).unwrap(); + let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "fonts"})).unwrap(); + assert_eq!((i["fontUses"].clone(), i["sections"][0]["rows"].clone()), (json!([]), json!([]))); + } + + /// Type set in a composite font counts as a use of the fonts of the parts its characters fall + /// in, as Find Font lists them, not of the composite font's name. + #[test] + fn info_fonts_count_the_parts_of_a_composite_font() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let font = json!({"name": "DI Uses Composite", "parts": { + "kanji": {"font": "Source Sans 3"}, + "roman": {"font": "JetBrains Mono"}, + "numerals": {"font": "Inter"}, + }}); + s.execute("type.compositeFonts.set", &json!({"fonts": [font]})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 20, "text": "Ab1", "font": "DI Uses Composite"})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 50, "text": "12", "font": "DI Uses Composite"})).unwrap(); + let i = s.execute("document.info", &json!({"category": "fonts"})).unwrap(); + assert_eq!(i["fonts"], json!(["Inter Regular", "JetBrains Mono Regular"])); + assert_eq!( + i["fontUses"], + json!([ + {"font": "Inter Regular", "type": "truetype", "uses": 2}, + {"font": "JetBrains Mono Regular", "type": "truetype", "uses": 1}, + ]) + ); + } + /// Document Info › Objects gives the paths' total length in the document's units (#1958): an /// open line, a closed rectangle's perimeter and a compound path's pieces count, a guide doesn't. #[test] diff --git a/crates/engine/src/cmd/draw2.rs b/crates/engine/src/cmd/draw2.rs index 63ae0a3e4c..885fd35988 100644 --- a/crates/engine/src/cmd/draw2.rs +++ b/crates/engine/src/cmd/draw2.rs @@ -28,6 +28,7 @@ mod commands; mod common; mod cut; mod freehand; +mod quickpen; mod smooth; pub use commands::specs; diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index c44aa1b24a..e4846367b5 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -1,6 +1,7 @@ use super::anchors::{convert_anchor, curvature, curvature_edit, remove_anchor, remove_anchors, reshape_segment}; use super::cut::{erase_region, erase_segments, knife, split}; use super::freehand::{blob, freehand}; +use super::quickpen::quick_pen; use super::smooth::{join_scrub, smooth_region}; use super::{CommandSpec, cmd, has_anchors, has_doc, has_selection}; @@ -11,7 +12,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\"} (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", + "{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 ), @@ -33,6 +34,15 @@ pub fn specs() -> Vec { has_doc, curvature_edit ), + cmd!( + "path.quickPen", + "Quick Pen", + [], + None, + "{start?: [x, y] (a new path starts there), id? (or: draw on this path), subpath?: index (0), keep?: count (default: all its points; the points after the first `keep` are replaced), pieces?: [{x, y, action?: \"line\" (default)|\"continuousArc\"|\"sharpArc\", turn?: 1..359 degrees (180), flip?: bool}] (at most 10000), closed?: bool} draw a path of straight lines and circular arcs as the Quick Pen tool does, each piece from the path's last point to x, y: a line; a continuous arc, which leaves its start in the direction the path arrives in (with no direction, the first piece of a path, it is drawn as a sharp-corner arc; with its end straight ahead or straight behind, as a line); a sharp-corner arc, which turns through `turn` degrees and bulges to the left of the direction drawn (with flip, to the right). A piece that ends where the path does adds nothing. closed: a last piece that ends on the first point joins it, otherwise a straight segment closes the path. A new path takes the current paint (a black stroke when it has neither fill nor stroke); the path is selected, as one undo step → {id}. Without id, `start` must be given; with id, the subpath must be open and `start` is refused", + has_doc, + quick_pen + ), cmd!( "path.removeAnchor", "Delete Anchor Point", @@ -92,7 +102,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 ), 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 cabe0e54e3..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()); diff --git a/crates/engine/src/cmd/draw2/quickpen.rs b/crates/engine/src/cmd/draw2/quickpen.rs new file mode 100644 index 0000000000..84640bc876 --- /dev/null +++ b/crates/engine/src/cmd/draw2/quickpen.rs @@ -0,0 +1,96 @@ +//! The Quick Pen tool's command (`path.quickPen`): a path of straight lines and circular arcs. + +use vectorcraft_tools::quickpen::{self as qp, Piece, Stroke}; + +use super::common::{path_kind, path_mut, point_entry, usize_opt, within_input_bound}; +use super::{Color, Paint, PathData, Result, Session, SubPath, Value, add_look, bad, json, number_or, object_param, switch_or}; + +const C: &str = "path.quickPen"; +/// The most pieces one request takes. +const MAX_PIECES: usize = 10_000; + +/// The `pieces` param. +fn pieces(p: &Value) -> Result> { + let list = match p.get("pieces") { + None | Some(Value::Null) => return Ok(vec![]), + Some(Value::Array(list)) if list.len() <= MAX_PIECES => list, + Some(_) => return Err(bad(C, "`pieces` must be a list of at most 10000 pieces")), + }; + list.iter() + .map(|v| { + let to = point_entry(v, C)?; + if !within_input_bound(to) { + return Err(bad(C, "x and y must be finite")); + } + let stroke = match v.get("action") { + None | Some(Value::Null) => Stroke::Line, + Some(a) => a.as_str().and_then(Stroke::parse).ok_or_else(|| { + let key = "action"; + bad(C, format!("`{key}` must be one of {}", Stroke::ALL.map(Stroke::name).join(", "))) + })?, + }; + let turn = number_or(v, "turn", qp::DEFAULT_TURN, C)?; + if !(qp::MIN_TURN..=qp::MAX_TURN).contains(&turn) { + let (key, min, max) = ("turn", qp::MIN_TURN, qp::MAX_TURN); + return Err(bad(C, format!("{key} must be a number from {min} to {max}"))); + } + let flip = switch_or(v, "flip", false, C)?; + Ok(Piece { to, stroke, turn, flip }) + }) + .collect() +} + +pub(super) fn quick_pen(s: &mut Session, p: &Value) -> Result { + let pieces = pieces(p)?; + let closed = switch_or(p, "closed", false, C)?; + let start_given = p.get("start").is_some_and(|v| !v.is_null()); + let either = "give either `start` for a new path or `id`, not both"; + let Some(id) = object_param(p, "id", C)? else { + let start = match p.get("start") { + Some(v) if start_given => point_entry(v, C)?, + _ => return Err(bad(C, either)), + }; + if !within_input_bound(start) { + return Err(bad(C, "x and y must be finite")); + } + if ["subpath", "keep"].iter().any(|key| p.get(key).is_some_and(|v| !v.is_null())) { + return Err(bad(C, "`subpath` and `keep` need `id`")); + } + let sp = qp::build(&SubPath::new(vec![vectorcraft_geom::Anchor::corner(start)], false), &pieces, closed); + let mut look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + let ap = &mut look.appearance; + if ap.stroke_paint().is_none() && ap.fill_paint().is_none() { + ap.set_stroke(Paint::solid(Color::BLACK)); + } + return add_look(s, "Quick Pen", path_kind(PathData::single(sp)), look, None); + }; + if start_given { + return Err(bad(C, either)); + } + let si = usize_opt(p, "subpath", C)?.unwrap_or(0); + let d = &s.doc()?.doc; + if !d.is_editable(id) { + return Err(bad(C, "the path is locked or hidden")); + } + let path = d.node(id).and_then(|n| n.path_data()).ok_or_else(|| bad(C, "`id` is not a path"))?; + let sp = path.subpaths.get(si).ok_or_else(|| bad(C, "no such subpath"))?; + if sp.closed { + return Err(bad(C, "the subpath is closed")); + } + let n = sp.anchors.len(); + let keep = usize_opt(p, "keep", C)?.unwrap_or(n); + if keep == 0 || keep > n { + let (key, min, max) = ("keep", 1, n); + return Err(bad(C, format!("{key} must be a number from {min} to {max}"))); + } + let base = SubPath::new(sp.anchors.get_range(..keep).unwrap_or_default(), false); + let out = qp::build(&base, &pieces, closed); + let top = super::super::path::compound_or_self(d, id); + s.edit("Quick Pen", |d, sel| { + let slot = path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| crate::EngineError::Other("no such subpath".into()))?; + *slot = out; + sel.set([top]); + Ok(()) + })?; + Ok(json!({ "id": id.0 })) +} diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 3b47fedb41..5e0231228b 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -115,7 +115,7 @@ pub fn specs() -> Vec { "Drop Artwork", [], None, - "{sourceDocument: uid, ids: [id…], grab: [x,y], at: [x,y]} copy 1–10000 editable source objects from an open document to the active document, preserving the grab point and clipboard, as one undo step", + "{sourceDocument: uid, ids: [id…], grab: [x,y], at: [x,y], profileMismatch?: as edit.paste} copy 1–10000 editable source objects from an open document to the active document, preserving the grab point and clipboard, as one undo step; colors from a document with another RGB or CMYK profile keep their numbers or convert as profileMismatch says, else as edit.colorSettings' policy of their model says (as edit.paste; clipboard.profileMismatch {sourceDocument, ids} lists them, and with askMismatchPaste on the desktop app asks first) → {ids, added, merged, renamed, profileMismatch?}", has_doc, drop_selection ), @@ -180,7 +180,7 @@ pub fn specs() -> Vec { "Paste", ["Edit"], Some("Cmd+V"), - "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", + "{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?, profileMismatch?: \"preserveNumbers\"|\"convert\"|{rgb?, cmyk?}} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch; legend labels in a pie's wedges that it turns dark or light take a redraw's contrast, unless their fill is their own) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. profileMismatch, for colors copied from a document whose RGB or CMYK profile is not this document's (clipboard.profileMismatch): \"preserveNumbers\" keeps their numbers, \"convert\" converts them into this document's profile with the working intent, and {rgb?, cmyk?} gives one of those for each model (default, also for a model left out and for null: as the model's policy of edit.colorSettings says; any other value is an error; colors whose source or destination profile is not available keep their numbers, also with \"convert\" (clipboard.profileMismatch's convertible: false); every paste command takes it, and the reply's profileMismatch lists [{model, clipboard, document, choice}]). With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}", has_clipboard, |s, p| paste(s, p, PasteMode::Offset) ), @@ -189,7 +189,7 @@ pub fn specs() -> Vec { "Paste in Front", ["Edit"], Some("Cmd+F"), - "{swatchConflict?, artboard?: index (the active artboard: the objects go where they were on the artboard they were copied from, on this one), artboards?: [index…] (a copy on each of these artboards, placed as on `artboard`, the copies in artboard order; `artboard` wins when both are given; default while the Artboard tool is chosen with several artboards selected: those; art copied from no artboard keeps its place on the first and its offset to it on the others; an index the document lacks, a repeated one or an empty list is an error)} paste in place just above the top selected object, or on top of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}", + "{swatchConflict?, profileMismatch? (as edit.paste), artboard?: index (the active artboard: the objects go where they were on the artboard they were copied from, on this one), artboards?: [index…] (a copy on each of these artboards, placed as on `artboard`, the copies in artboard order; `artboard` wins when both are given; default while the Artboard tool is chosen with several artboards selected: those; art copied from no artboard keeps its place on the first and its offset to it on the others; an index the document lacks, a repeated one or an empty list is an error)} paste in place just above the top selected object, or on top of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}", has_clipboard, |s, p| paste(s, p, PasteMode::Front) ), @@ -198,7 +198,7 @@ pub fn specs() -> Vec { "Paste in Back", ["Edit"], Some("Cmd+B"), - "{swatchConflict?, artboard?: index, artboards?: [index…] (both as edit.pasteInFront)} paste in place just below the bottom selected object, or at the bottom of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}", + "{swatchConflict?, profileMismatch?, artboard?: index, artboards?: [index…] (as edit.pasteInFront)} paste in place just below the bottom selected object, or at the bottom of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}", has_clipboard, |s, p| paste(s, p, PasteMode::Back) ), @@ -207,7 +207,7 @@ pub fn specs() -> Vec { "Paste in Place", ["Edit"], Some("Cmd+Shift+V"), - "{swatchConflict?, artboard?: index, artboards?: [index…] (both as edit.pasteInFront)} paste where the objects were copied (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}", + "{swatchConflict?, profileMismatch?, artboard?: index, artboards?: [index…] (as edit.pasteInFront)} paste where the objects were copied (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}", has_clipboard, |s, p| paste(s, p, PasteMode::InPlace) ), @@ -216,7 +216,7 @@ pub fn specs() -> Vec { "Paste on All Artboards", ["Edit"], Some("Cmd+Alt+Shift+V"), - "{swatchConflict?} paste a copy on every artboard at the offset the objects had to the artboard they were copied from (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}", + "{swatchConflict?, profileMismatch? (as edit.paste)} paste a copy on every artboard at the offset the objects had to the artboard they were copied from (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}", has_clipboard, |s, p| paste(s, p, PasteMode::AllArtboards) ), @@ -1278,26 +1278,12 @@ fn clear(s: &mut Session, p: &Value) -> Result { /// Document ids scope node ids: two tabs may contain objects with the same node id. fn drop_selection(s: &mut Session, p: &Value) -> Result { const CMD: &str = "edit.dropSelection"; - let uid = u64_req(p, "sourceDocument", CMD)?; + u64_req(p, "sourceDocument", CMD)?; let point = |key: &str| finite_numbers::<2>(&p[key]).ok_or_else(|| bad(CMD, format!("{key} must be [x, y] with finite coordinates"))); let grab = point("grab")?; let at = point("at")?; - let source = s.documents().iter().find(|d| d.uid == uid).ok_or_else(|| bad(CMD, "that document is no longer open"))?; - let key = "ids"; - let values = p[key].as_array().ok_or_else(|| bad(CMD, format!("{key} must be an array of non-negative integer object ids")))?; - if values.is_empty() || values.len() > 10000 { - return Err(bad(CMD, "ids must contain 1–10000 object ids")); - } - let ids = values - .iter() - .map(|value| value.as_u64().map(NodeId).ok_or_else(|| bad(CMD, format!("invalid object id {value}: expected a non-negative integer")))) - .collect::>>()?; - // Validate the entire batch in one walk; node ids are local to the source document. - let paths = source.doc.index_paths(ids.iter().copied()); - if let Some(id) = ids.iter().find(|id| !paths.contains_key(id)) { - return Err(EngineError::NoNode(*id)); - } - let clip = Clipboard::copy(source, &roots_of(&source.doc, ids), false); + let profile = super::colormgmt::PasteProfile::param(p, CMD)?; + let clip = drop_clip(s, p, CMD)?; let bounds = clip.bounds().ok_or_else(|| bad(CMD, "the art has no bounds"))?; let center = bounds.center() + Vec2::new(at[0] - grab[0], at[1] - grab[1]); if !center.x.is_finite() || !center.y.is_finite() { @@ -1305,7 +1291,38 @@ fn drop_selection(s: &mut Session, p: &Value) -> Result { } // A drop preserves the source colours even when the flyer has same-named swatches. let choices = SwatchChoices::parse(PasteMode::Drag.label(), &json!({"swatchConflict": "add"}))?; - paste_clip(s, &json!({"center": [center.x, center.y]}), PasteMode::Drag, &clip, &choices) + // Colors from another profile keep their numbers or convert, as `profileMismatch` says, else as + // the policies say. + let (converted, report) = super::colormgmt::paste_profiles(&clip, &s.doc()?.doc, profile, true); + let mut r = paste_clip(s, &json!({"center": [center.x, center.y]}), PasteMode::Drag, converted.as_ref().unwrap_or(&clip), &choices); + if let Ok(v) = &mut r + && !report.is_empty() + { + v["profileMismatch"] = json!(report); + } + r +} + +/// The objects `ids` of the open document `sourceDocument` that `edit.dropSelection` drops, copied +/// as a clipboard is (errors name command `cmd`). +pub(crate) fn drop_clip(s: &Session, p: &Value, cmd: &str) -> Result { + let uid = u64_req(p, "sourceDocument", cmd)?; + let source = s.documents().iter().find(|d| d.uid == uid).ok_or_else(|| bad(cmd, "that document is no longer open"))?; + let key = "ids"; + let values = p[key].as_array().ok_or_else(|| bad(cmd, format!("{key} must be an array of non-negative integer object ids")))?; + if values.is_empty() || values.len() > 10000 { + return Err(bad(cmd, "ids must contain 1–10000 object ids")); + } + let ids = values + .iter() + .map(|value| value.as_u64().map(NodeId).ok_or_else(|| bad(cmd, format!("invalid object id {value}: expected a non-negative integer")))) + .collect::>>()?; + // Validate the entire batch in one walk; node ids are local to the source document. + let paths = source.doc.index_paths(ids.iter().copied()); + if let Some(id) = ids.iter().find(|id| !paths.contains_key(id)) { + return Err(EngineError::NoNode(*id)); + } + Ok(Clipboard::copy(source, &roots_of(&source.doc, ids), false)) } #[derive(Clone, Copy, PartialEq, Eq)] @@ -1340,10 +1357,23 @@ fn paste(s: &mut Session, p: &Value, mode: PasteMode) -> Result { if mode == PasteMode::Offset { check_numbers(p, &["dx", "dy"], "edit.paste")?; } + let profile = super::colormgmt::PasteProfile::param(p, mode.label())?; // Taken out of the session for the edit (and put back whatever happens). let clip = std::mem::take(&mut s.clipboard); - let r = paste_clip(s, p, mode, &clip, &choices); + // Colors copied from a document with other profiles keep their numbers or convert + // (Edit › Color Settings' policies, or `profileMismatch`). Paste on All Artboards leaves the + // copied artboards, and so their backgrounds, behind. + let (converted, report) = match s.doc() { + Ok(st) => super::colormgmt::paste_profiles(&clip, &st.doc, profile, mode != PasteMode::AllArtboards), + Err(_) => (None, vec![]), + }; + let mut r = paste_clip(s, p, mode, converted.as_ref().unwrap_or(&clip), &choices); s.clipboard = clip; + if let Ok(v) = &mut r + && !report.is_empty() + { + v["profileMismatch"] = json!(report); + } r } @@ -1520,6 +1550,8 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho vec![Affine::IDENTITY] }; let (ids, imported, artboards, into) = s.edit(mode.label(), |d, sel| { + // Converted colors are compared with the document's resources, as another document's are + // (`Clipboard::import_into`); its images are still the document's own. let imported = clip.import_into(d, choices, same_doc)?; // Draw Inside: the clip group of the object drawn into, made on the first paste. let into = inside.map(|t| super::create::draw_inside_group(d, t)).transpose()?; @@ -1611,6 +1643,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho } } else { super::object::keep_pixel_aligned(&mut c, sc); + super::buildcmds::clear_part_name(d, par, &mut c); new_ids.push(d.insert(par, idx, c)?); } } diff --git a/crates/engine/src/cmd/effectcmd/graphics.rs b/crates/engine/src/cmd/effectcmd/graphics.rs index 498f322e91..8ad440b403 100644 --- a/crates/engine/src/cmd/effectcmd/graphics.rs +++ b/crates/engine/src/cmd/effectcmd/graphics.rs @@ -33,6 +33,15 @@ pub(super) fn specs() -> Vec { has_doc, map_graphic ), + cmd!( + "threeD.mapArt", + "Map Art", + [], + None, + "{surface?: integer (1..the object's surface count: Extrude & Bevel (Classic) numbers each solid's front cap and back cap (none on a hollow solid, cap false), then each side wall from corner to corner of the outline, then the bevel above each wall; Revolve (Classic)'s swept side is surface 1, in a group the side of the member with the longest profile, and the other members take no map), symbol?: name of a document symbol|null (with surface: the symbol mapped onto it; null removes the surface's map, also a map kept past the surface count, and is refused with x, y, scaleX, scaleY, rotation or fit true; omitted: the surface's map keeps its symbol, and a surface with no map is refused), x?: pt, y?: pt (-1000000..1000000; the offset of the art's center from the center of the surface laid out flat; a new map starts at 0, 0), scaleX?: %, scaleY?: % (1..10000; of the symbol's own width and height; a new map starts at 100), rotation?: degrees (-360..360; counterclockwise; a new map starts at 0), fit?: bool (false; true is Scale to Fit: the art is centered and scaled to fill the surface, each side on its own when the art is square to the surface, else in proportion; art with no area keeps its scales), clearAll?: bool (false; true removes every map first, so with surface only that surface's map is left), shade?: bool (Shade Artwork: the mapped art takes the tone and highlight of its face), invisible?: bool (Invisible Geometry: with at least one map, only the mapped art is drawn), index?: int (the 3D effect's position; default: each object's first Extrude & Bevel (Classic) or Revolve (Classic), its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} set, edit or remove the art mapped onto the numbered surfaces of each selected object's 3D effect, which must be Extrude & Bevel (Classic) or Revolve (Classic) (Rotate (Classic) takes no map); one of surface, clearAll, shade or invisible is required; the maps are the effect's mapArt, mapShade and mapInvisible parameters; one undo step, and none when nothing changes → {ids: [the objects changed], maps: [the first object's maps]}", + has_doc, + map_art + ), ] } @@ -166,6 +175,178 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": ids_json(&ids), "graphic": first })) } +/// The effect of `n` that Map Art edits when none is named: its first Extrude & Bevel (Classic) or +/// Revolve (Classic), its own before its fills' and strokes'. +fn first_mapped(n: &Node) -> Option<(Option, usize)> { + let at = |fx: &[Effect]| fx.iter().position(|e| effects::takes_map_art(&e.id)); + at(&n.appearance.effects) + .map(|i| (None, i)) + .or_else(|| n.appearance.items.iter().enumerate().find_map(|(k, item)| at(item.effects()).map(|i| (Some(k), i)))) +} + +/// `threeD.mapArt`: sets, edits or removes the maps of each target's classic 3D effect, after +/// checking that every target takes the change. Nothing is recorded when no target changes. +fn map_art(s: &mut Session, p: &Value) -> Result { + const C: &str = "threeD.mapArt"; + const PLACING: [&str; 6] = ["symbol", "x", "y", "scaleX", "scaleY", "rotation"]; + const KEYS: [&str; 15] = + ["surface", "symbol", "x", "y", "scaleX", "scaleY", "rotation", "fit", "clearAll", "shade", "invisible", "index", "item", "ids", "id"]; + if let Some(key) = p.as_object().and_then(|m| m.keys().find(|k| !KEYS.contains(&k.as_str()))) { + return Err(bad(C, format!("unknown parameter `{key}`"))); + } + if p.get("item").is_some() && p.get("index").is_none() { + return Err(bad(C, "`item` needs `index`")); + } + let surface = match p.get("surface") { + None => None, + Some(v) => Some( + v.as_u64() + .and_then(|n| usize::try_from(n).ok()) + .filter(|n| (1..=effects::MAX_MAP_SURFACE).contains(n)) + .ok_or_else(|| bad(C, "`surface` must be a whole number from 1 to the object's surface count"))?, + ), + }; + let fit = super::super::switch_or(p, "fit", false, C)?; + let clear_all = super::super::switch_or(p, "clearAll", false, C)?; + let flag = |key: &str| -> Result> { + match p.get(key) { + None => Ok(None), + Some(_) => super::super::switch_or(p, key, false, C).map(Some), + } + }; + let (shade, invisible) = (flag("shade")?, flag("invisible")?); + match surface { + None if fit || PLACING.iter().any(|k| p.get(*k).is_some()) => { + return Err(bad(C, "`symbol`, `x`, `y`, `scaleX`, `scaleY`, `rotation` and `fit` need `surface`")); + } + None if !clear_all && shade.is_none() && invisible.is_none() => { + return Err(bad(C, "give `surface`, `clearAll`, `shade` or `invisible`")); + } + _ => {} + } + let removes = p.get("symbol").is_some_and(Value::is_null); + if removes && (fit || PLACING[1..].iter().any(|k| p.get(*k).is_some())) { + return Err(bad(C, "`symbol: null` removes the map: leave out `x`, `y`, `scaleX`, `scaleY`, `rotation` and `fit`")); + } + let d = &s.doc()?.doc; + let targets: Vec<(NodeId, Option, usize)> = if p.get("index").is_some() { + let index = index_param(p, "index", C)?; + let item = item_target(s, p, C)?; + effect_targets(s, p, item, index, C)? + } else { + let mut out = vec![]; + for id in edit_targets(s, p, C)? { + let found = d.node(id).and_then(first_mapped); + let (item, index) = found.ok_or_else(|| bad(C, format!("object {}: {}", id.0, effects::MAP_ART_NOT_TAKEN)))?; + out.push((id, item, index)); + } + out + }; + if targets.is_empty() { + return Err(bad(C, "select an object with a 3D effect")); + } + let mut edits = Vec::with_capacity(targets.len()); + for &(id, item, index) in &targets { + let n = d.node(id).ok_or(EngineError::NoNode(id))?; + let Some(effect) = n.appearance.effects_at(item).and_then(|fx| fx.get(index)).filter(|e| effects::is_three_d(&e.id)) else { + return Err(bad(C, format!("object {} needs a 3D effect at index {index}", id.0))); + }; + if !effects::takes_map_art(&effect.id) { + return Err(bad(C, format!("object {}: {}", id.0, effects::MAP_ART_NOT_TAKEN))); + } + let merged = effects::merged_params(&effect.id, &effect.params); + let mut params = merged.clone(); + if clear_all { + params[effects::MAP_ART] = json!([]); + } + if let Some(surface) = surface { + // Art that can't be built has no surfaces: the effect's own check says why. + let surfaces = match effects::map_surfaces_at(Some(d), n, item, index) { + Some(surfaces) => surfaces, + None => { + effects::validate_three_d_at_in(Some(d), n, &effect.id, &merged, (item, index)).map_err(|e| bad(C, e))?; + vec![] + } + }; + // Read before clearAll empties the list, so with clearAll the surface keeps its map. + let current = effects::surface_maps(&merged).into_iter().find(|m| m.surface == surface); + // A map kept past the surface count (the solid lost surfaces) can still be removed. + let flat = surfaces.get(surface - 1); + if flat.is_none() && !(removes && current.is_some()) { + return Err(bad(C, format!("object {}: `surface` must be from 1 to {}, the object's surface count", id.0, surfaces.len()))); + } + if removes { + params = effects::with_surface_map(¶ms, surface, None); + } else if let Some(flat) = flat { + // The values given go over the surface's map, or over a new map's defaults. + let mut given = match (¤t, p.get("symbol")) { + (Some(m), _) => m.to_value(), + (None, Some(_)) => json!({ "surface": surface }), + (None, None) => return Err(bad(C, format!("object {}: surface {surface} has no map: give `symbol`", id.0))), + }; + for key in PLACING { + if let Some(v) = p.get(key) { + given[key] = v.clone(); + } + } + let mut map = effects::SurfaceMap::from_value(&given).map_err(|e| bad(C, e))?; + // A map whose symbol was deleted keeps it while the request leaves `symbol` out; a + // symbol the request names must exist. + if !d.symbols.iter().any(|sym| sym.name == map.symbol) && (p.get("symbol").is_some() || current.is_none()) { + return Err(bad(C, format!("no symbol named `{}`", map.symbol))); + } + if fit { + // Art or a surface with no area has no size to fit: the map is centered and + // keeps its scales. + let scales = effects::graphic_bounds(d, &map.symbol).and_then(|art| map.fitting_scales(art, (flat.width, flat.height))); + let (scale_x, scale_y) = scales.unwrap_or((map.scale_x, map.scale_y)); + map = effects::SurfaceMap { x: 0.0, y: 0.0, scale_x, scale_y, ..map }; + } + params = effects::with_surface_map(¶ms, surface, Some(&map)); + } + } + for (key, value) in [(effects::MAP_SHADE, shade), (effects::MAP_INVISIBLE, invisible)] { + if let Some(on) = value { + params[key] = json!(on); + } + } + effects::validate_three_d_at_in(Some(d), n, &effect.id, ¶ms, (item, index)).map_err(|e| bad(C, e))?; + let state = |p: &Value| { + let on = |key: &str| p.get(key).and_then(Value::as_bool).unwrap_or(false); + (effects::surface_maps(p), on(effects::MAP_SHADE), on(effects::MAP_INVISIBLE)) + }; + let maps: Vec = effects::surface_maps(¶ms).iter().map(effects::SurfaceMap::to_value).collect(); + let changed = state(¶ms) != state(&merged); + edits.push((id, item, index, params, changed, maps)); + } + let first = edits.first().map(|(.., maps)| maps.clone()).unwrap_or_default(); + if !edits.iter().any(|(.., changed, _)| *changed) { + return Ok(json!({ "ids": [], "maps": first })); + } + let ids = s.edit("Map Art", |d, _| { + let mut done = vec![]; + for (id, item, index, params, changed, _) in &edits { + let Some(e) = d.node_mut(*id).and_then(|n| n.appearance.effects_mut(*item)).and_then(|fx| fx.get_mut(*index)).filter(|_| *changed) else { + continue; + }; + let mut current = effects::upgrade_params(&e.id, &e.params); + for key in [effects::MAP_ART, effects::MAP_SHADE, effects::MAP_INVISIBLE] { + if let (Some(v), Some(m)) = (params.get(key), current.as_object_mut()) { + m.insert(key.into(), v.clone()); + } + } + e.params = current; + done.push(*id); + } + Ok(done) + })?; + Ok(json!({ "ids": ids_json(&ids), "maps": first })) +} + #[cfg(test)] #[path = "graphics_tests.rs"] mod tests; + +#[cfg(test)] +#[path = "map_art_tests.rs"] +mod map_art_tests; diff --git a/crates/engine/src/cmd/effectcmd/map_art_tests.rs b/crates/engine/src/cmd/effectcmd/map_art_tests.rs new file mode 100644 index 0000000000..a63e46b429 --- /dev/null +++ b/crates/engine/src/cmd/effectcmd/map_art_tests.rs @@ -0,0 +1,258 @@ +#![allow(clippy::unwrap_used, clippy::panic)] +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; + +use crate::Session; + +/// A 100 × 100 square with `effect` seen straight on, and a 10 × 20 red rectangle beside it kept +/// as symbol "Mark" (11 × 21 with its stroke). +fn setup(effect: &str) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width":400,"height":400})).unwrap(); + let mark = s.execute("path.create", &json!({"d":"M300 300L310 300L310 320L300 320Z"})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"color":"#ff0000"})).unwrap(); + s.execute("threeD.addGraphic", &json!({"name": "Mark", "ids": [mark]})).unwrap(); + let id = NodeId(s.execute("path.create", &json!({"d":"M100 100L200 100L200 200L100 200Z"})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"color":"#338ad6"})).unwrap(); + s.execute("effect.apply", &json!({"effect":effect,"item":null,"params":{"rotationX":0.0,"rotationY":0.0,"rotationZ":0.0}})).unwrap(); + (s, id) +} + +fn params(s: &Session, id: NodeId) -> Value { + s.doc().unwrap().doc.node(id).unwrap().appearance.effects[0].params.clone() +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn map(surface: u64, x: f64, scale: (f64, f64), rotation: f64) -> Value { + json!({"surface": surface, "symbol": "Mark", "x": x, "y": 0.0, "scaleX": scale.0, "scaleY": scale.1, "rotation": rotation}) +} + +#[test] +fn map_art_sets_edits_and_removes_a_surfaces_map_one_undo_step_each() { + let (mut s, id) = setup("threeD.classicExtrude"); + let before = s.doc().unwrap().doc.clone(); + let history = undo_len(&s); + let r = s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark", "x": 5.0, "rotation": 30.0})).unwrap(); + assert_eq!(r["ids"], json!([id.0])); + assert_eq!(r["maps"], json!([map(1, 5.0, (100.0, 100.0), 30.0)])); + assert_eq!(params(&s, id)["mapArt"], json!([map(1, 5.0, (100.0, 100.0), 30.0)])); + assert_eq!(undo_len(&s), history + 1); + // Without a symbol the surface's map keeps its own, and only the values given change. + s.execute("threeD.mapArt", &json!({"surface": 1, "scaleX": 50.0})).unwrap(); + assert_eq!(params(&s, id)["mapArt"], json!([map(1, 5.0, (50.0, 100.0), 30.0)])); + // Another surface takes a map of its own, kept in the order of the surfaces. + s.execute("threeD.mapArt", &json!({"surface": 4, "symbol": "Mark"})).unwrap(); + s.execute("threeD.mapArt", &json!({"surface": 2, "symbol": "Mark"})).unwrap(); + let surfaces: Vec = params(&s, id)["mapArt"].as_array().unwrap().iter().map(|m| m["surface"].as_u64().unwrap()).collect(); + assert_eq!(surfaces, [1, 2, 4]); + // Shade Artwork and Invisible Geometry are the effect's own flags. + s.execute("threeD.mapArt", &json!({"shade": true, "invisible": true})).unwrap(); + assert_eq!((params(&s, id)["mapShade"].clone(), params(&s, id)["mapInvisible"].clone()), (json!(true), json!(true))); + // A null symbol clears one surface, and clearAll every surface. + s.execute("threeD.mapArt", &json!({"surface": 2, "symbol": null})).unwrap(); + assert_eq!(params(&s, id)["mapArt"].as_array().unwrap().len(), 2); + let r = s.execute("threeD.mapArt", &json!({"clearAll": true})).unwrap(); + assert_eq!((r["maps"].clone(), params(&s, id)["mapArt"].clone()), (json!([]), json!([]))); + // With a surface, clearAll leaves that surface's new map alone. + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap(); + s.execute("threeD.mapArt", &json!({"surface": 3, "symbol": "Mark", "clearAll": true})).unwrap(); + assert_eq!(params(&s, id)["mapArt"], json!([map(3, 0.0, (100.0, 100.0), 0.0)])); + // Without a symbol, clearAll keeps the surface's own map and edits it. + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap(); + s.execute("threeD.mapArt", &json!({"surface": 3, "x": 4.0, "clearAll": true})).unwrap(); + assert_eq!(params(&s, id)["mapArt"], json!([map(3, 4.0, (100.0, 100.0), 0.0)])); + assert_eq!(undo_len(&s), history + 11); + for _ in 0..11 { + s.execute("edit.undo", &json!({})).unwrap(); + } + assert_eq!(s.doc().unwrap().doc.layers, before.layers); +} + +#[test] +fn a_map_past_the_surface_count_can_still_be_removed() { + let (mut s, id) = setup("threeD.classicExtrude"); + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap(); + s.execute("threeD.mapArt", &json!({"surface": 6, "symbol": "Mark"})).unwrap(); + // With no depth the solid is a plane with fewer surfaces, and the map of surface 6 stays. + s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"depth": 0}})).unwrap(); + let e = s.execute("threeD.mapArt", &json!({"surface": 6, "symbol": "Mark", "x": 3.0})).unwrap_err().to_string(); + assert!(e.contains("the object's surface count"), "{e}"); + s.execute("threeD.mapArt", &json!({"surface": 6, "symbol": null})).unwrap(); + assert_eq!(params(&s, id)["mapArt"], json!([map(1, 0.0, (100.0, 100.0), 0.0)])); + // A surface past the count with no map is still refused. + let e = s.execute("threeD.mapArt", &json!({"surface": 9, "symbol": null})).unwrap_err().to_string(); + assert!(e.contains("the object's surface count"), "{e}"); +} + +#[test] +fn a_map_of_a_deleted_symbol_keeps_it_only_while_the_request_leaves_symbol_out() { + let (mut s, id) = setup("threeD.classicExtrude"); + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap(); + s.execute("symbol.delete", &json!({"name": "Mark"})).unwrap(); + let ids = json!([id.0]); + // Naming the deleted symbol is refused, and nothing changes. + let e = s.execute("threeD.mapArt", &json!({"ids": ids, "surface": 1, "symbol": "Mark", "x": 10.0})).unwrap_err().to_string(); + assert!(e.contains("no symbol named `Mark`"), "{e}"); + assert_eq!(params(&s, id)["mapArt"], json!([map(1, 0.0, (100.0, 100.0), 0.0)])); + // Leaving it out edits the map and keeps its symbol, and `symbol: null` removes the map. + s.execute("threeD.mapArt", &json!({"ids": ids, "surface": 1, "x": 10.0})).unwrap(); + assert_eq!(params(&s, id)["mapArt"], json!([map(1, 10.0, (100.0, 100.0), 0.0)])); + s.execute("threeD.mapArt", &json!({"ids": ids, "surface": 1, "symbol": null})).unwrap(); + assert_eq!(params(&s, id)["mapArt"], json!([])); +} + +#[test] +fn scale_to_fit_centers_the_art_and_fills_the_surface() { + let (mut s, id) = setup("threeD.classicExtrude"); + // The cap is 100 × 100 and the symbol's art 11 × 21. + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark", "x": 20.0, "y": 3.0, "fit": true})).unwrap(); + let m = ¶ms(&s, id)["mapArt"][0]; + assert_eq!((m["x"].as_f64(), m["y"].as_f64()), (Some(0.0), Some(0.0))); + assert!((m["scaleX"].as_f64().unwrap() - 100.0 / 11.0 * 100.0).abs() < 1e-6, "{m}"); + assert!((m["scaleY"].as_f64().unwrap() - 100.0 / 21.0 * 100.0).abs() < 1e-6, "{m}"); + // A side wall is 100 along the outline and as deep as the solid, 50. + s.execute("threeD.mapArt", &json!({"surface": 3, "symbol": "Mark", "fit": true})).unwrap(); + let m = ¶ms(&s, id)["mapArt"][1]; + assert!((m["scaleY"].as_f64().unwrap() - 50.0 / 21.0 * 100.0).abs() < 1e-6, "{m}"); +} + +#[test] +fn a_change_that_changes_nothing_records_no_undo_step() { + let (mut s, id) = setup("threeD.classicExtrude"); + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap(); + let history = undo_len(&s); + let same = params(&s, id); + for p in [ + json!({"surface": 1, "symbol": "Mark"}), + json!({"surface": 1, "x": 0.0, "scaleX": 100.0}), + json!({"surface": 2, "symbol": null}), + json!({"shade": false}), + json!({"invisible": false}), + ] { + let r = s.execute("threeD.mapArt", &p).unwrap(); + assert_eq!(r["ids"], json!([]), "{p}"); + assert_eq!((undo_len(&s), params(&s, id)), (history, same.clone()), "{p}"); + } + // Clearing an object with no map records nothing either. + let (mut s, _) = setup("threeD.classicRevolve"); + let history = undo_len(&s); + assert_eq!(s.execute("threeD.mapArt", &json!({"clearAll": true})).unwrap()["ids"], json!([])); + assert_eq!(undo_len(&s), history); +} + +#[test] +fn bad_surfaces_symbols_and_values_are_refused() { + let (mut s, id) = setup("threeD.classicExtrude"); + let history = undo_len(&s); + let maps = params(&s, id)["mapArt"].clone(); + for (p, error) in [ + (json!({}), "give `surface`, `clearAll`, `shade` or `invisible`"), + (json!({"surface": 0, "symbol": "Mark"}), "`surface` must be a whole number"), + (json!({"surface": 1.5, "symbol": "Mark"}), "`surface` must be a whole number"), + (json!({"surface": "front", "symbol": "Mark"}), "`surface` must be a whole number"), + // The fill's solid has 6 surfaces and the stroke's, a square ring, 10: two caps and the + // four walls of each of its two outlines. + (json!({"surface": 17, "symbol": "Mark"}), "`surface` must be from 1 to 16"), + (json!({"surface": 1, "symbol": "Gone"}), "no symbol named `Gone`"), + (json!({"surface": 1, "symbol": 3}), "needs `symbol`"), + (json!({"surface": 1}), "surface 1 has no map: give `symbol`"), + (json!({"surface": 1, "symbol": "Mark", "scaleX": 0}), "scaleX must be a number from 1 to 10000"), + (json!({"surface": 1, "symbol": "Mark", "scaleY": 10001}), "scaleY must be a number from 1 to 10000"), + (json!({"surface": 1, "symbol": "Mark", "rotation": -361}), "rotation must be a number from -360 to 360"), + (json!({"surface": 1, "symbol": "Mark", "x": 1e7}), "x must be a number"), + (json!({"surface": 1, "symbol": "Mark", "y": "up"}), "y must be a number"), + (json!({"surface": 1, "symbol": "Mark", "fit": 1}), "fit"), + (json!({"surface": 1, "symbol": null, "x": 4.0}), "`symbol: null` removes the map"), + (json!({"surface": 1, "symbol": null, "rotation": 30.0}), "`symbol: null` removes the map"), + (json!({"surface": 1, "symbol": null, "fit": true}), "`symbol: null` removes the map"), + (json!({"symbol": "Mark"}), "need `surface`"), + (json!({"fit": true}), "need `surface`"), + (json!({"shade": "on"}), "shade"), + (json!({"invisible": 1}), "invisible"), + (json!({"clearAll": "yes"}), "clearAll"), + (json!({"surface": 1, "symbol": "Mark", "face": "front"}), "unknown parameter `face`"), + (json!({"surface": 1, "symbol": "Mark", "item": null}), "`item` needs `index`"), + (json!({"surface": 1, "symbol": "Mark", "index": 3}), "needs a 3D effect at index 3"), + ] { + let e = s.execute("threeD.mapArt", &p).unwrap_err().to_string(); + assert!(e.contains(error), "{p}: {e}"); + } + assert_eq!((undo_len(&s), params(&s, id)["mapArt"].clone()), (history, maps)); + // Revolve (Classic) has one surface, and the other 3D effects take no map. + let (mut s, _) = setup("threeD.classicRevolve"); + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap(); + let e = s.execute("threeD.mapArt", &json!({"surface": 2, "symbol": "Mark"})).unwrap_err().to_string(); + assert!(e.contains("`surface` must be from 1 to 1"), "{e}"); + for effect in ["threeD.classicRotate", "threeD.extrude", "threeD.revolve"] { + let (mut s, _) = setup(effect); + for p in [json!({"surface": 1, "symbol": "Mark"}), json!({"surface": 1, "symbol": "Mark", "index": 0})] { + let e = s.execute("threeD.mapArt", &p).unwrap_err().to_string(); + assert!(e.contains("Map Art maps symbols onto Extrude & Bevel (Classic) and Revolve (Classic)"), "{effect}: {e}"); + } + // The effect's own parameters refuse a map too. + let e = s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"mapArt": [{"surface": 1, "symbol": "Mark"}]}})); + assert!(e.is_err(), "{effect}"); + } +} + +#[test] +fn a_mapped_symbol_is_drawn_expanded_renamed_and_kept_in_use() { + let (mut s, id) = setup("threeD.classicExtrude"); + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark", "scaleX": 300.0})).unwrap(); + // effect.setParams takes the same maps and refuses a symbol the document does not have. + let e = s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"mapArt": [{"surface": 1, "symbol": "Gone"}]}})); + assert!(e.unwrap_err().to_string().contains("Gone")); + // The symbol counts as used, and renaming it renames it in the map. + assert_eq!(s.execute("symbol.unused", &json!({})).unwrap()["names"], json!([])); + s.execute("symbol.options", &json!({"name": "Mark", "newName": "Logo"})).unwrap(); + assert_eq!(params(&s, id)["mapArt"][0]["symbol"], "Logo"); + // Expand Appearance keeps the mapped art: the red fill is among the expanded paths. + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + let mut red = 0; + for l in &d.layers { + l.walk(&mut |n| { + for item in &n.appearance.items { + if let vectorcraft_doc::AppearanceItem::Fill(f) = item + && f.paint.color().is_some_and(|c| c.to_rgb()[0] > 0.9 && c.to_rgb()[1] < 0.1 && c.to_rgb()[2] < 0.1) + && n.visual_bounds().is_some_and(|b| b.x0 < 250.0) + { + red += 1; + } + } + }); + } + assert!(red > 0, "the expanded art holds the mapped symbol's red fill"); +} + +#[test] +fn pasted_into_another_document_a_map_brings_its_symbol() { + let (mut s, id) = setup("threeD.classicExtrude"); + s.execute("threeD.mapArt", &json!({"surface": 1, "symbol": "Mark"})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // The symbol the pasted object's map names, and the size of that symbol's art. + let pasted = |s: &mut Session| { + s.execute("edit.paste", &json!({})).unwrap(); + let st = s.doc().unwrap(); + let n = st.doc.node(st.selection.objects[0]).unwrap(); + let name = n.appearance.effects[0].params["mapArt"][0]["symbol"].as_str().unwrap().to_string(); + let size = vectorcraft_render::effects::graphic_bounds(&st.doc, &name).map(|r| (r.width(), r.height())); + (name, size) + }; + // A document without the symbol gets it. + s.execute("file.new", &json!({"width":400,"height":400})).unwrap(); + assert_eq!(pasted(&mut s), ("Mark".to_string(), Some((11.0, 21.0)))); + // A document whose symbol "Mark" is other art gets the copied symbol under a free name, and + // the map names it. + s.execute("file.new", &json!({"width":400,"height":400})).unwrap(); + let other = s.execute("path.create", &json!({"d":"M0 0L50 0L50 50L0 50Z"})).unwrap()["id"].clone(); + s.execute("threeD.addGraphic", &json!({"name": "Mark", "ids": [other]})).unwrap(); + let (name, size) = pasted(&mut s); + assert_ne!(name, "Mark"); + assert_eq!(size, Some((11.0, 21.0))); +} diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 7117899baf..d63489fb2e 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -182,7 +182,7 @@ impl Expandable { n.walk(&mut |c| { let shape = matches!(c.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }); e.text |= matches!(c.kind, NodeKind::Text(_)); - e.live |= matches!(c.kind, NodeKind::Path { live: Some(_), .. }); + e.live |= matches!(c.kind, NodeKind::Path { live: Some(_), .. }) || c.extras().flare.is_some(); e.effects |= !c.appearance.effects.is_empty(); e.envelope |= matches!(c.kind, NodeKind::Envelope { .. }); e.blends |= matches!(c.kind, NodeKind::Blend { .. }); @@ -503,10 +503,14 @@ fn end_dimension_links(s: &mut Session, ended: &mut Vec) -> Result<() Ok(()) } +/// Makes the live shapes in `n` plain paths, and the flares plain groups of their parts. fn drop_live(n: &mut Node) { if let NodeKind::Path { live, .. } = &mut n.kind { *live = None; } + if n.extras().flare.is_some() { + n.extras_mut().flare = None; + } if let Some(ch) = n.children_mut() { for c in ch.iter_mut() { drop_live(Arc::make_mut(c)); diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index cd6ec30f0d..4f0c3d6005 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -17,6 +17,8 @@ //! - `eps`: EPS export options (flattened transparency, previews, the embedded document), `document.exportEps`. //! - `dxfimport`: the DXF options `document.open` and Place read, `document.dxfInfo`. //! - `metafile`: EMF and WMF export, open and place; PICT open and place. +//! - `cdr`: `.cdr` drawings of versions 1 to 27 and `.cdt` templates, and `.cmx` files with +//! 32-bit coordinates, open and place. //! - `hpgl`: HP-GL export options and plots. //! - `importer`: files that importer plug-ins open (`document.open {importer}`, and extensions no //! built-in format reads). @@ -28,6 +30,7 @@ mod action_batch; mod affinity; mod batch; +mod cdr; pub mod dxf; pub mod dxfimport; mod encode; @@ -41,7 +44,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; @@ -84,7 +87,7 @@ pub(crate) use load::page_or_editing_data; pub(crate) use load::source; pub use load::{ Loaded, RasterImage, ReadFile, detect, file_name, load, load_with, open_bytes, open_bytes_with, open_read, open_template, raster_image, - read_for_open, texture_image, + read_for_open, read_for_open_asking, texture_image, }; pub(crate) use load::{check_files_not_lossy_overwrite, check_not_lossy_overwrite, lossy_source}; pub use load::{losses_summary, overwrite_losses}; @@ -98,7 +101,7 @@ pub use native::with_compression_pref; pub(crate) use pdfimport::opened_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 use psdlayers::{LAYER_WARNINGS as PSD_LAYER_WARNINGS, MERGED_WARNING as PSD_MERGED_WARNING, PsdInfo, info as psd_info}; pub(crate) use psdslices::over as psd_slices; pub(crate) use save::job_for; pub(crate) use save::save as save_document; @@ -175,6 +178,10 @@ mod tests_affinity; #[cfg(test)] mod tests_artboard_fill; #[cfg(test)] +mod tests_cdr; +#[cfg(test)] +mod tests_cmx; +#[cfg(test)] mod tests_pdf; #[cfg(test)] mod tests_pdfcolor; diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index bd55624b32..8ca1fedcd7 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -297,7 +297,17 @@ pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> { vectorcraft_doc::cancel::check()?; may_write(path)?; // Never a half-written file: see [`write_atomic`]. - write_atomic(std::path::Path::new(path), bytes).map_err(|e| EngineError::Other(format!("{path}: {e}"))) + write_atomic(std::path::Path::new(path), bytes).map_err(|e| write_error(path, e)) +} + +/// The error writing `path` failed with: [`EngineError::Cancelled`] for work canceled before the +/// file was put in place ([`vectorcraft_format::write_atomic_with`]), otherwise the path and the reason. +#[cfg(not(target_arch = "wasm32"))] +fn write_error(path: &str, error: std::io::Error) -> EngineError { + if error.get_ref().is_some_and(|e| e.is::()) { + return EngineError::Cancelled; + } + EngineError::Other(format!("{path}: {error}")) } /// [`write_file`] with what `fill` writes into the file (a save streamed into it). @@ -305,7 +315,7 @@ pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> { pub fn write_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> { vectorcraft_doc::cancel::check()?; may_write(path)?; - vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| EngineError::Other(format!("{path}: {e}"))) + vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| write_error(path, e)) } /// The save commands' writer: preserves a filesystem location refusal as a typed error. Other @@ -324,8 +334,10 @@ pub fn write_save_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::W #[cfg(not(target_arch = "wasm32"))] pub(super) fn save_write_error(path: &str, error: std::io::Error) -> EngineError { - let reason = format!("{path}: {error}"); - if vectorcraft_format::read_only_location(&error) { EngineError::ReadOnlyLocation(reason) } else { EngineError::Other(reason) } + if !vectorcraft_format::read_only_location(&error) { + return write_error(path, error); + } + EngineError::ReadOnlyLocation(format!("{path}: {error}")) } #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 5863dd4ff7..93670cefd9 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -68,6 +68,7 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { o.insert("commands".into(), Value::Array(cmds)); } if !s.previewing { + s.note_shape_drawn("command.batch", &entry); s.journal.push(("command.batch".into(), entry)); } Ok(json!({ "results": results })) diff --git a/crates/engine/src/cmd/fileio/cdr.rs b/crates/engine/src/cmd/fileio/cdr.rs new file mode 100644 index 0000000000..aaa3f46ad0 --- /dev/null +++ b/crates/engine/src/cmd/fileio/cdr.rs @@ -0,0 +1,494 @@ +//! `.cdr` drawings of versions 1 to 27 (`.cdr`, and `.cdt` templates): the pages, layers, +//! guidelines, groups, curves, rectangles, ellipses, arcs and polygons with uniform fills and +//! outlines, their hidden and locked states, fill rules and uniform transparency that +//! `vectorcraft-cdr` reads, mapped to editable VectorCraft art. Pages become +//! artboards side by side; layers of the same name on different pages become one layer where the +//! pages stack them in the same order. What the +//! reader leaves out is listed in the warnings, one line for each kind ([`note`]). `.cmx` exchange +//! files with 32-bit coordinates are mapped the same way, with their own warnings ([`cmx_note`]). + +use std::collections::HashMap; +use std::sync::Arc; + +use kurbo::{Affine, Rect}; +use vectorcraft_cdr::model::{self as cd, LayerKind}; +use vectorcraft_cdr::{Limits, Warning}; +use vectorcraft_doc::{Artboard, ColorMode, Document, Guide, LayerColor, Node, NodeKind}; + +use super::load::err; +use crate::Result; + +mod shapes; + +const UNSUPPORTED_OBJECTS: &str = "CDR text, bitmaps, blends, contours, brush strokes and other objects VectorCraft doesn't read yet were left out"; +const UNSUPPORTED_FILLS: &str = "CDR fountain, pattern, texture and PostScript fills were left out"; +const UNKNOWN_COLORS: &str = "colors in CDR color models VectorCraft doesn't read were opened as black"; +const SPOT_LOOKS: &str = "CDR library colors that the drawing stores only by number were opened as black spot colors"; +const ARROWHEADS: &str = "CDR outline arrowheads were left out"; +const ENVELOPES: &str = "CDR envelopes were not applied, and the shapes under them keep their outlines"; +const LENSES: &str = "CDR lenses and object transparency were not applied, and the objects they are on show opaque"; +const TOO_DEEP: &str = "parts of the drawing nested too deeply, or past the import limits, were left out"; +const DAMAGED: &str = "damaged parts of the drawing were left out"; +const PAGES_CUT: &str = "CDR pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard"; + +const CMX_UNSUPPORTED_OBJECTS: &str = + "CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out"; +const CMX_UNSUPPORTED_FILLS: &str = "CMX fills other than uniform colors were left out"; +const CMX_UNKNOWN_COLORS: &str = "colors in CMX color models VectorCraft doesn't read were opened as black"; +const CMX_SPOT_LOOKS: &str = "CMX library colors that the file stores only by number were opened as black spot colors"; +const CMX_ARROWHEADS: &str = "CMX outline arrowheads were left out"; +const CMX_LENSES: &str = "CMX lenses were not applied"; +const CMX_PAGES_CUT: &str = "CMX pages longer than 163,830 pt were opened at that length, and art near their edges lies outside the artboard"; + +/// What reading a drawing left out or changed, for each kind the reader reports. +fn note(w: Warning) -> &'static str { + match w { + Warning::UnsupportedObjects => UNSUPPORTED_OBJECTS, + Warning::UnsupportedFills => UNSUPPORTED_FILLS, + Warning::UnknownColors => UNKNOWN_COLORS, + Warning::SpotLooks => SPOT_LOOKS, + Warning::Arrowheads => ARROWHEADS, + Warning::Envelopes => ENVELOPES, + Warning::Lenses => LENSES, + Warning::TooDeep => TOO_DEEP, + Warning::Damaged => DAMAGED, + } +} + +/// What reading a `.cmx` file left out or changed. The reader reports no envelopes in one. +fn cmx_note(w: Warning) -> &'static str { + match w { + Warning::UnsupportedObjects | Warning::Envelopes => CMX_UNSUPPORTED_OBJECTS, + Warning::UnsupportedFills => CMX_UNSUPPORTED_FILLS, + Warning::UnknownColors => CMX_UNKNOWN_COLORS, + Warning::SpotLooks => CMX_SPOT_LOOKS, + Warning::Arrowheads => CMX_ARROWHEADS, + Warning::Lenses => CMX_LENSES, + Warning::TooDeep => TOO_DEEP, + Warning::Damaged => DAMAGED, + } +} + +/// The page size used when neither the page nor the document settings give one: US Letter, +/// VectorCraft's own choice. +const FALLBACK_PAGE: (f64, f64) = (612.0, 792.0); +/// The layer that holds guidelines at angles other than horizontal and vertical, as guide paths. +const GUIDES_LAYER: &str = "Guides"; +/// The hidden layer that holds hidden guidelines. +const HIDDEN_GUIDES_LAYER: &str = "Hidden guides"; +/// The most pages read, as artboards: the most a new document may have. +const MAX_PAGES: usize = crate::cmd::newdoc::MAX_ARTBOARDS as usize; +/// The longest page side, in points: the longest artboard side a new document may have. +const MAX_PAGE_SIDE: f64 = 16383.0 * 10.0; +/// The gap between pages laid side by side, in points. +const PAGE_GAP: f64 = 36.0; +/// The most objects, subpaths and path segments copied from master layers onto pages, all pages +/// together: the `.af` importer's budget for its master pages (`affinity/master_copies.rs`). +const MAX_MASTER_COPIES: usize = 1 << 23; +/// The most guides and guide paths made, the master page's copied onto every page included. +const MAX_GUIDES: usize = 100_000; +/// The most layers made from the master page's and the pages' layers: VectorCraft's own limit. +const MAX_LAYERS: usize = 10_000; + +/// Is `bytes` a `.cdr` drawing this importer reads? +pub(super) fn is_cdr(bytes: &[u8]) -> bool { + vectorcraft_cdr::is_cdr(bytes) +} + +pub(super) fn import(bytes: &[u8]) -> Result<(Document, Vec)> { + let d = vectorcraft_cdr::read(bytes, Limits::default()).map_err(|e| match e { + vectorcraft_cdr::Error::Version(v) => { + let version = v / 100; + err(format!("CDR {version} drawings can't be opened: VectorCraft reads versions 1 to 27")) + } + why => err(format!("this CDR drawing can't be read ({why})")), + })?; + Ok(build(&d, note, PAGES_CUT)) +} + +/// Is `bytes` a `.cmx` file, of any byte order or coordinate size? +pub(super) fn is_cmx(bytes: &[u8]) -> bool { + vectorcraft_cdr::is_cmx(bytes) +} + +/// A `.cmx` file with 32-bit coordinates: its pages, layers, groups and curves with uniform fills +/// and outlines, mapped as a `.cdr` drawing's are. +pub(super) fn import_cmx(bytes: &[u8]) -> Result<(Document, Vec)> { + let d = vectorcraft_cdr::read_cmx(bytes, Limits::default()).map_err(|why| err(format!("this CMX file can't be read ({why})")))?; + Ok(build(&d, cmx_note, CMX_PAGES_CUT)) +} + +/// The document of `d`, and one warning for each kind of content left out or changed. +fn build(d: &cd::Drawing, note: fn(Warning) -> &'static str, pages_cut: &str) -> (Document, Vec) { + let mut b = shapes::Builder::new(); + let mut doc = b.document(d); + let mut warnings: Vec = Vec::new(); + for w in d.warnings.iter().chain(&b.notes) { + if !warnings.iter().any(|x| x == note(*w)) { + warnings.push(note(*w).to_string()); + } + } + if b.pages_cut { + warnings.push(pages_cut.to_string()); + } + doc.limit_depth_noting(&mut warnings); + (doc, warnings) +} + +/// Where each page lies in the document: its artboard, and the map from its own space (points +/// from its centre, y up) into the document. +struct Placed { + rect: Rect, + to_doc: Affine, +} + +/// Pages laid out by [`place_pages`]. +struct Layout { + placed: Vec, + /// Pages past [`MAX_PAGES`] or past the document's range were left out. + left_out: bool, + /// A page side longer than [`MAX_PAGE_SIDE`] was cut to it. + cut: bool, +} + +/// The pages' artboards side by side, each side held to 1 to [`MAX_PAGE_SIDE`] points. +fn place_pages(d: &cd::Drawing) -> Layout { + let mut x = 0.0; + let size = |p: &cd::Page| p.size.or(d.page_size).unwrap_or(FALLBACK_PAGE); + let sizes: Vec<(f64, f64)> = + if d.pages.is_empty() { vec![d.page_size.unwrap_or(FALLBACK_PAGE)] } else { d.pages.iter().take(MAX_PAGES).map(size).collect() }; + let mut placed = Vec::with_capacity(sizes.len()); + let mut cut = false; + for (w, h) in sizes { + let long = w > MAX_PAGE_SIDE || h > MAX_PAGE_SIDE; + let (w, h) = (w.clamp(1.0, MAX_PAGE_SIDE), h.clamp(1.0, MAX_PAGE_SIDE)); + if x + w > crate::MAX_COORD { + break; + } + cut |= long; + let rect = Rect::new(x, 0.0, x + w, h); + placed.push(Placed { rect, to_doc: Affine::translate((x + w / 2.0, h / 2.0)) * Affine::FLIP_Y }); + x += w + PAGE_GAP; + } + let left_out = placed.len() < d.pages.len(); + Layout { placed, left_out, cut } +} + +impl shapes::Builder { + fn document(&mut self, d: &cd::Drawing) -> Document { + self.learn_spots(d); + let Layout { placed, left_out, cut } = place_pages(d); + if left_out { + self.notes.push(Warning::TooDeep); + } + self.pages_cut = cut; + let (w, h) = placed.first().map_or(FALLBACK_PAGE, |p| (p.rect.width(), p.rect.height())); + let mut doc = Document::new(w, h); + doc.artboards = placed + .iter() + .enumerate() + .map(|(i, p)| Artboard { + id: i as u32 + 1, + name: format!("Page {}", i + 1), + rect: p.rect, + locked: false, + show_center_mark: false, + show_cross_hairs: false, + show_video_safe_areas: false, + video_ruler_pixel_aspect_ratio: 1.0, + color: None, + guide_label: None, + }) + .collect(); + self.doc = doc; + self.name_spots(); + // Bottom to top: the master page's layers, then the pages' in the order first seen. + let mut layers: Vec = Vec::new(); + // A layer is known by its name and how many layers of that name the page has below it, so + // two layers of one name on a page stay two layers. Each key keeps every layer made for + // it, bottom to top. + let mut by_name: HashMap<(String, usize), Vec> = HashMap::new(); + self.master_layers(d, &placed, &mut layers); + // The pages' layers go above the master page's. + let pages_from = layers.len(); + for (i, (page, p)) in d.pages.iter().zip(&placed).enumerate() { + let artboard = Some(i as u32 + 1); + let mut seen: HashMap<&str, usize> = HashMap::new(); + // The layer this page's last layer went to: the next one goes above it. + let mut below: Option = None; + // The file lists layers front to back. + for (j, l) in page.layers.iter().rev().enumerate() { + self.guides(&l.guides, p, artboard); + if l.kind != LayerKind::Drawing && l.kind != LayerKind::Desktop { + continue; + } + let art = self.objects(&l.objects, p.to_doc); + let n = seen.entry(l.name.as_str()).or_insert(0); + let key = (l.name.clone(), *n); + *n += 1; + // A layer an earlier page stacked below this page's last one would put this page's + // art in the wrong order, so the page gets a new layer of that name instead, just + // above its last one. Of the layers of that name above the last one, the lowest + // takes the art. + match by_name.get(&key).and_then(|is| is.iter().copied().find(|&i| below.is_none_or(|b| i > b))) { + Some(i) => { + if let Some(out) = layers.get_mut(i) { + out.add(art, l.flags); + } + below = Some(i); + } + None if layers.len() >= MAX_LAYERS => self.notes.push(Warning::TooDeep), + None => { + // The page's bottom layer goes below the lowest layer that the rest of the + // page shares with earlier pages, so the page keeps its own order. When the + // page shares none, it goes on top, in the order the layers were first seen. + let at = match below { + Some(b) => b + 1, + None => { + let mut counts = seen.clone(); + page.layers + .iter() + .rev() + .skip(j + 1) + .filter(|l| l.kind == LayerKind::Drawing || l.kind == LayerKind::Desktop) + .filter_map(|l| { + let n = counts.entry(l.name.as_str()).or_insert(0); + let key = (l.name.clone(), *n); + *n += 1; + by_name.get(&key).and_then(|is| is.first().copied()) + }) + .min() + .unwrap_or(layers.len()) + .max(pages_from) + } + }; + if at < layers.len() { + for i in by_name.values_mut().flatten().filter(|i| **i >= at) { + *i += 1; + } + } + let is = by_name.entry(key).or_default(); + is.insert(is.partition_point(|&i| i < at), at); + let mut out = LayerOut::new(l.name.clone()); + out.add(art, l.flags); + layers.insert(at, out); + below = Some(at); + } + } + } + } + // Guidelines every page shows, on each page's artboard. + for (i, p) in placed.iter().enumerate() { + self.guides(&d.guides, p, Some(i as u32 + 1)); + } + if !self.guide_paths.is_empty() { + let paths = std::mem::take(&mut self.guide_paths); + // At the layer limit the guide paths go on the top shown layer instead of a layer of + // their own; when every layer is hidden they go on the top one, with the limit warning. + let full = layers.len() >= MAX_LAYERS; + let top = layers.iter().rposition(|l| !l.hidden()).unwrap_or(layers.len().saturating_sub(1)); + match layers.get_mut(top) { + Some(out) if full => { + if out.hidden() { + self.notes.push(Warning::TooDeep); + } + out.kids.extend(paths.into_iter().map(|p| (p, cd::Flags::default()))); + } + _ => { + let mut out = LayerOut::new(GUIDES_LAYER.to_string()); + out.kids.extend(paths.into_iter().map(|p| (p, cd::Flags::default()))); + layers.push(out); + } + } + } + // Hidden guidelines go on a hidden layer of their own on top; past the layer limit they + // are left out. + if !self.hidden_guides.is_empty() || !self.hidden_paths.is_empty() { + if layers.len() >= MAX_LAYERS { + self.notes.push(Warning::TooDeep); + } else { + let mut art = std::mem::take(&mut self.hidden_paths); + for g in std::mem::take(&mut self.hidden_guides) { + let kind = NodeKind::RulerGuide { vertical: g.vertical, pos: g.pos, artboard: g.artboard }; + art.push(Arc::new(Node::new(self.doc.alloc_id(), kind))); + } + let mut out = LayerOut::new(HIDDEN_GUIDES_LAYER.to_string()); + out.add(art, cd::Flags { hidden: true, locked: false }); + layers.push(out); + } + } + let mut doc = std::mem::replace(&mut self.doc, Document::new(1.0, 1.0)); + doc.layers = layers.into_iter().enumerate().map(|(i, out)| out.finish(&mut doc, i)).collect(); + if doc.layers.is_empty() { + let l = layer(&mut doc, "Layer 1", 0, Vec::new(), cd::Flags::default()); + doc.layers.push(l); + } + // Ruler guides go at the top of the top shown layer, in the order they were read. When + // every layer is hidden they go on a layer of their own on top; past the layer limit they + // go on the hidden top layer, with the limit warning. + let guides: Vec> = std::mem::take(&mut self.guide_list) + .into_iter() + .map(|g| Arc::new(Node::new(doc.alloc_id(), NodeKind::RulerGuide { vertical: g.vertical, pos: g.pos, artboard: g.artboard }))) + .collect(); + if !guides.is_empty() && !doc.layers.iter().any(|l| l.visible) && doc.layers.len() < MAX_LAYERS { + let i = doc.layers.len(); + let l = layer(&mut doc, GUIDES_LAYER, i, Vec::new(), cd::Flags::default()); + doc.layers.push(l); + } + let top = doc.layers.iter().rposition(|l| l.visible).unwrap_or(doc.layers.len().saturating_sub(1)); + if !guides.is_empty() && doc.layers.get(top).is_some_and(|l| !l.visible) { + self.notes.push(Warning::TooDeep); + } + if let Some(kids) = doc.layers.get_mut(top).and_then(|l| Arc::make_mut(l).children_mut()) { + kids.extend(guides); + } + self.finish_swatches(&mut doc); + if self.cmyk > self.rgb { + doc.color_mode = ColorMode::Cmyk; + } + doc + } + + /// The master page's layers: the desktop's objects once, on the first page's space; other + /// layers' objects on every page, as many copies as [`MAX_MASTER_COPIES`] allows. + fn master_layers(&mut self, d: &cd::Drawing, placed: &[Placed], layers: &mut Vec) { + for l in d.master.iter().rev() { + if layers.len() >= MAX_LAYERS { + self.notes.push(Warning::TooDeep); + break; + } + let frames: Vec<&Placed> = if l.kind == LayerKind::Desktop { placed.iter().take(1).collect() } else { placed.iter().collect() }; + let mut art = Vec::new(); + let count = copy_cost(&l.objects); + for p in frames { + if count > self.copies_left { + self.notes.push(Warning::TooDeep); + break; + } + self.copies_left -= count; + art.extend(self.objects(&l.objects, p.to_doc)); + } + let name = if l.name.is_empty() { "Master".to_string() } else { l.name.clone() }; + let mut out = LayerOut::new(name); + out.add(art, l.flags); + layers.push(out); + } + } + + /// `guides` of a page placed by `p`: horizontal and vertical ones as guides of the page's + /// artboard, others as guide paths. + fn guides(&mut self, guides: &[cd::Guideline], p: &Placed, artboard: Option) { + for g in guides { + if self.guide_list.len() + self.guide_paths.len() + self.hidden_guides.len() + self.hidden_paths.len() >= MAX_GUIDES { + self.notes.push(Warning::TooDeep); + return; + } + let at = p.to_doc * kurbo::Point::new(g.at.x, g.at.y); + let turn = g.angle.rem_euclid(180.0); + if !(at.x.is_finite() && at.y.is_finite() && at.x.abs() <= crate::MAX_COORD && at.y.abs() <= crate::MAX_COORD) { + self.notes.push(Warning::TooDeep); + continue; + } + let list = if g.hidden { &mut self.hidden_guides } else { &mut self.guide_list }; + if turn.abs() < 1e-9 { + list.push(Guide { artboard, ..Guide::new(false, at.y) }); + } else if (turn - 90.0).abs() < 1e-9 { + list.push(Guide { artboard, ..Guide::new(true, at.x) }); + } else { + self.angled_guide(at, g.angle, p.rect, g.hidden); + } + } + } +} + +/// What one copy of `objects` takes: each object, each subpath and segment of its path, and each +/// dash of its outline, since every copy builds its own path and dash pattern. +fn copy_cost(objects: &[cd::Object]) -> usize { + let mut n: usize = 0; + let mut stack: Vec<&cd::Object> = objects.iter().collect(); + while let Some(o) = stack.pop() { + n = n.saturating_add(1); + match o { + cd::Object::Group { objects: kids, .. } => stack.extend(kids), + cd::Object::Shape(s) => n = n.saturating_add(shape_cost(s)), + cd::Object::Clip { container, objects } => { + // A container whose outline is behind its fill is built twice, as that outline + // and as the clipping path, inside a group of their own. + n = n.saturating_add(shape_cost(container)); + // The second path, without the dashes, which only the outline shape has, and the + // group around the two. + if container.outline.as_ref().is_some_and(|o| o.behind_fill) { + n = n.saturating_add(2 + path_cost(container)); + } + stack.extend(objects); + } + } + } + n +} + +/// What one copy of shape `s` takes past the object itself: its path's subpaths and segments and +/// its outline's dashes. +fn shape_cost(s: &cd::Shape) -> usize { + path_cost(s).saturating_add(s.outline.as_ref().map_or(0, |o| o.dashes.len())) +} + +/// The subpaths and segments of shape `s`'s path. +fn path_cost(s: &cd::Shape) -> usize { + match &s.geometry { + cd::Geometry::Path(p) => p.subpaths.iter().fold(0usize, |n, sp| n.saturating_add(1 + sp.segments.len())), + _ => 0, + } +} + +/// A document layer being made from the drawing's layers of one name: its art bottom to top, each +/// part with the flags of the layer it came from, and those flags for every layer merged into it. +struct LayerOut { + name: String, + kids: Vec<(Arc, cd::Flags)>, + merged: Vec, +} + +impl LayerOut { + fn new(name: String) -> Self { + LayerOut { name, kids: Vec::new(), merged: Vec::new() } + } + + /// Whether the layer node will be hidden: every drawing layer merged into it is. + fn hidden(&self) -> bool { + !self.merged.is_empty() && self.merged.iter().all(|f| f.hidden) + } + + /// Adds the art of a drawing layer with flags `flags`. + fn add(&mut self, art: Vec>, flags: cd::Flags) { + self.kids.extend(art.into_iter().map(|n| (n, flags))); + self.merged.push(flags); + } + + /// The layer node, as the `i`th layer from the bottom. It is hidden or locked when every + /// drawing layer merged into it is; otherwise the art of a hidden or locked drawing layer is + /// hidden or locked object by object. + fn finish(self, doc: &mut Document, i: usize) -> Arc { + let all = |f: fn(&cd::Flags) -> bool| !self.merged.is_empty() && self.merged.iter().all(f); + let own = cd::Flags { hidden: all(|f| f.hidden), locked: all(|f| f.locked) }; + let kids = self + .kids + .into_iter() + .map(|(n, f)| shapes::with_flags(n, cd::Flags { hidden: f.hidden && !own.hidden, locked: f.locked && !own.locked })) + .collect(); + layer(doc, &self.name, i, kids, own) + } +} + +/// A layer of the document named `name` holding `kids` (bottom to top), hidden or locked as +/// `flags` say. +fn layer(doc: &mut Document, name: &str, i: usize, kids: Vec>, flags: cd::Flags) -> Arc { + let name = if name.is_empty() { format!("Layer {}", i + 1) } else { name.to_string() }; + let mut n = Node::layer(doc.alloc_id(), &name, LayerColor::Preset((i % 9) as u8)); + n.visible = !flags.hidden; + n.locked = flags.locked; + if let Some(c) = n.children_mut() { + *c = kids; + } + Arc::new(n) +} diff --git a/crates/engine/src/cmd/fileio/cdr/shapes.rs b/crates/engine/src/cmd/fileio/cdr/shapes.rs new file mode 100644 index 0000000000..6427d49e97 --- /dev/null +++ b/crates/engine/src/cmd/fileio/cdr/shapes.rs @@ -0,0 +1,784 @@ +//! A drawing's objects as VectorCraft art: paths, live rectangles and ellipses, groups, solid +//! fills and strokes, and the spot colors they use as swatches. + +use std::collections::HashMap; +use std::sync::Arc; + +use kurbo::{Affine, BezPath, Point, Rect}; +use vectorcraft_cdr::Warning; +use vectorcraft_cdr::model::{self as cd, Geometry}; +use vectorcraft_color::swatch::REGISTRATION; +use vectorcraft_color::{BlendMode, Color, Paint, Swatch}; +use vectorcraft_doc::appearance::{Appearance, AppearanceItem, Dash, FillLayer, LineCap, LineJoin, StrokeLayer}; +use vectorcraft_doc::geom::{FillRule, PathData}; +use vectorcraft_doc::{Document, Guide, Knockout, LiveShape, Node, NodeKind}; + +/// The most nested groups mapped; the reader holds nesting well below it. +const MAX_DEPTH: usize = 256; +/// The width, in points, of a stroke made from an outline of width 0: the width PDF import gives a +/// line width of 0 (`crates/pdf/src/import/state.rs`). +const HAIRLINE: f64 = 0.25; + +pub(super) struct Builder { + pub(super) doc: Document, + /// What mapping left out, as the reader's warning kinds. + pub(super) notes: Vec, + /// A page side was cut to the longest artboard side. + pub(super) pages_cut: bool, + /// What copies of master art onto the pages may still take ([`super::MAX_MASTER_COPIES`] at + /// the start). + pub(super) copies_left: usize, + /// Horizontal and vertical guidelines, as guides of the pages' artboards. + pub(super) guide_list: Vec, + /// Guidelines at other angles, as guide paths. + pub(super) guide_paths: Vec>, + /// Hidden guidelines, as guides and guide paths of a hidden layer of their own. + pub(super) hidden_guides: Vec, + pub(super) hidden_paths: Vec>, + /// Colors read in each model, which picks the document's color mode. + pub(super) cmyk: usize, + pub(super) rgb: usize, + /// The spot colors used, in the order first seen, with their full-strength color and the tint + /// of the use it was worked out from (`None`: the file stores no color for it). + spots: Vec<(String, Color, Option)>, + spot_index: HashMap, +} + +impl Builder { + pub(super) fn new() -> Self { + Builder { + doc: Document::new(1.0, 1.0), + notes: Vec::new(), + pages_cut: false, + copies_left: super::MAX_MASTER_COPIES, + guide_list: Vec::new(), + guide_paths: Vec::new(), + hidden_guides: Vec::new(), + hidden_paths: Vec::new(), + cmyk: 0, + rgb: 0, + spots: Vec::new(), + spot_index: HashMap::new(), + } + } + + /// Every spot color `d` uses, with its full-strength color taken from its use at the highest + /// tint: a use at a low tint keeps little of the color, and one at 0% keeps none. + pub(super) fn learn_spots(&mut self, d: &cd::Drawing) { + let layers = d.pages.iter().flat_map(|p| &p.layers).chain(&d.master); + let mut stack: Vec<&cd::Object> = layers.flat_map(|l| &l.objects).collect(); + while let Some(o) = stack.pop() { + match o { + cd::Object::Shape(s) => { + for c in s.fill.iter().chain(s.outline.iter().map(|o| &o.color)) { + self.learn_spot(c); + } + } + cd::Object::Group { objects: kids, .. } => stack.extend(kids), + cd::Object::Clip { container, objects } => { + for c in container.fill.iter().chain(container.outline.iter().map(|o| &o.color)) { + self.learn_spot(c); + } + stack.extend(objects); + } + } + } + } + + /// Note spot color `c`, keeping the full-strength color of its use at the highest tint. + fn learn_spot(&mut self, c: &cd::Color) -> Option { + let cd::Color::Spot { name, tint, look } = c else { return None }; + let seen = look.map(|_| *tint); + let base = look.map_or(Color::BLACK, |[r, g, b]| Color::rgb(r, g, b)); + let Some(&i) = self.spot_index.get(name) else { + self.spot_index.insert(name.clone(), self.spots.len()); + self.spots.push((name.clone(), base, seen)); + return Some(base); + }; + let slot = self.spots.get_mut(i)?; + if seen.is_some() && seen > slot.2 { + slot.1 = base; + slot.2 = seen; + } + Some(slot.1) + } + + fn note(&mut self, w: Warning) { + if !self.notes.contains(&w) { + self.notes.push(w); + } + } + + /// `objects` (front to back, as the file lists them) bottom to top, mapped by `to_doc`. + pub(super) fn objects(&mut self, objects: &[cd::Object], to_doc: Affine) -> Vec> { + self.objects_at(objects, to_doc, 0) + } + + fn objects_at(&mut self, objects: &[cd::Object], to_doc: Affine, depth: usize) -> Vec> { + if depth > MAX_DEPTH { + self.note(Warning::TooDeep); + return Vec::new(); + } + let mut out = Vec::with_capacity(objects.len()); + for o in objects.iter().rev() { + match o { + cd::Object::Shape(s) => out.extend(self.shape(s, to_doc, false).map(|n| with_flags(n, s.flags))), + cd::Object::Group { objects: kids, flags } => { + let children = self.objects_at(kids, to_doc, depth + 1); + if !children.is_empty() { + let group = Arc::new(Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: false })); + out.push(with_flags(group, *flags)); + } + } + // A clipping group whose clipping path keeps the container's paint: its fill + // behind the clipped objects and its outline over them. + cd::Object::Clip { container, objects } => { + // A clipping path's stroke paints over the clipped objects, so an outline + // behind the fill becomes a shape of its own below the clipping group, the + // two in a group of their own. + let behind = container.outline.as_ref().is_some_and(|o| o.behind_fill); + let (outline, clip) = if behind { + let outline = self.shape(&cd::Shape { fill: None, ..(**container).clone() }, to_doc, false); + (outline, self.shape(&cd::Shape { outline: None, ..(**container).clone() }, to_doc, true)) + } else { + (None, self.shape(container, to_doc, true)) + }; + let Some(clip) = clip else { continue }; + let mut children = vec![clip]; + children.extend(self.objects_at(objects, to_doc, depth + 1)); + let mut group = Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: true }); + // A see-through container's fill knocks out the outline behind it, so the two + // parts do not add up their transparency where they overlap; the clipped + // objects inside still combine as usual. + let knock = outline.is_some() && (container.opacity < 1.0 || container.blend != cd::Blend::Normal); + if knock { + group.knockout = Knockout::Off; + } + let group = Arc::new(group); + // The container's flags hide or lock the whole clipping group. + let whole = match outline { + Some(outline) => { + let children = vec![outline, group]; + let mut pair = Node::new(self.doc.alloc_id(), NodeKind::Group { children, clip: false }); + if knock { + pair.knockout = Knockout::On; + } + Arc::new(pair) + } + None => group, + }; + out.push(with_flags(whole, container.flags)); + } + } + } + out + } + + /// Shape `s` placed by `to_doc`; as a clipping path when `clipping`. + fn shape(&mut self, s: &cd::Shape, to_doc: Affine, clipping: bool) -> Option> { + let m = to_doc * affine(&s.matrix); + let (path, live) = match &s.geometry { + Geometry::Path(p) => (PathData::from_bezpath(&(m * bez(p))), None), + Geometry::Rect { w, h, radii } => live_rect(*w, *h, *radii, m)?, + Geometry::Ellipse { w, h } => { + let (x0, y0) = (w.min(0.0), h.min(0.0)); + let live = LiveShape::Ellipse { w: w.abs(), h: h.abs(), pie: (0.0, 360.0), xf: m * Affine::translate((x0, y0)) }; + (live.to_path(), Some(live)) + } + }; + if path.is_empty() || !in_range(&path) { + self.note(Warning::TooDeep); + return None; + } + // In paint order: an outline behind the fill comes first. + let mut items = Vec::new(); + if let Some(o) = s.outline.as_ref().filter(|o| o.behind_fill) { + items.push(AppearanceItem::Stroke(self.stroke(o, &s.matrix))); + } + if let Some(c) = &s.fill { + items.push(AppearanceItem::Fill(FillLayer::new(self.paint(c)))); + } + if let Some(o) = s.outline.as_ref().filter(|o| !o.behind_fill) { + items.push(AppearanceItem::Stroke(self.stroke(o, &s.matrix))); + } + // Without the winding flag, a curve of several subpaths is filled with holes where they + // overlap: VectorCraft's own choice of rule for it. + let rule = if s.nonzero { FillRule::NonZero } else { FillRule::EvenOdd }; + let mut n = Node::new(self.doc.alloc_id(), NodeKind::Path { path, rule, live: live.map(Box::new), clipping, guide: false }); + n.appearance = Appearance { items, ..Appearance::default() }.into(); + n.opacity = if s.opacity.is_finite() { s.opacity.clamp(0.0, 1.0) } else { 1.0 }; + n.blend = blend(s.blend); + Some(Arc::new(n)) + } + + /// The stroke of outline `o` on a shape placed by `matrix`. + fn stroke(&mut self, o: &cd::Outline, matrix: &cd::Matrix) -> StrokeLayer { + // The width of an outline scaled with the shape is multiplied by the square root of the + // matrix's area factor (R50). For a matrix that scales x and y differently, that width is + // VectorCraft's own value. + let width = if o.scale_with { + let [a, b, c, d, _, _] = matrix.0; + o.width * (a * d - b * c).abs().sqrt() + } else { + o.width + }; + // A drawn outline of width 0 shows as a hairline, as a PDF line width of 0 does. + let width = if width.is_finite() && width > 0.0 { width.min(1000.0) } else { HAIRLINE }; + let mut l = StrokeLayer::new(self.paint(&o.color), width); + l.cap = match o.cap { + cd::Cap::Butt => LineCap::Butt, + cd::Cap::Round => LineCap::Round, + cd::Cap::Square => LineCap::Square, + }; + l.join = match o.join { + cd::Join::Miter => LineJoin::Miter, + cd::Join::Round => LineJoin::Round, + cd::Join::Bevel => LineJoin::Bevel, + }; + // Dashes are stored in multiples of the outline's width. + if !o.dashes.is_empty() && width > 0.0 { + let pattern: Vec = o.dashes.iter().map(|d| d * width).collect(); + l.dash = Some(Dash { pattern, offset: 0.0, align_corners: false }); + } + l + } + + fn paint(&mut self, c: &cd::Color) -> Paint { + match c { + cd::Color::Rgb([r, g, b]) => { + self.rgb += 1; + Paint::solid(Color::rgb(*r, *g, *b)) + } + cd::Color::Cmyk([c, m, y, k]) => { + self.cmyk += 1; + Paint::solid(Color::cmyk(*c, *m, *y, *k)) + } + cd::Color::Gray(k) => Paint::solid(Color::Gray { k: *k }), + cd::Color::Registration => Paint::Solid { color: Color::cmyk(1.0, 1.0, 1.0, 1.0), swatch: Some(REGISTRATION.into()), tint: 1.0 }, + cd::Color::Spot { name, tint, .. } => { + let base = self.learn_spot(c).unwrap_or(Color::BLACK); + let tint = tint.clamp(0.0, 1.0); + let swatch = self.spot_index.get(name).and_then(|&i| self.spots.get(i)).map_or_else(|| name.clone(), |s| s.0.clone()); + Paint::Solid { color: base.tinted(tint), swatch: Some(swatch), tint } + } + } + } + + /// Gives each spot color a swatch name of its own in the new document: a name its swatches, + /// color groups or Registration already use becomes the first free "name 2", "name 3"…, so + /// the ink stays a spot color. The drawing's other spot names are kept as they are. Call it + /// once the document is made and before any paint. + pub(super) fn name_spots(&mut self) { + let mut free = self.doc.free_swatch_names(); + let clashes: Vec = self.spots.iter().map(|s| s.0 == REGISTRATION || self.doc.swatch_name_taken(&s.0)).collect(); + for (s, _) in self.spots.iter().zip(&clashes).filter(|(_, c)| !**c) { + free.take(&s.0); + } + for (s, _) in self.spots.iter_mut().zip(&clashes).filter(|(_, c)| **c) { + s.0 = free.take(&s.0); + } + } + + /// The spot colors the drawing used, as global spot swatches; a swatch of the same name the + /// document already has is kept as it is. + pub(super) fn finish_swatches(&mut self, doc: &mut Document) { + self.spot_index.clear(); + for (name, color, _) in std::mem::take(&mut self.spots) { + if !doc.swatches.iter().any(|s| s.name == name) { + doc.swatches.push(Swatch { name, paint: Paint::solid(color), global: true, spot: true }); + } + } + } + + /// A guideline through `at` (document space) at `angle` degrees counterclockwise, as a guide + /// path from edge to edge of the page `rect`, so it moves with the page's artboard. A + /// guideline that misses the page runs through `at` for the page's diagonal each way. A + /// `hidden` one goes with the hidden guides. + pub(super) fn angled_guide(&mut self, at: Point, angle: f64, rect: Rect, hidden: bool) { + let (s, c) = angle.to_radians().sin_cos(); + // The document's y axis points down. + let dir = kurbo::Vec2::new(c, -s); + let (a, b) = match chord(at, dir, rect) { + Some((t0, t1)) => (at + dir * t0, at + dir * t1), + None => { + let d = dir * rect.width().hypot(rect.height()).max(1.0); + (at - d, at + d) + } + }; + let mut bp = BezPath::new(); + bp.move_to(a); + bp.line_to(b); + let path = PathData::from_bezpath(&bp); + if !in_range(&path) { + self.note(Warning::TooDeep); + return; + } + let n = Node::new(self.doc.alloc_id(), NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: true }); + if hidden { self.hidden_paths.push(Arc::new(n)) } else { self.guide_paths.push(Arc::new(n)) } + } +} + +/// Where the line through `at` along the unit vector `dir` crosses `rect`: the distances along +/// it to the two edges it meets, the nearer first. None when it misses `rect` or only touches it +/// at a point. +fn chord(at: Point, dir: kurbo::Vec2, rect: Rect) -> Option<(f64, f64)> { + let (mut lo, mut hi) = (f64::NEG_INFINITY, f64::INFINITY); + for (p, d, min, max) in [(at.x, dir.x, rect.x0, rect.x1), (at.y, dir.y, rect.y0, rect.y1)] { + if d.abs() < 1e-12 { + if p < min || p > max { + return None; + } + } else { + let (t0, t1) = ((min - p) / d, (max - p) / d); + lo = lo.max(t0.min(t1)); + hi = hi.min(t0.max(t1)); + } + } + (lo.is_finite() && hi.is_finite() && hi - lo > 1e-9).then_some((lo, hi)) +} + +fn affine(m: &cd::Matrix) -> Affine { + Affine::new(m.0) +} + +fn blend(b: cd::Blend) -> BlendMode { + match b { + cd::Blend::Normal => BlendMode::Normal, + cd::Blend::Multiply => BlendMode::Multiply, + cd::Blend::Screen => BlendMode::Screen, + cd::Blend::Overlay => BlendMode::Overlay, + cd::Blend::SoftLight => BlendMode::SoftLight, + cd::Blend::HardLight => BlendMode::HardLight, + cd::Blend::ColorDodge => BlendMode::ColorDodge, + cd::Blend::ColorBurn => BlendMode::ColorBurn, + cd::Blend::Darken => BlendMode::Darken, + cd::Blend::Lighten => BlendMode::Lighten, + cd::Blend::Difference => BlendMode::Difference, + cd::Blend::Exclusion => BlendMode::Exclusion, + cd::Blend::Hue => BlendMode::Hue, + cd::Blend::Saturation => BlendMode::Saturation, + cd::Blend::Color => BlendMode::Color, + cd::Blend::Luminosity => BlendMode::Luminosity, + } +} + +/// `n` hidden or locked as `flags` say; left as it is when they say neither. +pub(super) fn with_flags(mut n: Arc, flags: cd::Flags) -> Arc { + if flags.hidden || flags.locked { + let m = Arc::make_mut(&mut n); + m.visible &= !flags.hidden; + m.locked |= flags.locked; + } + n +} + +fn bez(p: &cd::Path) -> BezPath { + let pt = |q: cd::Pt| Point::new(q.x, q.y); + let mut bp = BezPath::new(); + for s in &p.subpaths { + bp.move_to(pt(s.start)); + for seg in &s.segments { + match *seg { + cd::Segment::Line(e) => bp.line_to(pt(e)), + cd::Segment::Cubic(a, b, e) => bp.curve_to(pt(a), pt(b), pt(e)), + } + } + if s.closed { + bp.close_path(); + } + } + bp +} + +/// A rectangle from the origin to (`w`, `h`) with `radii` counterclockwise from its corner at +/// (`w`, 0), placed by `m`, as a live rectangle: each radius stays on the corner it belongs to, +/// whichever way `w` and `h` point. +fn live_rect(w: f64, h: f64, radii: [f64; 4], m: Affine) -> Option<(PathData, Option)> { + if !(w.is_finite() && h.is_finite()) { + return None; + } + let (x0, y1, ww, hh) = (w.min(0.0), h.max(0.0), w.abs(), h.abs()); + // The live shape's own space has its origin at the top-left and y pointing down. + let to_file = Affine::translate((x0, y1)) * Affine::FLIP_Y; + let corners = [(w, 0.0), (w, h), (0.0, h), (0.0, 0.0)]; + let mut live_radii = [0.0; 4]; + for ((px, py), r) in corners.into_iter().zip(radii) { + let (lx, ly) = (px - x0, y1 - py); + let right = lx > ww / 2.0; + let bottom = ly > hh / 2.0; + let i = match (right, bottom) { + (false, false) => 0, + (true, false) => 1, + (true, true) => 2, + (false, true) => 3, + }; + if let Some(slot) = live_radii.get_mut(i) { + *slot = if r.is_finite() { r.max(0.0) } else { 0.0 }; + } + } + let mut live = LiveShape::Rectangle { w: ww, h: hh, radii: live_radii, kinds: Default::default(), radii_relative: false, xf: m * to_file }; + live.fold_scale(); + Some((live.to_path(), Some(live))) +} + +/// Whether every control point of `path` is finite and within `MAX_COORD` of the origin. +fn in_range(path: &PathData) -> bool { + path.control_bounds().is_some_and(|r| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite() && v.abs() <= crate::MAX_COORD)) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A named spot color takes its full-strength color from its use at the highest tint, wherever + /// that use comes in the drawing: a use at 0% stores only white. + #[test] + fn a_spot_color_keeps_its_color_from_its_strongest_use() { + let red = [1.0, 0.0, 0.0]; + let shape = |tint: f32, look: [f32; 3]| { + cd::Object::Shape(Box::new(cd::Shape::new( + Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, + cd::Matrix::IDENTITY, + Some(cd::Color::Spot { name: "Red ink".into(), tint, look: Some(look) }), + None, + ))) + }; + for objects in [vec![shape(0.0, [1.0; 3]), shape(1.0, red)], vec![shape(1.0, red), shape(0.0, [1.0; 3])]] { + let layer = cd::Layer { name: "L".into(), kind: cd::LayerKind::Drawing, flags: cd::Flags::default(), objects, guides: vec![] }; + let d = cd::Drawing { + version: 1300, + page_size: None, + pages: vec![cd::Page { size: None, layers: vec![layer] }], + master: vec![], + guides: vec![], + warnings: vec![], + }; + let doc = Builder::new().document(&d); + let swatch = doc.swatches.iter().find(|s| s.name == "Red ink").unwrap(); + assert_eq!(swatch.paint, Paint::solid(Color::rgb(1.0, 0.0, 0.0))); + let layer = doc.layers.first().unwrap().children().unwrap(); + let full = layer.iter().find_map(|n| match n.appearance.items.first() { + Some(AppearanceItem::Fill(f)) => match &f.paint { + Paint::Solid { color, tint, .. } if *tint == 1.0 => Some(*color), + _ => None, + }, + _ => None, + }); + assert_eq!(full, Some(Color::rgb(1.0, 0.0, 0.0))); + } + } + + /// A spot color named like one of a new document's process swatches gets a numbered name that + /// no other spot color of the drawing uses, and its paint names that spot swatch. + #[test] + fn a_spot_color_named_like_a_default_swatch_stays_a_spot_color() { + let shape = |name: &str| { + cd::Object::Shape(Box::new(cd::Shape::new( + Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, + cd::Matrix::IDENTITY, + Some(cd::Color::Spot { name: name.into(), tint: 1.0, look: Some([0.0; 3]) }), + None, + ))) + }; + let layer = cd::Layer { + name: "L".into(), + kind: cd::LayerKind::Drawing, + flags: cd::Flags::default(), + objects: vec![shape("Black"), shape("Black 2")], + guides: vec![], + }; + let d = cd::Drawing { + version: 1300, + page_size: None, + pages: vec![cd::Page { size: None, layers: vec![layer] }], + master: vec![], + guides: vec![], + warnings: vec![], + }; + assert!(Document::new(612.0, 792.0).swatches.iter().any(|s| s.name == "Black" && !s.spot)); + let doc = Builder::new().document(&d); + let layer = doc.layers.first().unwrap().children().unwrap(); + let mut names: Vec = layer + .iter() + .filter_map(|n| match n.appearance.items.first() { + Some(AppearanceItem::Fill(f)) => match &f.paint { + Paint::Solid { swatch: Some(name), .. } => Some(name.clone()), + _ => None, + }, + _ => None, + }) + .collect(); + names.sort(); + assert_eq!(names, ["Black 2", "Black 3"]); + for name in &names { + let swatch = doc.swatches.iter().find(|s| &s.name == name).unwrap(); + assert!(swatch.spot && swatch.global, "{name}: {swatch:?}"); + } + } + + /// Copies of master art onto the pages take from the budget by their objects, subpaths and + /// segments: a curve of 300 segments costs 302 each time it is copied. + #[test] + fn master_copies_count_their_path_segments() { + let segments = (1..=300).map(|i| cd::Segment::Line(cd::Pt { x: f64::from(i), y: 0.0 })).collect(); + let curve = cd::Object::Shape(Box::new(cd::Shape::new( + Geometry::Path(cd::Path { subpaths: vec![cd::SubPath { start: cd::Pt { x: 0.0, y: 0.0 }, segments, closed: false }] }), + cd::Matrix::IDENTITY, + None, + None, + ))); + let master = cd::Layer { name: "M".into(), kind: cd::LayerKind::Drawing, flags: cd::Flags::default(), objects: vec![curve], guides: vec![] }; + let d = cd::Drawing { + version: 1300, + page_size: None, + pages: (0..10).map(|_| cd::Page { size: None, layers: vec![] }).collect(), + master: vec![master], + guides: vec![], + warnings: vec![], + }; + let mut b = Builder::new(); + b.copies_left = 1000; + let doc = b.document(&d); + let copies = doc.layers.first().and_then(|l| l.children()).map_or(0, |c| c.len()); + assert_eq!(copies, 3, "1,000 holds three copies of 302"); + assert!(b.notes.contains(&Warning::TooDeep)); + } + + /// Copies of master art take from the budget by the dashes of their outlines too: a rectangle + /// whose outline has 299 dashes costs 300 each time it is copied. + #[test] + fn master_copies_count_their_dashes() { + let outline = cd::Outline { + width: 1.0, + color: cd::Color::Gray(1.0), + cap: cd::Cap::Butt, + join: cd::Join::Miter, + dashes: vec![1.0; 299], + behind_fill: false, + scale_with: false, + }; + let rect = cd::Object::Shape(Box::new(cd::Shape::new( + Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, + cd::Matrix::IDENTITY, + None, + Some(outline), + ))); + let master = cd::Layer { name: "M".into(), kind: cd::LayerKind::Drawing, flags: cd::Flags::default(), objects: vec![rect], guides: vec![] }; + let d = cd::Drawing { + version: 1300, + page_size: None, + pages: (0..10).map(|_| cd::Page { size: None, layers: vec![] }).collect(), + master: vec![master], + guides: vec![], + warnings: vec![], + }; + let mut b = Builder::new(); + b.copies_left = 1000; + let doc = b.document(&d); + let copies = doc.layers.first().and_then(|l| l.children()).map_or(0, |c| c.len()); + assert_eq!(copies, 3, "1,000 holds three copies of 300"); + assert!(b.notes.contains(&Warning::TooDeep)); + } + + /// An outline scaled with the shape takes the square root of the matrix's area factor on its + /// width and dashes; another outline keeps its stored width under the same matrix. + #[test] + fn outlines_scaled_with_the_shape_scale_their_width_and_dashes() { + // A matrix that scales by 2 and 8 and skews: area factor 2 * 8 - 3 * 0 = 16, mean scale 4. + let matrix = cd::Matrix([2.0, 0.0, 3.0, 8.0, 5.0, 5.0]); + for (scale_with, width, dashes) in [(true, 6.0, [12.0, 6.0]), (false, 1.5, [3.0, 1.5])] { + let outline = cd::Outline { + width: 1.5, + color: cd::Color::Gray(1.0), + cap: cd::Cap::Butt, + join: cd::Join::Miter, + dashes: vec![2.0, 1.0], + behind_fill: false, + scale_with, + }; + let rect = cd::Shape::new(Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, matrix, None, Some(outline)); + let mut b = Builder::new(); + let Some(node) = b.shape(&rect, Affine::IDENTITY, false) else { panic!("{scale_with}: no shape") }; + let [AppearanceItem::Stroke(s)] = node.appearance.items.as_slice() else { panic!("{scale_with}: {:?}", node.appearance.items) }; + assert!((s.width - width).abs() < 1e-9, "{scale_with}: {}", s.width); + let pattern = s.dash.as_ref().map(|d| d.pattern.clone()); + assert_eq!(pattern, Some(dashes.to_vec()), "{scale_with}"); + } + } + + /// A shape's opacity, blend mode and fill rule reach its path; a shape without them is opaque, + /// normal and filled even-odd. + #[test] + fn opacity_blend_and_fill_rule_reach_the_path() { + let square = Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }; + let plain = cd::Shape::new(square.clone(), cd::Matrix::IDENTITY, Some(cd::Color::Gray(1.0)), None); + let seen = cd::Shape { nonzero: true, opacity: 0.25, blend: cd::Blend::Multiply, ..plain.clone() }; + let mut b = Builder::new(); + for (s, opacity, blend, nonzero) in [(&plain, 1.0, BlendMode::Normal, false), (&seen, 0.25, BlendMode::Multiply, true)] { + let Some(n) = b.shape(s, Affine::IDENTITY, false) else { panic!("no shape") }; + let NodeKind::Path { rule, .. } = &n.kind else { panic!("{:?}", n.kind) }; + assert_eq!((n.opacity, n.blend, *rule == FillRule::NonZero), (opacity, blend, nonzero)); + } + let wild = cd::Shape { opacity: f32::NAN, ..plain }; + assert_eq!(b.shape(&wild, Affine::IDENTITY, false).map(|n| n.opacity), Some(1.0)); + } + + /// Ruler guides go on the top shown layer, or on a layer of their own when every layer is + /// hidden; hidden guidelines go on a hidden layer of their own. + #[test] + fn ruler_guides_stay_off_hidden_layers() { + let square = || cd::Shape::new(Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, cd::Matrix::IDENTITY, None, None); + let hidden = cd::Flags { hidden: true, locked: false }; + let layer = |name: &str, flags: cd::Flags| cd::Layer { + name: name.into(), + kind: cd::LayerKind::Drawing, + flags, + objects: vec![cd::Object::Shape(Box::new(square()))], + guides: vec![], + }; + let guides_of = |layers: Vec, hidden: bool| { + let d = cd::Drawing { + version: 1300, + page_size: None, + pages: vec![cd::Page { size: None, layers }], + master: vec![], + guides: vec![cd::Guideline { at: cd::Pt { x: 0.0, y: 0.0 }, angle: 90.0, hidden }], + warnings: vec![], + }; + let doc = Builder::new().document(&d); + doc.layers + .iter() + .map(|l| { + let n = l.children().map_or(0, |k| k.iter().filter(|n| matches!(n.kind, NodeKind::RulerGuide { .. })).count()); + (l.name.clone().unwrap_or_default(), l.visible, n) + }) + .collect::>() + }; + // Front to back: "Top" hidden over "Base" shown. + let got = guides_of(vec![layer("Top", hidden), layer("Base", cd::Flags::default())], false); + assert_eq!(got, [("Base".to_string(), true, 1), ("Top".to_string(), false, 0)]); + let got = guides_of(vec![layer("Only", hidden)], false); + assert_eq!(got, [("Only".to_string(), false, 0), ("Guides".to_string(), true, 1)]); + let got = guides_of(vec![layer("Base", cd::Flags::default())], true); + assert_eq!(got, [("Base".to_string(), true, 0), ("Hidden guides".to_string(), false, 1)]); + // At the layer limit an angled guideline's path goes on the top shown layer. + let mut layers: Vec = (0..super::super::MAX_LAYERS).map(|i| layer(&format!("L{i}"), cd::Flags::default())).collect(); + layers[0].flags = hidden; + let d = cd::Drawing { + version: 1300, + page_size: None, + pages: vec![cd::Page { size: None, layers }], + master: vec![], + guides: vec![cd::Guideline { at: cd::Pt { x: 0.0, y: 0.0 }, angle: 45.0, hidden: false }], + warnings: vec![], + }; + let mut b = Builder::new(); + let doc = b.document(&d); + let with_path: Vec<(bool, bool)> = doc + .layers + .iter() + .rev() + .take(2) + .map(|l| (l.visible, l.children().is_some_and(|k| k.iter().any(|n| matches!(n.kind, NodeKind::Path { guide: true, .. }))))) + .collect(); + assert_eq!(with_path, [(false, false), (true, true)]); + assert!(!b.notes.contains(&Warning::TooDeep)); + // With every layer hidden as well, the guides go on the top layer with the limit warning. + let mut d = d; + for l in &mut d.pages[0].layers { + l.flags = hidden; + } + d.guides.push(cd::Guideline { at: cd::Pt { x: 0.0, y: 0.0 }, angle: 90.0, hidden: false }); + let mut b = Builder::new(); + let doc = b.document(&d); + assert!(doc.layers.iter().all(|l| !l.visible)); + assert!(b.notes.contains(&Warning::TooDeep), "{:?}", b.notes); + } + + /// A see-through container whose outline is behind its fill knocks the outline out under its + /// fill, and its clipping group keeps its own objects combining as usual; an opaque one leaves + /// the pair a plain group. + #[test] + fn a_see_through_container_with_its_outline_behind_knocks_it_out() { + let outline = cd::Outline { + width: 4.0, + color: cd::Color::Gray(1.0), + cap: cd::Cap::Butt, + join: cd::Join::Miter, + dashes: vec![], + behind_fill: true, + scale_with: false, + }; + let square = || cd::Shape::new(Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, cd::Matrix::IDENTITY, Some(cd::Color::Gray(0.5)), None); + for (opacity, knockout, inner) in [(1.0, Knockout::Neutral, Knockout::Neutral), (0.5, Knockout::On, Knockout::Off)] { + let container = Box::new(cd::Shape { opacity, outline: Some(outline.clone()), ..square() }); + let clip = cd::Object::Clip { container, objects: vec![cd::Object::Shape(Box::new(square()))] }; + let nodes = Builder::new().objects(&[clip], Affine::IDENTITY); + let [pair] = nodes.as_slice() else { panic!("{nodes:?}") }; + let NodeKind::Group { children, clip: false } = &pair.kind else { panic!("{:?}", pair.kind) }; + assert_eq!(pair.knockout, knockout, "{opacity}"); + let clipping = children.iter().find(|n| matches!(n.kind, NodeKind::Group { clip: true, .. })); + assert_eq!(clipping.map(|n| n.knockout), Some(inner), "{opacity}"); + } + } + + /// A hidden or locked shape, group or clipping container gives its node those states. A layer + /// is hidden or locked when every drawing layer merged into it is; otherwise only the art of + /// the hidden or locked drawing layer is. + #[test] + fn hidden_and_locked_flags_reach_the_nodes() { + let square = || cd::Shape::new(Geometry::Rect { w: 10.0, h: 10.0, radii: [0.0; 4] }, cd::Matrix::IDENTITY, Some(cd::Color::Gray(1.0)), None); + let hidden = cd::Flags { hidden: true, locked: false }; + let locked = cd::Flags { hidden: false, locked: true }; + let objects = vec![ + cd::Object::Shape(Box::new(cd::Shape { flags: hidden, ..square() })), + cd::Object::Group { objects: vec![cd::Object::Shape(Box::new(square()))], flags: locked }, + cd::Object::Clip { container: Box::new(cd::Shape { flags: hidden, ..square() }), objects: vec![cd::Object::Shape(Box::new(square()))] }, + ]; + let layer = + |flags: cd::Flags, objects: Vec| cd::Layer { name: "L".into(), kind: cd::LayerKind::Drawing, flags, objects, guides: vec![] }; + let drawing = |pages: Vec>| cd::Drawing { + version: 1300, + page_size: None, + pages: pages.into_iter().map(|layers| cd::Page { size: None, layers }).collect(), + master: vec![], + guides: vec![], + warnings: vec![], + }; + let doc = Builder::new().document(&drawing(vec![vec![layer(cd::Flags::default(), objects)]])); + let kids = doc.layers[0].children().unwrap(); + // Bottom to top: the clipping group, the group, the shape. + let states: Vec<(bool, bool)> = kids.iter().map(|n| (n.visible, n.locked)).collect(); + assert_eq!(states, [(false, false), (true, true), (false, false)]); + assert!(doc.layers[0].visible && !doc.layers[0].locked); + // One name on two pages: hidden on the first only, then on both. + let one = || vec![cd::Object::Shape(Box::new(square()))]; + let doc = Builder::new().document(&drawing(vec![vec![layer(hidden, one())], vec![layer(cd::Flags::default(), one())]])); + assert_eq!(doc.layers.len(), 1); + assert!(doc.layers[0].visible); + let states: Vec = doc.layers[0].children().unwrap().iter().map(|n| n.visible).collect(); + assert_eq!(states, [false, true]); + let doc = Builder::new().document(&drawing(vec![vec![layer(cd::Flags { hidden: true, locked: true }, one())], vec![layer(hidden, one())]])); + assert!(!doc.layers[0].visible && !doc.layers[0].locked); + let states: Vec<(bool, bool)> = doc.layers[0].children().unwrap().iter().map(|n| (n.visible, n.locked)).collect(); + assert_eq!(states, [(true, true), (true, false)]); + } + + /// A corner rounded in the file stays on the same corner of the page, however the rectangle's + /// size points. + #[test] + fn rectangle_radii_stay_on_their_corners() { + // Only the corner at (w, 0) rounded; the page flips y as the document does. + for (w, h) in [(100.0, 50.0), (-100.0, 50.0), (100.0, -50.0), (-100.0, -50.0)] { + let (path, _) = live_rect(w, h, [10.0, 0.0, 0.0, 0.0], Affine::FLIP_Y).unwrap(); + let rounded = Point::new(w, -0.0); + let bp = path.to_bezpath(); + // No anchor sits on the rounded corner itself; the other three corners are anchors. + let anchors: Vec = bp.elements().iter().filter_map(|e| e.end_point()).collect(); + assert!(!anchors.iter().any(|p| (*p - rounded).hypot() < 1e-6), "{w} {h}: {anchors:?}"); + for c in [Point::new(w, -h), Point::new(0.0, -h), Point::new(0.0, 0.0)] { + assert!(anchors.iter().any(|p| (*p - c).hypot() < 1e-6), "{w} {h}: {c:?} not in {anchors:?}"); + } + } + } +} diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 0969adb5a2..a41831b200 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec { "Open Document", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", + "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignProfile?: a profile of that model) (default: what the model's policy of edit.colorSettings does; a choice for the other case, or for a document tagged with the working space, is not used; the reply's profileChoice gives {issue: mismatch|missing, model, choice} when one was given for the document's question: it names the choice, not what it did, so \"convert\" from a profile that is not available keeps the profile and a warning says the colors were not converted; the desktop app asks for it when edit.colorSettings' askMismatchOpen or askMissingOpen is on, document.open never asks), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, profileChoice?, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", always, load::open ), diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 8b5cd9fe6f..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, diff --git a/crates/engine/src/cmd/fileio/formats.rs b/crates/engine/src/cmd/fileio/formats.rs index 2cc57144fb..3b520d5635 100644 --- a/crates/engine/src/cmd/fileio/formats.rs +++ b/crates/engine/src/cmd/fileio/formats.rs @@ -532,6 +532,14 @@ pub const FORMATS: &[Format] = &[ reader("heif", "HEIC/HEIF", &["heic", "heif"], "image/heic", true), // jxl-oxide reads a JPEG XL file's first frame, which is stored as PNG. Exports don't write it. reader("jxl", "JPEG XL", &["jxl"], "image/jxl", true), + // `.cdr` drawings of versions 1 to 27 (`WL` files, RIFF files from version 3, and the ZIP packages of 14 on), read by + // `vectorcraft-cdr`; a `.cdt` template opens as a new untitled document. Exports don't write + // them. + reader("cdr", "CDR Drawing", &["cdr"], "application/vnd.corel-draw", false), // brand-ok: shared MIME type + reader("cdt", "CDR Template", &["cdt"], "application/vnd.corel-draw", false), // brand-ok: shared MIME type + // `.cmx` exchange files with 32-bit coordinates, read by `vectorcraft-cdr`; exports don't write + // them. + reader("cmx", "CMX", &["cmx"], "image/x-cmx", false), // QuickDraw pictures, read by `vectorcraft_metafile::import_pict` into paths, type and images. reader("pict", "PICT", &["pct", "pic", "pict"], "image/x-pict", false), ]; @@ -591,17 +599,20 @@ pub const OPEN_EXTS: &[&str] = &[ "af", "afdesign", "afpub", + "cdr", + "cdt", + "cmx", ]; /// Extensions in [`OPEN_EXTS`] the packaging declares no type for: Photoshop documents belong to /// raster editors, so Finder and file managers don't offer a vector app for them, and there is no -/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF or JPEG XL type, nor one for the `.pns`, `.dib` and `.rle` names of +/// `.epsf`, `.ps`, Targa, PCX, Pixar, JPEG 2000, HEIC/HEIF, JPEG XL, `.cdr` or `.cmx` type, nor one for the `.pns`, `.dib` and `.rle` names of /// PNG and BMP files (File › Open and Place still read them all). On Linux the desktop entry's EPS /// type (shared-mime-info's) also covers `.epsf`, so file managers offer VectorCraft for it. /// The packaging declares no type for HP-GL plot files or PICT pictures either. pub const UNASSOCIATED_EXTS: &[&str] = &[ "psd", "pdd", "psb", "epsf", "ps", "pns", "dib", "rle", "tga", "vda", "icb", "vst", "pcx", "pxr", "jpf", "jpx", "jp2", "j2k", "j2c", "jpc", - "heic", "heif", "jxl", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", + "heic", "heif", "jxl", "cdr", "cdt", "cmx", "plt", "hpgl", "hgl", "hpg", "pct", "pic", "pict", ]; /// The extension that picks each writable format when exporting (the format's first; PNG-8 shares @@ -688,6 +699,9 @@ pub const PLACE_EXTS: &[&str] = &[ "af", "afdesign", "afpub", + "cdr", + "cdt", + "cmx", "txt", "rtf", "docx", 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..cedda4844a 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -92,6 +92,13 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<&'static Format> { if vectorcraft_affinity::is_affinity(bytes) { return format("affinity"); } + if super::cdr::is_cdr(bytes) { + // A template keeps its meaning from the extension. + return by_name.filter(|f| f.id == "cdt").or_else(|| format("cdr")); + } + if super::cdr::is_cmx(bytes) { + return format("cmx"); + } if vectorcraft_format::sniff(bytes) { // A template keeps its meaning from the extension, like .ait. return by_name.filter(|f| f.id == "template").or_else(|| format("vectorcraft")); @@ -541,6 +548,14 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result preview_only = i.preview_only; (i.doc, i.warnings, false) } + "cdr" | "cdt" => { + let (doc, warnings) = super::cdr::import(bytes)?; + (doc, warnings, false) + } + "cmx" => { + let (doc, warnings) = super::cdr::import_cmx(bytes)?; + (doc, warnings, false) + } // A PSD or PSB file's layers become layers (`layers`, default on); without layers, or with // `layers: false`, its merged image opens. Layers that can't be read leave the merged image. "psd" | "psb" if opts.layers => match super::psdlayers::import_active(bytes, opts.hidden_layers) { @@ -686,6 +701,29 @@ pub struct ReadFile { links: Resolved, /// Whether the color management policies changed the document ([`apply_policies`]). policy_changed: bool, + /// The answer to the document's profile question (`profileChoice`, or the app's prompt). + choice: Option, + /// What opening still has to do while the app asks about the profile ([`ReadFile::question`]): + /// the policies, the color mode, the linked files and the type are left for + /// [`ReadFile::answer`] or [`open_read`]. + rest: Option, + /// The answer that was used and the question it answered (`document.open`'s `profileChoice` + /// reply). + answered: Option, + /// The profile question as it was last asked ([`ReadFile::ask`]): an answer is taken only while + /// the question is still the same. + asked: Option, + /// Update Links and the low-resolution EPS proxy setting, while the linked files and the type + /// are left to do after the answer ([`ReadFile::finish_read`]). + links_left: Option<(bool, bool)>, +} + +/// The part of [`read_for_open`] a file waiting for a profile answer has left to do. +struct Rest { + update_links: bool, + low_res_proxy_eps: bool, + /// The color mode `colorMode` asks for, converted after the policies. + color_mode: Option, } /// Edit › Color Settings: the color management policies keep, take off or convert from the @@ -714,36 +752,145 @@ impl ReadFile { /// reads (`importer` in `p`, or an extension only an importer lists) is read by it /// ([`super::importer`]). pub fn read_for_open(name: &str, bytes: &[u8], path: Option, p: &Value, update_links: bool, low_res_proxy_eps: bool) -> Result { + read_for_open_asking(name, bytes, path, p, update_links, low_res_proxy_eps, false) +} + +/// [`read_for_open`]; with `ask` (the desktop app's File › Open), a document whose profile +/// question ([`ReadFile::question`]) Edit › Color Settings asks, and that `p` gives no +/// `profileChoice` for, stops after it is decoded: the app asks, and [`ReadFile::answer`] (or +/// [`open_read`], with the policy's choice) does the rest. +pub fn read_for_open_asking( + name: &str, + bytes: &[u8], + path: Option, + p: &Value, + update_links: bool, + low_res_proxy_eps: bool, + ask: bool, +) -> Result { let opts = LoadOptions::from_params("document.open", p)?; - let (mut loaded, policy_changed) = if opts.link_pages { - let mut loaded = linked_pages(name, bytes, path.as_deref(), &opts)?; - let changed = apply_policies(&mut loaded); - (loaded, changed) + let choice = crate::cmd::colormgmt::ProfileChoice::param(p, "document.open")?; + let (loaded, color_mode) = if opts.link_pages { + (linked_pages(name, bytes, path.as_deref(), &opts)?, None) } else { match super::importer::pick(name, bytes, p)? { - Some(plugin) => { - let mut loaded = super::importer::load(name, bytes, &plugin, p)?; - let changed = apply_policies(&mut loaded); - (loaded, changed) - } - None => { - // The color mode `p` asks for converts the colors after the policies did, through - // the profiles the document keeps. - let mut loaded = load_with(name, bytes, &LoadOptions { color_mode: None, ..opts.clone() })?; - let changed = apply_policies(&mut loaded); - if let Some(mode) = opts.color_mode.filter(|m| *m != loaded.doc.color_mode) { - let doc = &mut loaded.doc; - vectorcraft_color::cms::with_active(super::super::colormgmt::doc_cms(doc), || { - super::super::colormgmt::set_color_mode(doc, mode, true, None, opts.grays); - }); - } - (loaded, changed) - } + Some(plugin) => (super::importer::load(name, bytes, &plugin, p)?, None), + // The color mode `p` asks for converts the colors after the policies did, through the + // profiles the document keeps. + None => (load_with(name, bytes, &LoadOptions { color_mode: None, ..opts.clone() })?, opts.color_mode), } }; - let links = crate::cmd::links::resolve(&mut loaded.doc, crate::cmd::links::LinkBase::file(path.as_deref()), update_links, low_res_proxy_eps); - Session::refresh_text_bounds(&mut loaded.doc); - Ok(ReadFile { loaded, opts, path, links, policy_changed }) + let mut file = ReadFile { + loaded, + opts, + path, + links: Resolved::default(), + policy_changed: false, + choice, + rest: Some(Rest { update_links, low_res_proxy_eps, color_mode }), + answered: None, + asked: None, + links_left: None, + }; + if ask && file.choice.is_none() && file.ask().is_some() { + return Ok(file); + } + file.finish_read()?; + Ok(file) +} + +impl ReadFile { + /// The file's name, for a prompt. + pub fn name(&self) -> String { + self.path.as_deref().map(file_name).unwrap_or_else(|| self.loaded.doc.title.clone()) + } + + /// The profile question Edit › Color Settings asks about this file before it opens (its Ask + /// When Opening box of that kind is on), while the file waits for the answer + /// ([`read_for_open_asking`]); none once it is answered or read through. + pub fn question(&self) -> Option { + self.rest.as_ref()?; + let st = vectorcraft_color::cms::working_settings(); + crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &st).filter(|q| q.asked(&st)) + } + + /// [`Self::question`], kept as the question asked: [`Self::answer`] takes an answer only while + /// the question is still the same. The app calls it when it shows the question. + pub fn ask(&mut self) -> Option { + self.asked = self.question(); + self.asked.clone() + } + + /// Answer the profile question with `choice` and apply it: the policies (the answer in place of + /// the one of the document's color mode) and the color mode. The linked files and the type are + /// left for [`Self::finish_read`] or [`open_read`]. An error leaves the file waiting: a profile + /// to assign that is not one of that model, or Color Settings changed since the question was + /// asked ([`Self::ask`]) so that the question, its model, the profile it is about or the working + /// space differ. + pub fn answer(&mut self, choice: crate::cmd::colormgmt::ProfileChoice) -> Result<()> { + if let Some(asked) = &self.asked + && self.rest.is_some() + { + let now = crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &vectorcraft_color::cms::working_settings()); + let key = |q: &crate::cmd::colormgmt::ProfileQuestion| (q.issue, q.model, q.profile.clone(), q.working.clone()); + if now.as_ref().map(key) != Some(key(asked)) { + return Err(bad("document.open", "the profile question changed since it was asked: answer the question it asks now")); + } + } + let before = self.choice.replace(choice); + let r = self.apply_answer(); + if r.is_err() { + self.choice = before; + } + r + } + + /// The rest of [`read_for_open_asking`], once: the color management policies with the profile + /// answer (or as the policy says without one), the color mode `colorMode` asks for, the linked + /// files and the type. The app runs it off the UI thread once the question is answered. + pub fn finish_read(&mut self) -> Result<()> { + self.apply_answer()?; + self.finish_links(); + Ok(()) + } + + /// Read the linked files and lay out the type of a file whose profile answer is applied + /// ([`Self::answer`]), once. A file still waiting for its answer is left as it is. + fn finish_links(&mut self) { + let Some((update_links, low_res_proxy_eps)) = self.links_left.take() else { return }; + let base = crate::cmd::links::LinkBase::file(self.path.as_deref()); + self.links = crate::cmd::links::resolve(&mut self.loaded.doc, base, update_links, low_res_proxy_eps); + Session::refresh_text_bounds(&mut self.loaded.doc); + } + + /// The policies with the profile answer and the color mode `colorMode` asks for, once; the + /// linked files and the type are left for [`Self::finish_read`]. + fn apply_answer(&mut self) -> Result<()> { + if self.rest.is_none() { + return Ok(()); + } + // The question the answer was given to, for the reply's `profileChoice`. + let question = crate::cmd::colormgmt::ProfileQuestion::of(&self.loaded.doc, &vectorcraft_color::cms::working_settings()); + let answered = match (&self.choice, &question) { + (Some(c), Some(q)) if c.issue() == q.issue => Some(json!({ "issue": q.issue.id(), "model": q.to_json()["model"], "choice": c.id() })), + _ => None, + }; + // A failure leaves the file waiting, unchanged. + let (notes, changed) = crate::cmd::colormgmt::apply_open_policies_choosing(&mut self.loaded.doc, self.choice.as_ref())?; + let Some(rest) = self.rest.take() else { return Ok(()) }; + self.answered = answered; + self.loaded.warnings.extend(notes); + self.policy_changed = changed; + if let Some(mode) = rest.color_mode.filter(|m| *m != self.loaded.doc.color_mode) { + let doc = &mut self.loaded.doc; + let grays = self.opts.grays; + vectorcraft_color::cms::with_active(super::super::colormgmt::doc_cms(doc), || { + super::super::colormgmt::set_color_mode(doc, mode, true, None, grays); + }); + } + self.links_left = Some((rest.update_links, rest.low_res_proxy_eps)); + Ok(()) + } } /// The PDF `name` (`bytes`, read from `path`) opened with `linkPages`: its pages as placed documents @@ -757,8 +904,15 @@ fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, opts: &LoadOptions /// The second half of [`open_bytes_with`]: open a file [`read_for_open`] read as the new active /// document → `document.open`'s result. -pub fn open_read(s: &mut Session, file: ReadFile) -> Result { - open_loaded(s, file.loaded, file.links, file.path, &file.opts, false, file.policy_changed) +/// A file still waiting for its profile answer ([`ReadFile::question`]) opens as its policy says. +pub fn open_read(s: &mut Session, mut file: ReadFile) -> Result { + file.finish_read()?; + let answered = file.answered.take(); + let mut r = open_loaded(s, file.loaded, file.links, file.path, &file.opts, false, file.policy_changed)?; + if let Some(a) = answered { + r["profileChoice"] = a; + } + Ok(r) } /// File → New from Template: any readable file (at `path`, if it is one: its links are looked for @@ -791,11 +945,13 @@ fn open_loaded( let Loaded { mut doc, format, warnings, restored, converted, native_pdf_compatible, .. } = loaded.with_grid_prefs(&s.prefs).with_unit_prefs(&s.prefs); // EPS now has an ordinary Save path. Its preview, partial-program and damaged-editing - // fallbacks must ask before overwriting the richer source they could not fully read. + // fallbacks must ask before overwriting the richer source they could not fully read. Every + // warning of a `.cdr` drawing or a `.cmx` file names content the import left out or changed. let losses: Vec = warnings .iter() .filter(|w| { is_loss(w) + || matches!(format.id, "cdr" | "cdt" | "cmx") || (format.id == "eps" && (matches!(w.as_str(), EDITING_DAMAGED | EDITING_STALE) || w.starts_with("this file's PostScript couldn't be read") @@ -804,9 +960,9 @@ fn open_loaded( .cloned() .collect(); let source_path = path.clone().filter(|_| !losses.is_empty()); - // A template (saved by Save as Template, or an .ait/.vctemplate file) opens as a new untitled - // document. - let template = as_template || doc.template || matches!(format.id, "ait" | "template"); + // A template (saved by Save as Template, or an .ait, .vctemplate or .cdt file) opens as a new + // untitled document. + let template = as_template || doc.template || matches!(format.id, "ait" | "template" | "cdt"); if template { doc.template = false; doc.title = s.next_untitled(); @@ -962,7 +1118,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 +1296,15 @@ pub fn texture_image(bytes: &[u8]) -> Result { texture.and_then(|t| t.to_stored()).ok_or_else(|| err("the image can't be read as a texture")) } -/// An image's encoded `bytes`, `width` × `height` pixels, ready to embed. +/// An image's encoded `bytes`, `width` × `height` pixels, ready to embed, with the clipping path a +/// PNG or TIFF made from a PSD or PSB file keeps ([`image_clip`]). fn stored(bytes: Vec, mime: &'static str, (width, height): (u32, u32), ppi: Option<(f64, f64)>) -> Result { if width == 0 || height == 0 { return Err(err("the image is empty")); } let blob = ImageBlob::new(mime, bytes); - Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip: None }) + let clip = image_clip(&blob).map(|path| (path, vectorcraft_geom::FillRule::EvenOdd)); + Ok(RasterImage { key: blob.content_key(), blob, width, height, ppi, clip }) } /// The keyword of the PNG text chunk holding the clipping path of the file a PNG was made from diff --git a/crates/engine/src/cmd/fileio/metafile.rs b/crates/engine/src/cmd/fileio/metafile.rs index e9e1e882a7..3012f7c238 100644 --- a/crates/engine/src/cmd/fileio/metafile.rs +++ b/crates/engine/src/cmd/fileio/metafile.rs @@ -19,6 +19,18 @@ pub(super) const OPTIONS: &[FormatOption] = &[super::ARTBOARD, super::ARTBOARDS, /// Encode `doc` as `kind`: the chosen artboard (default the first), or with `use_artboards` one /// picture per chosen artboard (default all). pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option, kind: Kind) -> Result { + encode_flattening(doc, p, use_artboards, kind, crate::flatten_raster_effects) +} + +/// [`encode`] with `flatten` turning raster effects into images. The chosen artboards are checked +/// first, so an export that is refused does not call `flatten`. +pub(super) fn encode_flattening( + doc: &Document, + p: &Value, + use_artboards: Option, + kind: Kind, + flatten: impl FnOnce(&Document) -> Option, +) -> Result { let f = super::format(kind.id()).ok_or_else(|| bad(C, "no metafile format"))?; let pick: ArtboardPick = super::encode::options(f, p)?; let n = doc.artboards.len(); @@ -26,12 +38,16 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option, kin Some(true) => pick.resolve(n).map_err(|e| bad(C, e))?.unwrap_or_else(|| (0..n).collect()), _ => vec![pick.one(n).map_err(|e| bad(C, e))?], }; + if boards.is_empty() { + return Err(bad(C, "the document has no artboard")); + } let rects = boards .iter() .map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))) .collect::>>()?; + vectorcraft_metafile::check_regions(&rects).map_err(|e| bad(C, e))?; // Raster effects (shadows, glows, blurs) as images, as PDF export does. - let flat = crate::flatten_raster_effects(doc); + let flat = flatten(doc); let src = flat.as_ref().unwrap_or(doc); let outs = vectorcraft_metafile::export_regions(src, &rects, kind).map_err(|e| bad(C, e))?; let mut enc = Encoded::default(); diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index daa20ac2b0..c0bb942150 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -69,7 +69,7 @@ pub(crate) const OPTIONS: &[FormatOption] = &[ name: "bleed", ty: "object", default: "null", - description: "{useDocument, top, bottom, left, right} in points: the page grows by the bleed (BleedBox) around its artboard (TrimBox); a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning", + description: "{useDocument, top, bottom, left, right} in points: the page grows by the bleed (BleedBox) around its artboard (TrimBox); a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so do objects that reach the trim edge on a side with a bleed but stop short of the bleed edge", }, FormatOption { name: "output", @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says, but in pdfX3 and pdfX4 CMYK colors in the profile of a CMYK output intent are DeviceCMYK, and with none and a CMYK output intent pdfX3 and pdfX4 write every CMYK color as DeviceCMYK, unless colors are converted to a CMYK destination of another profile; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a, nor when CMYK colors are DeviceCMYK and either its profile is the output intent's or profiles is none), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says, but in pdfX3 and pdfX4 CMYK colors in the profile of a CMYK output intent are DeviceCMYK, and with none and a CMYK output intent pdfX3 and pdfX4 write every CMYK color as DeviceCMYK, unless colors are converted to a CMYK destination of another profile; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a, nor when CMYK colors are DeviceCMYK and either its profile is the output intent's or profiles is none), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", has_doc, export_pdf ), @@ -295,6 +295,8 @@ pub(super) fn encode_art_page(cmd: &str, doc: &Document, p: &Value) -> Result Result, non_printing: bool) -> usize { + let bleed = bleed.map(|b| if b.is_finite() && b > EDGE_TOLERANCE { b } else { 0.0 }); + if bleed.iter().all(|b| *b == 0.0) { + return 0; + } + let trims: Vec = match artboards { + Some(picked) => picked.iter().filter_map(|&i| doc.artboards.get(i)).map(|a| a.rect).collect(), + None => doc.artboards.iter().map(|a| a.rect).collect(), + }; + let symbols = doc.symbol_boxes(); + let mut count = 0; + // Each object with the clipping path of the layers above it. + let mut stack: Vec<(&Node, Option)> = doc.layers.iter().map(|l| (&**l, None)).collect(); + while let Some((n, clip)) = stack.pop() { + if let NodeKind::Layer { template, printable, children, clip: clipping, .. } = &n.kind { + // An opacity mask decides what shows, so a masked layer's art is not measured. + if !n.visible || *template || !(*printable || non_printing) || n.opacity <= 0.0 || n.extras().mask.is_some() { + continue; + } + // A clipping layer's first child clips the others, and its fills and strokes are an + // object of their own. + let (inner, members) = if *clipping { + let Some(own) = clip_region(children, &symbols) else { continue }; + let inner = clip.map_or(own, |c| c.intersect(own)); + if let Some(first) = children.first() + && let Drawn::Bounds(b) = clip_paint_drawn(first, inner, &symbols) + { + let b = clip.map_or(b, |c| c.intersect(b)); + if b.area() > 0.0 && trims.iter().any(|t| stops_short(b, *t, bleed)) { + count += 1; + } + } + (Some(inner), children.get(1..).unwrap_or_default()) + } else { + (clip, &children[..]) + }; + stack.extend(members.iter().map(|c| (&**c, inner))); + continue; + } + let Drawn::Bounds(b) = drawn_bounds(n, &symbols) else { continue }; + let b = clip.map_or(b, |c| c.intersect(b)); + if b.area() > 0.0 && trims.iter().any(|t| stops_short(b, *t, bleed)) { + count += 1; + } + } + count +} + +/// What [`drawn_bounds`] finds an object draws. +enum Drawn { + /// Nothing: it is hidden, a guide, at 0% opacity, or a path that paints nothing. + Nothing, + /// Art within these bounds. + Bounds(vectorcraft_geom::Rect), + /// Art whose bounds aren't known, which is not measured: brush art paints past the visual + /// bounds by an amount they don't give, an opacity mask hides part of what they hold, and area + /// type and type on a path are bounded by their frame or path. + Unknown, +} + +/// Whether path or compound path `n` paints: one of its fills and strokes is visible, has a paint +/// and an opacity above 0 and, a stroke, a width above 0. Other objects count as painting. +fn paints(n: &Node) -> bool { + !matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) + || n.appearance.items.iter().any(|i| { + i.visible() && i.opacity() > 0.0 && !i.paint().is_none() && !matches!(i, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0) + }) +} + +/// What `n` draws on a page, by its visual bounds (strokes included): a group without a clipping +/// path by the members that draw, and a clip group by the part of them inside its clipping path +/// together with what the clipping path paints itself ([`clip_paint_drawn`]). +/// Hidden objects, guides, objects at 0% opacity and paths that paint nothing draw nothing. Art +/// with a brushed stroke that draws, in `n` or (outside groups) in the objects it holds, art with +/// an opacity mask, and area type and type on a path are [`Drawn::Unknown`]. +fn drawn_bounds(n: &Node, symbols: &vectorcraft_doc::SymbolBoxes) -> Drawn { + if !n.visible || n.is_guide() || n.opacity <= 0.0 || !paints(n) { + return Drawn::Nothing; + } + // An opacity mask decides what shows of the object, and the bounds of area type and type on a + // path are its frame or path, not its glyphs. + let frame_bounds = matches!(&n.kind, NodeKind::Text(t) if !matches!(t.kind, vectorcraft_doc::TextKind::Point)); + if vectorcraft_brush::reach(n) > 0.0 || n.extras().mask.is_some() || frame_bounds { + return Drawn::Unknown; + } + let members = |children: &[Arc]| { + let mut out = Some(None); + for c in children { + out = match (out, drawn_bounds(c, symbols)) { + (None, _) | (_, Drawn::Unknown) => None, + (Some(acc), Drawn::Bounds(b)) => Some(vectorcraft_geom::union_opt(acc, Some(b))), + (keep, Drawn::Nothing) => keep, + }; + } + out + }; + let measured = match &n.kind { + NodeKind::Group { clip: false, .. } => match members(n.editing_children()) { + Some(art) => art.and_then(|_| n.visual_of_members(std::iter::once(art))), + None => return Drawn::Unknown, + }, + NodeKind::Group { clip: true, children } => { + let Some(region) = clip_region(children, symbols) else { return Drawn::Nothing }; + let Some(art) = members(children.get(1..).unwrap_or_default()) else { return Drawn::Unknown }; + let art = art.map(|a| region.intersect(a)).filter(|b| b.area() > 0.0); + match children.first().map_or(Drawn::Nothing, |first| clip_paint_drawn(first, region, symbols)) { + Drawn::Unknown => return Drawn::Unknown, + Drawn::Bounds(b) => vectorcraft_geom::union_opt(art, Some(b)), + Drawn::Nothing => art, + } + } + _ if vectorcraft_brush::reach_within(n) > 0.0 => return Drawn::Unknown, + _ => n.visual_bounds_with(symbols), + }; + measured.map_or(Drawn::Nothing, Drawn::Bounds) +} + +/// The region the clipping path of a clip group or clipping layer with `children` clips to: its +/// geometric bounds, without its strokes. +fn clip_region(children: &[Arc], symbols: &vectorcraft_doc::SymbolBoxes) -> Option { + children.first()?.geometric_bounds_with(symbols) +} + +/// What clipping path `clip` paints itself ([`Node::clip_paint`]): its fills inside `region`, the +/// region it clips to, and its strokes over the clipped art, unclipped. +fn clip_paint_drawn(clip: &Node, region: vectorcraft_geom::Rect, symbols: &vectorcraft_doc::SymbolBoxes) -> Drawn { + let paint = clip.clip_paint(); + let mut out = None; + for (part, clipped) in [(paint.fill, true), (paint.stroke, false)] { + let Some(part) = part else { continue }; + match drawn_bounds(&part, symbols) { + Drawn::Unknown => return Drawn::Unknown, + Drawn::Nothing => {} + Drawn::Bounds(b) => { + let b = if clipped { region.intersect(b) } else { b }; + out = vectorcraft_geom::union_opt(out, Some(b).filter(|b| b.area() > 0.0)); + } + } + } + out.map_or(Drawn::Nothing, Drawn::Bounds) +} + +/// Whether bounds `b` reach the trim edge `t` (within [`EDGE_TOLERANCE`] on either side of it) on a +/// side where `bleed` (`[top, bottom, left, right]`) is above 0 and end before the bleed edge there. +/// Document space has y down. +fn stops_short(b: vectorcraft_geom::Rect, t: vectorcraft_geom::Rect, [top, bottom, left, right]: [f64; 4]) -> bool { + let tol = EDGE_TOLERANCE; + let across = b.x0 < t.x1 && b.x1 > t.x0; + let down = b.y0 < t.y1 && b.y1 > t.y0; + let reaches = |near: f64, far: f64, edge: f64| near <= edge + tol && far >= edge - tol; + (across && top > 0.0 && reaches(b.y0, b.y1, t.y0) && b.y0 > t.y0 - top + tol) + || (across && bottom > 0.0 && reaches(-b.y1, -b.y0, -t.y1) && b.y1 < t.y1 + bottom - tol) + || (down && left > 0.0 && reaches(b.x0, b.x1, t.x0) && b.x0 > t.x0 - left + tol) + || (down && right > 0.0 && reaches(-b.x1, -b.x0, -t.x1) && b.x1 < t.x1 + right - tol) +} + +/// The warning for `n` objects that [`short_of_bleed`] finds; `None` for none. +pub fn short_of_bleed_warning(n: usize) -> Option { + match n { + 0 => None, + 1 => Some(format!("1 object {SHORT_OF_BLEED_ONE}")), + _ => Some(format!("{n} objects {SHORT_OF_BLEED_OTHER}")), + } +} + +/// The end of [`short_of_bleed_warning`] for one object and for more. +const SHORT_OF_BLEED_ONE: &str = "reaches the trim edge but stops short of the bleed"; +const SHORT_OF_BLEED_OTHER: &str = "reach the trim edge but stop short of the bleed"; + +/// Whether `text` is a warning [`short_of_bleed_warning`] gives. +pub fn is_short_of_bleed(text: &str) -> bool { + text.ends_with(SHORT_OF_BLEED_ONE) || text.ends_with(SHORT_OF_BLEED_OTHER) +} + /// The end of the writer's warning for a page longer than 14,400 pt written with a `UserUnit` /// above 1. const SHOWN_SMALLER: &str = "so apps that ignore UserUnit show it that many times smaller"; @@ -340,7 +527,7 @@ pub(super) fn encode_at(cmd: &str, doc: &Document, p: &Value, modified: Option = placed.into_iter().map(Note::loss).collect(); // The editing data leaves out an Export for Screens folder outside the read roots. let native = || Ok(vectorcraft_format::save(&super::access::with_readable_settings_folder(doc), false)); - let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, native, || Ok(None))?; + let (bytes, drawn) = encode_carrying_at(cmd, &full, p, modified, true, native, || Ok(None))?; notes.extend(drawn); if notes.iter().any(|n| n.text.ends_with(SHOWN_SMALLER)) && options(cmd, &full, p)?.settings.standard == Standard::None { for n in notes.iter_mut().filter(|n| n.text.ends_with(SHOWN_SMALLER)) { @@ -364,7 +551,8 @@ fn overflow_warning(cmd: &str, doc: &Document, p: &Value) -> Result Result>, private: impl FnOnce() -> Result)>>, ) -> Result<(Vec, Vec)> { - encode_carrying_at(cmd, doc, p, None, native, private) + encode_carrying_at(cmd, doc, p, None, false, native, private) } /// [`encode_carrying`] modified at `modified` (Unix seconds) when given, instead of the time of -/// writing. +/// writing, warning about art that stops short of the bleed when `bleed_check` is true. fn encode_carrying_at( cmd: &str, doc: &Document, p: &Value, modified: Option, + bleed_check: bool, native: impl FnOnce() -> Result>, private: impl FnOnce() -> Result)>>, ) -> Result<(Vec, Vec)> { let mut opts = options_at(cmd, doc, p, modified.or_else(vectorcraft_doc::metadata::output_time))?; + // Measured before the pages' background colors join the art. Only art that prints counts: + // createLayers writes non-printing layers with /PrintState /OFF, so they count only with + // includeNonPrinting, which writes them as printing art. + let set = &opts.settings; + let short = if bleed_check { short_of_bleed(doc, set.bleed_of(doc), opts.artboards.as_deref(), set.include_non_printing) } else { 0 }; // The pages' background colors, behind the art (the editing data keeps them as colors). let pages = opts.artboards.clone().unwrap_or_else(|| (0..doc.artboards.len()).collect()); let filled = super::export::with_artboard_fills(doc, p, pages).map_err(|e| bad(cmd, e))?; @@ -401,6 +595,8 @@ fn encode_carrying_at( if opts.settings.leaves_out_bleed(doc) { notes.push(Note::loss(BLEED_LEFT_OUT)); } + // Art that reaches the trim edge but leaves part of the page's bleed empty. + notes.extend(short_of_bleed_warning(short).map(Note::loss)); if opts.settings.preserve_editing { if opts.artboards.as_ref().is_none_or(|v| v.iter().copied().eq(0..doc.artboards.len())) { opts.native = Some(native()?); @@ -440,8 +636,8 @@ pub const DEFAULT_FLATTENER: &str = "High Resolution"; /// `doc` with its transparency flattened for a PDF 1.3 file (asked for, or PDF/X-1a and PDF/X-3, /// whose files have none), with `flattenerPreset` (default High Resolution) and `p`'s `flattener` /// options over it; images with see-through pixels and colorized images, including those in -/// pattern tiles, count as transparency. Rasterized areas are clipped to their regions, and -/// discarded overprints are dropped. Layers the pages leave out (non-printing ones, unless asked +/// pattern tiles, count as transparency. Rasterized areas are clipped to their regions and keep no +/// alpha, and discarded overprints are dropped. Layers the pages leave out (non-printing ones, unless asked /// for) are left out of the flattening, hidden. → the document to write (`None`: `doc` as it is) /// and whether its transparency was flattened. fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Result<(Option, Option)> { @@ -459,8 +655,9 @@ fn flatten_for(cmd: &str, doc: &Document, set: &PdfSettings, p: &Value) -> Resul o.preserve_overprints &= set.advanced.overprint == Overprint::Preserve; o.no_transparency = Some(see_through_images(doc)); // Without soft masks a rasterized area can't be a rectangle with see-through pixels around - // its art: it is clipped to its regions (opaque inside them). + // its art: it is clipped to its regions (opaque inside them). Rasters keep no alpha either. o.clip_complex_regions = true; + o.preserve_alpha = false; Ok(match flatten_document(shown.as_ref().unwrap_or(doc), &o)? { Some(flat) => (Some(flat), Some(o)), None => (shown, None), diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index ea5cf63aa2..cbfaa434d5 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -684,57 +684,64 @@ struct Counts { clipped_out: usize, } -/// `n` things: "1 layer was", "2 layers were". -fn count(n: usize, one: &str, many: &str) -> String { - if n == 1 { format!("1 {one} was") } else { format!("{n} {many} were") } +/// Adds the warning for `n` things to `out`: `one` when `n` is 1, `many` with the count in place +/// of `{n}` when it is more, none when it is 0. Each form is a whole sentence, the key of its own +/// catalog row. +fn note(out: &mut Vec, n: usize, (one, many): (&str, &str)) { + match n { + 0 => {} + 1 => out.push(one.to_string()), + n => out.push(many.replace("{n}", &n.to_string())), + } } +/// The layer warnings in English, the form for one layer and the form for more, in the order a +/// file's warnings list them. +pub const LAYER_WARNINGS: [(&str, &str); 10] = [ + ("1 type layer came in as pixels: the text isn't editable", "{n} type layers came in as pixels: the text isn't editable"), + ("1 adjustment layer was not applied", "{n} adjustment layers were not applied"), + ( + "1 fill layer was not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels)", + "{n} fill layers were not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels)", + ), + ("the layer effects of 1 layer weren't drawn", "the layer effects of {n} layers weren't drawn"), + ("the vector masks of 1 layer weren't applied", "the vector masks of {n} layers weren't applied"), + ("the knockout of 1 layer wasn't applied", "the knockout of {n} layers wasn't applied"), + ( + "1 layer was left out (hidden layers and the layers clipped to them)", + "{n} layers were left out (hidden layers and the layers clipped to them)", + ), + ("1 layer clipped to a fill layer that wasn't drawn was left out", "{n} layers clipped to fill layers that weren't drawn were left out"), + ( + "1 layer in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed", + "{n} layers in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed", + ), + ( + "1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed", + "{n} layers clipped to the layer below came in unclipped: the merge needs more memory than allowed", + ), +]; + +/// The warning for layers merged with the layers below them, `{modes}` the blend modes' names. +pub const MERGED_WARNING: &str = "layers in blend modes VectorCraft doesn't have ({modes}) were merged with the layers below them"; + impl Notes { fn warnings(self) -> Vec { + let [types, adjustments, fills, effects, masks, knockouts, hidden, clipped_out, unmerged, unclipped] = LAYER_WARNINGS; let mut out = vec![]; - if self.types > 0 { - let n = if self.types == 1 { "1 type layer".to_string() } else { format!("{} type layers", self.types) }; - out.push(format!("{n} came in as pixels: the text isn't editable")); - } - if self.adjustments > 0 { - out.push(format!("{} not applied", count(self.adjustments, "adjustment layer", "adjustment layers"))); - } - if self.fills > 0 { - out.push(format!( - "{} not drawn (a gradient or pattern fill, a color that can't be read, or a shape that stores no pixels)", - count(self.fills, "fill layer", "fill layers") - )); - } - let layers = |n: usize| if n == 1 { "1 layer".to_string() } else { format!("{n} layers") }; - if self.effects > 0 { - out.push(format!("the layer effects of {} weren't drawn", layers(self.effects))); - } - if self.vector_masks > 0 { - out.push(format!("the vector masks of {} weren't applied", layers(self.vector_masks))); - } - if self.knockouts > 0 { - out.push(format!("the knockout of {} wasn't applied", layers(self.knockouts))); - } - if self.hidden > 0 { - out.push(format!("{} left out (hidden layers and the layers clipped to them)", count(self.hidden, "layer", "layers"))); - } - if self.clipped_out == 1 { - out.push("1 layer clipped to a fill layer that wasn't drawn was left out".into()); - } else if self.clipped_out > 1 { - out.push(format!("{} layers clipped to fill layers that weren't drawn were left out", self.clipped_out)); - } + note(&mut out, self.types, types); + note(&mut out, self.adjustments, adjustments); + note(&mut out, self.fills, fills); + note(&mut out, self.effects, effects); + note(&mut out, self.vector_masks, masks); + note(&mut out, self.knockouts, knockouts); + note(&mut out, self.hidden, hidden); + note(&mut out, self.clipped_out, clipped_out); if !self.merged.is_empty() { - out.push(format!("layers in blend modes VectorCraft doesn't have ({}) were merged with the layers below them", self.merged.join(", "))); - } - if self.unmerged > 0 { - out.push(format!( - "{} in blend modes VectorCraft doesn't have came in as Normal: the merge needs more memory than allowed", - layers(self.unmerged) - )); - } - if self.unclipped > 0 { - out.push(format!("{} clipped to the layer below came in unclipped: the merge needs more memory than allowed", layers(self.unclipped))); + out.push(MERGED_WARNING.replace("{modes}", &self.merged.join(", "))); } + note(&mut out, self.unmerged, unmerged); + note(&mut out, self.unclipped, unclipped); out } diff --git a/crates/engine/src/cmd/fileio/psdslices.rs b/crates/engine/src/cmd/fileio/psdslices.rs index cf5506ff3b..974b48ec2c 100644 --- a/crates/engine/src/cmd/fileio/psdslices.rs +++ b/crates/engine/src/cmd/fileio/psdslices.rs @@ -175,8 +175,9 @@ fn skip_record(r: &mut Reader<'_>) -> Result<(), String> { /// Versions 7 and 8: the descriptor's `slices` list, each slice an object. fn from_descriptor(d: &[(String, Value)]) -> Result, String> { let Some(Value::List(list)) = field(d, "slices") else { return Err("the slices' descriptor has no list of slices".into()) }; - if list.len() > MAX_SLICES { - return Err(format!("the file has {} slices, more than the {MAX_SLICES} read", list.len())); + let count = list.len(); + if count > MAX_SLICES { + return Err(format!("the file has {count} slices, more than the {MAX_SLICES} read")); } let mut out = vec![]; for s in list { diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 8a9b29fec2..7150d68dbb 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -629,6 +629,24 @@ impl std::io::Write for Counted { } } +/// A writer that fails once the work running on this thread is canceled +/// ([`crate::cancel::is_cancelled`]), so a streamed save stops writing into its temporary file. +/// It sits under the stream's buffer: it is checked once per buffer written, not per write. +struct StopsWhenCancelled(W); + +impl std::io::Write for StopsWhenCancelled { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if crate::cancel::is_cancelled() { + return Err(std::io::Error::other(crate::cancel::Cancelled)); + } + self.0.write(buf) + } + + fn flush(&mut self) -> std::io::Result<()> { + self.0.flush() + } +} + /// The artboards a native or `.ai` save also writes to files of their own: with /// `separateArtboards`, those `range` names (default all). fn separate_boards(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result> { @@ -1026,10 +1044,15 @@ impl SaveJob { } /// [`SaveJob::write`], once `stop` has seen the paths of every file it writes to a path, in - /// order: when `stop` returns a value, nothing is written and that value is returned. + /// order: when `stop` returns a value, nothing is written and that value is returned. Work + /// canceled ([`crate::cancel`]) before the first file is written returns + /// [`crate::EngineError::Cancelled`] and writes nothing; once the first file is written, the + /// others are written too. pub fn write_unless(&self, stop: impl FnOnce(&[&str]) -> Option, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result { let (plan, doc) = (&self.plan, &*self.doc); + crate::cancel::check()?; let enc = self.encode()?; + crate::cancel::check()?; let extra = json!({ "format": plan.format.id, "warnings": enc.notes() }); let Some(path) = &plan.path else { let mut out = write_encoded(None, &plan.name, doc, &enc, extra)?; @@ -1046,8 +1069,13 @@ impl SaveJob { if let Some(stopped) = stop(&files.iter().map(|(p, _)| p.as_str()).collect::>()) { return Ok(stopped); } - for (p, bytes) in &files { - write(p, bytes)?; + for (i, (p, bytes)) in files.iter().enumerate() { + if i == 0 { + write(p, bytes)?; + } else { + // Once a file is in place, a Cancel no longer stops the save: the set is written whole. + crate::cancel::scope(&crate::cancel::CancelToken::new(), None, || write(p, bytes))?; + } } let bytes = files.first().map_or(0, |f| f.1.len()); let mut out = super::merge(json!({ "path": path, "bytes": bytes }), extra); @@ -1070,11 +1098,15 @@ impl SaveJob { /// [`SaveJob::write`] through `stream`, which writes the file at a path with what the filler /// it is given writes (atomically, as [`vectorcraft_format::write_atomic_with`]). A native /// file goes into it as it is encoded ([`SaveJob::streams`]), never held whole in memory; - /// other files are encoded first, then written into it. + /// other files are encoded first, then written into it. Work canceled ([`crate::cancel`]) + /// while the native file is encoded, or before its filler returns, returns + /// [`crate::EngineError::Cancelled`]: the filler fails, so `stream` keeps the file as it was + /// (the atomic writer checks once more before it puts the file in place). pub fn write_streamed(&self, stream: StreamWrite) -> Result { let (Some(path), true) = (&self.plan.path, self.streams()) else { return self.write(|p, b| stream(p, &mut |w| w.write_all(b))); }; + crate::cancel::check()?; let (cmd, f) = (self.plan.mode.command(), self.plan.format); let doc = self.doc.without_edit_modes(); let doc = match f.id { @@ -1091,16 +1123,22 @@ impl SaveJob { let mut failed = None; let mut written = 0u64; let mut fill = |w: &mut dyn std::io::Write| { - let mut out = Counted { inner: std::io::BufWriter::with_capacity(STREAM_BUFFER, w), n: 0 }; + let mut out = Counted { inner: std::io::BufWriter::with_capacity(STREAM_BUFFER, StopsWhenCancelled(w)), n: 0 }; let r = super::native::encode_to(cmd, f, &doc, &self.params, &mut out); written = out.n; - match r { + let r = match r { Ok(()) => out.inner.flush(), Err(e) => { failed = Some(e); Err(std::io::Error::other("the file couldn't be encoded")) } + }; + // The last check before the file is replaced: a canceled save leaves it as it was. + if crate::cancel::is_cancelled() { + failed = Some(crate::EngineError::Cancelled); + return Err(std::io::Error::other(crate::cancel::Cancelled)); } + r }; let r = stream(path, &mut fill); r.map_err(|e| failed.take().unwrap_or(e))?; diff --git a/crates/engine/src/cmd/fileio/screens.rs b/crates/engine/src/cmd/fileio/screens.rs index 3663d3e2f6..442f38e3cc 100644 --- a/crates/engine/src/cmd/fileio/screens.rs +++ b/crates/engine/src/cmd/fileio/screens.rs @@ -1349,10 +1349,14 @@ fn encode_and_write(export: ScreenExport, writer: &mut dyn FnMut(&str, &[u8]) -> } // The document a PDF row writes: with Include Bleed, the artboards as they are. let pdf_doc = ungrown.as_deref(); + // A PDF page of an artboard has the artboard as its trim, with or without Include Bleed. A + // page of its art's bounds has every object at its edge: it doesn't say whether art stops + // short of the bleed. + let artboard_page = o.assets.is_none() && o.layers.is_none() && o.selection.is_none(); let mut write = |doc: &Document, format: &str, options: &Value| -> Result> { // The steps are the files: an encoder's own steps (artboards, pages) are not reported. let (bytes, given) = vectorcraft_doc::cancel::quiet(|| encode_with_notes(doc, format, options))?; - for n in given { + for n in given.into_iter().filter(|n| artboard_page || !super::pdf::is_short_of_bleed(&n.text)) { add_note(&mut notes, n); } Ok(bytes) diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index f3161c229d..56e2a12f30 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -935,6 +935,109 @@ fn a_save_that_fails_while_streaming_leaves_the_file_as_it_was() { let _ = std::fs::remove_dir_all(&d); } +/// A save canceled (Background Save's Cancel) before it starts, while a native file streams into +/// its temporary file, or after the last byte went into it, fails with `Cancelled` and leaves the +/// file as it was, with no temporary file behind. A file encoded first is never written. +#[test] +fn a_canceled_save_leaves_the_file_as_it_was() { + /// Passes every write on, and cancels the save after the first one. + struct CancelAfterFirst<'a> { + inner: &'a mut dyn std::io::Write, + token: crate::cancel::CancelToken, + } + impl std::io::Write for CancelAfterFirst<'_> { + fn write(&mut self, b: &[u8]) -> std::io::Result { + let n = self.inner.write(b)?; + self.token.cancel(); + Ok(n) + } + fn flush(&mut self) -> std::io::Result<()> { + self.inner.flush() + } + } + let d = tmp_dir("stream-cancel"); + // A small document's file goes in one piece; a large one's in several. + for count in [1, 1500] { + let mut s = session(2000.0, 2000.0, 1); + for i in 0..count { + s.execute("shape.rectangle", &json!({"x": i % 100 * 20, "y": i / 100 * 20, "width": 10, "height": 10})).unwrap(); + } + let path = d.join("a.vectorcraft").to_string_lossy().to_string(); + s.execute("file.saveCopy", &json!({"path": path})).unwrap(); + let before = std::fs::read(&path).unwrap(); + s.execute("shape.ellipse", &json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap(); + let plan = save_plan(&s, SaveMode::Copy, &json!({"path": path})).unwrap(); + let job = save_job(&mut s, plan).unwrap(); + assert!(job.streams()); + let token = crate::cancel::CancelToken::new(); + let r = crate::cancel::scope(&token, None, || { + job.write_streamed(&mut |p, fill| super::write_file_with(p, &mut |w| fill(&mut CancelAfterFirst { inner: w, token: token.clone() }))) + }); + assert!(matches!(r, Err(EngineError::Cancelled)), "{count}: {r:?}"); + assert_eq!(std::fs::read(&path).unwrap(), before, "{count} objects"); + assert_eq!(std::fs::read_dir(&d).unwrap().count(), 1, "no temporary file is left"); + // Canceled before it starts: the file isn't opened. + let mut opened = false; + let r = crate::cancel::scope(&token, None, || { + job.write_streamed(&mut |_, _| { + opened = true; + Ok(()) + }) + }); + assert!(matches!(r, Err(EngineError::Cancelled)) && !opened, "{r:?}"); + } + // A file encoded first (SVG): nothing reaches the writer. + let mut s = session(200.0, 100.0, 1); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); + let plan = save_plan(&s, SaveMode::Copy, &json!({"path": d.join("a.svg").to_string_lossy()})).unwrap(); + let job = save_job(&mut s, plan).unwrap(); + let token = crate::cancel::CancelToken::new(); + token.cancel(); + let mut writes = 0; + let r = crate::cancel::scope(&token, None, || { + job.write_streamed(&mut |_, _| { + writes += 1; + Ok(()) + }) + }); + assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); + let r = crate::cancel::scope(&token, None, || { + job.write(|_, _| { + writes += 1; + Ok(()) + }) + }); + assert!(matches!(r, Err(EngineError::Cancelled)) && writes == 0, "{r:?}"); + assert!(!d.join("a.svg").exists()); + let _ = std::fs::remove_dir_all(&d); +} + +/// A save that writes several files (EPS with Use Artboards) and is canceled once its first file is +/// in place writes the others too and succeeds: the set is never left half written. +#[test] +fn a_save_canceled_after_its_first_file_writes_them_all() { + let d = tmp_dir("cancel-files"); + let mut s = session(100.0, 100.0, 2); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); + let path = d.join("logo.eps").to_string_lossy().to_string(); + let plan = save_plan(&s, SaveMode::Copy, &json!({"path": path, "options": {"useArtboards": true}})).unwrap(); + let job = save_job(&mut s, plan).unwrap(); + let token = crate::cancel::CancelToken::new(); + let mut written = vec![]; + let r = crate::cancel::scope(&token, None, || { + job.write(|p, b| { + super::write_save_file(p, b)?; + written.push(p.to_string()); + token.cancel(); + Ok(()) + }) + }); + assert!(r.is_ok(), "{r:?}"); + assert_eq!(written.len(), 3, "{written:?}"); + assert!(written.iter().all(|p| std::path::Path::new(p).is_file()), "{written:?}"); + let _ = std::fs::remove_dir_all(&d); +} + /// A save that fails leaves File Info's dates and the saved state alone; one that works stamps them. #[test] fn a_failed_save_does_not_stamp_the_documents_dates() { diff --git a/crates/engine/src/cmd/fileio/tests_cdr.rs b/crates/engine/src/cmd/fileio/tests_cdr.rs new file mode 100644 index 0000000000..a8782eca89 --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_cdr.rs @@ -0,0 +1,618 @@ +//! `.cdr` drawings: Open, Place and New from Template, by extension and by content, mapped to +//! artboards, layers, guides, live shapes, solid paint and strokes. + +use super::*; +use serde_json::json; +use vectorcraft_cdr::synth::{self, V, chunk, list}; +use vectorcraft_doc::{LiveShape, Node, NodeKind}; + +fn walk(nodes: &[std::sync::Arc], out: &mut Vec) { + for n in nodes { + match &n.kind { + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => walk(children, out), + NodeKind::RulerGuide { .. } => {} + _ => out.push((**n).clone()), + } + } +} + +fn paths(doc: &vectorcraft_doc::Document) -> Vec { + let mut out = Vec::new(); + walk(&doc.layers, &mut out); + out +} + +#[test] +fn every_version_opens_as_editable_art() { + // Versions 14 on are ZIP packages. + for version in [500, 600, 700, 800, 900, 1000, 1100, 1200, 1300, 1400, 1500, 1600, 2000, 2700] { + let mut s = Session::new(); + let r = open_bytes(&mut s, "drawing.cdr", &synth::sample_file(version, version >= 700), None).unwrap(); + assert_eq!(r["format"], "cdr", "{version}"); + let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).collect(); + assert!(w.iter().any(|w| w.contains("text, bitmaps")), "{version}: {w:?}"); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.artboards.len(), 1); + assert_eq!((doc.artboards[0].rect.width().round(), doc.artboards[0].rect.height().round()), (612.0, 792.0)); + // The page's layer "Art", above the master page's desktop layer. + let names: Vec = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + assert_eq!(names.last().map(String::as_str), Some("Art"), "{version}: {names:?}"); + let p = paths(doc); + // Five shapes on the page and one on the desktop. + assert_eq!(p.len(), 6, "{version}"); + let rect = p.iter().find( + |n| matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Rectangle { w, .. } if (w - 100.0).abs() < 0.1)), + ); + let rect = rect.unwrap_or_else(|| panic!("{version}: no live rectangle")); + let NodeKind::Path { live: Some(live), .. } = &rect.kind else { unreachable_in_test() }; + let LiveShape::Rectangle { radii, .. } = **live else { unreachable_in_test() }; + assert!(radii.iter().all(|r| (r - 5.0).abs() < 0.1), "{version}: {radii:?}"); + assert!(p.iter().any(|n| matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Ellipse { .. })))); + // The rectangle is filled red and stroked 2 pt with round caps. + let a = &rect.appearance; + assert_eq!(a.items.len(), 2, "{version}"); + // The master page's vertical guideline at 36 pt right of the page centre, a ruler guide + // on the top layer. + if version >= 600 { + let guides = doc.ruler_guides(); + let top = doc.layers.last().map(|l| l.id); + assert!( + guides.iter().any(|g| g.vertical && (g.pos - (306.0 + 36.0)).abs() < 0.05 && g.artboard == Some(1) && g.layer == top), + "{version}: {guides:?}" + ); + } + } +} + +fn unreachable_in_test() -> ! { + panic!("the match above already checked the shape") +} + +/// The live rectangle of `doc` that is 100 pt wide, with its node. +fn sample_rect(doc: &vectorcraft_doc::Document) -> Node { + paths(doc) + .into_iter() + .find(|n| matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Rectangle { w, .. } if (w - 100.0).abs() < 0.1))) + .unwrap_or_else(|| panic!("no live rectangle")) +} + +#[test] +fn versions_3_and_4_open_and_place_as_editable_art() { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::appearance::{AppearanceItem, LineCap, LineJoin}; + for version in [300, 400] { + let bytes = synth::sample(version, false); + let mut s = Session::new(); + // By its name, and by its content under another name. + for name in ["drawing.cdr", "renamed.bin"] { + let r = open_bytes(&mut s, name, &bytes, None).unwrap(); + assert_eq!(r["format"], "cdr", "{version} {name}"); + let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).collect(); + assert!(w.iter().any(|w| w.contains("text, bitmaps")) && !w.iter().any(|w| w.contains("damaged")), "{version}: {w:?}"); + } + let doc = &s.doc().unwrap().doc; + assert_eq!((doc.artboards[0].rect.width().round(), doc.artboards[0].rect.height().round()), (612.0, 792.0), "{version}"); + let names: Vec = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + assert_eq!(names.last().map(String::as_str), Some("Art"), "{version}: {names:?}"); + assert_eq!(paths(doc).len(), 6, "{version}"); + let rect = sample_rect(doc); + let NodeKind::Path { live: Some(live), path, .. } = &rect.kind else { unreachable_in_test() }; + let LiveShape::Rectangle { radii, .. } = **live else { unreachable_in_test() }; + assert!(radii.iter().all(|r| (r - 5.0).abs() < 0.1), "{version}: {radii:?}"); + // 100 pt left of and above the page centre, y pointing down in the document. + let b = path.bounds().unwrap(); + assert!((b.x0 - 206.0).abs() < 0.2 && (b.y1 - 296.0).abs() < 0.2, "{version}: {b:?}"); + let [AppearanceItem::Fill(fill), AppearanceItem::Stroke(stroke)] = rect.appearance.items.as_slice() else { + panic!("{version}: {:?}", rect.appearance.items) + }; + assert_eq!(fill.paint, Paint::solid(Color::cmyk(0.0, 1.0, 1.0, 0.0)), "{version}"); + assert!((stroke.width - 2.0).abs() < 0.05, "{version}: {}", stroke.width); + assert_eq!((stroke.cap, stroke.join), (LineCap::Round, LineJoin::Round), "{version}"); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + s.execute("file.place", &json!({"name":"art.cdr", "dataBase64":vectorcraft_format::base64_encode(&bytes)})).unwrap(); + assert!(s.doc().unwrap().doc.layers.iter().any(|l| !l.children().unwrap().is_empty()), "{version}"); + } +} + +#[test] +fn versions_1_and_2_open_and_place_as_editable_art() { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::appearance::AppearanceItem; + for marker in *b"elm" { + let bytes = synth::wl_sample(marker); + let mut s = Session::new(); + for name in ["drawing.cdr", "renamed.bin"] { + let r = open_bytes(&mut s, name, &bytes, None).unwrap(); + assert_eq!(r["format"], "cdr", "{name}"); + let w: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()).collect(); + assert!(w.len() == 1 && w[0].contains("text, bitmaps"), "{w:?}"); + } + assert_eq!(detect("drawing.cdt", &bytes).map(|f| f.id), Some("cdt")); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.artboards.len(), 1); + assert_eq!((doc.artboards[0].rect.width().round(), doc.artboards[0].rect.height().round()), (612.0, 792.0)); + assert_eq!(doc.layers.len(), 1); + // Bottom first in the document: the curve, the ellipse, then the rectangle in front. + let p = paths(doc); + assert_eq!(p.len(), 3); + assert!(matches!(&p[1].kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Ellipse { .. }))); + let rect = sample_rect(doc); + assert_eq!(rect.id, p[2].id); + let NodeKind::Path { path, .. } = &rect.kind else { unreachable_in_test() }; + let b = path.bounds().unwrap(); + assert!((b.x0 - 206.0).abs() < 0.2 && (b.y1 - 296.0).abs() < 0.2 && (b.height() - 50.0).abs() < 0.2, "{b:?}"); + let [AppearanceItem::Fill(fill), AppearanceItem::Stroke(stroke)] = rect.appearance.items.as_slice() else { + panic!("{:?}", rect.appearance.items) + }; + assert_eq!(fill.paint, Paint::solid(Color::cmyk(0.0, 1.0, 1.0, 0.0))); + assert_eq!(stroke.paint, Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0))); + assert!((stroke.width - 2.0).abs() < 0.05, "{}", stroke.width); + // The curve is drawn at twice its size by its matrix: 100 pt wide. + let NodeKind::Path { path, .. } = &p[0].kind else { panic!("{:?}", p[0].kind) }; + assert!((path.bounds().unwrap().width() - 100.0).abs() < 0.2); + assert_eq!(doc.color_mode, vectorcraft_doc::ColorMode::Cmyk); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + s.execute("file.place", &json!({"name":"art.cdr", "dataBase64":vectorcraft_format::base64_encode(&bytes)})).unwrap(); + assert!(s.doc().unwrap().doc.layers.iter().any(|l| !l.children().unwrap().is_empty())); + } + // The two letters alone are not taken for a drawing. + assert_eq!(detect("notes.bin", b"WLAN settings, exported as plain text for the help desk").map(|f| f.id), None); +} + +#[test] +fn objects_keep_the_file_order_front_to_back() { + let v = V(1100); + let rect = + |w: f64| synth::object(v, 1, &[(30, [v.coord(w), v.coord(10.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + // The first object listed is the front-most. + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect(30.0), rect(20.0)])]); + let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), page]); + let (doc, _) = super::cdr::import(&file).unwrap(); + let p = paths(&doc); + let widths: Vec = p + .iter() + .filter_map(|n| match &n.kind { + NodeKind::Path { path, .. } => path.bounds(), + _ => None, + }) + .map(|b| b.width().round()) + .collect(); + assert_eq!(widths, vec![20.0, 30.0], "bottom first"); +} + +#[test] +fn spot_colors_become_spot_swatches_and_cmyk_drawings_open_in_cmyk() { + let v = V(1100); + let spot = synth::color(25, [7, 0, 40, 0]); + let cmyk = synth::color(2, [0, 100, 0, 0]); + let doc = list(b"doc ", vec![list(b"filt", vec![chunk(b"fild", v.fill(1, &spot)), chunk(b"fild", v.fill(2, &cmyk))])]); + let obj = |fill: u32| { + synth::object( + v, + 1, + &[ + (20, fill.to_le_bytes().to_vec()), + (30, [v.coord(10.0), v.coord(10.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat()), + ], + None, + ) + }; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![obj(1), obj(2), obj(2)])]); + let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, page]); + let (doc, warnings) = super::cdr::import(&file).unwrap(); + let s = doc.swatches.iter().find(|s| s.name == "Spot 0:7").unwrap(); + assert!(s.spot && s.global); + assert!(warnings.iter().any(|w| w.contains("library colors")), "{warnings:?}"); + let filled_with_spot = paths(&doc).iter().any(|n| { + n.appearance.items.iter().any(|i| matches!(i, vectorcraft_doc::appearance::AppearanceItem::Fill(f) if matches!(&f.paint, vectorcraft_color::Paint::Solid { swatch: Some(name), tint, .. } if name == "Spot 0:7" && (*tint - 0.4).abs() < 1e-6))) + }); + assert!(filled_with_spot); + assert_eq!(doc.color_mode, vectorcraft_doc::ColorMode::Cmyk); +} + +#[test] +fn detection_by_content_place_and_template() { + let bytes = synth::sample(1100, true); + let mut s = Session::new(); + // A renamed drawing is found by its content. + assert_eq!(open_bytes(&mut s, "renamed.bin", &bytes, None).unwrap()["format"], "cdr"); + assert_eq!(detect("drawing.cdt", &bytes).map(|f| f.id), Some("cdt")); + assert_eq!(detect("drawing.png", &bytes).map(|f| f.id), Some("cdr")); + // So is a package of version 14 or later, and other ZIP archives are not taken for one. + for version in [1400, 2700] { + let package = synth::sample_file(version, true); + assert_eq!(open_bytes(&mut s, "renamed.zip", &package, None).unwrap()["format"], "cdr", "{version}"); + assert_eq!(detect("drawing.cdt", &package).map(|f| f.id), Some("cdt")); + } + let other = synth::zip(&[synth::Member { name: "content/other.dat".into(), data: vec![1, 2, 3], deflate: false }], b""); + assert_eq!(detect("archive.zip", &other).map(|f| f.id), None); + let r = open_bytes(&mut s, "letter.cdt", &bytes, Some("/t/letter.cdt".into())).unwrap(); + assert_eq!(r["format"], "cdt"); + assert!(s.doc().unwrap().path.is_none(), "a template opens untitled"); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + s.execute("file.place", &json!({"name":"art.cdr", "dataBase64":vectorcraft_format::base64_encode(&bytes)})).unwrap(); + assert!(s.doc().unwrap().doc.layers.iter().any(|l| !l.children().unwrap().is_empty())); + // Packages place too. + for version in [1400, 2700] { + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + let package = synth::sample_file(version, true); + s.execute("file.place", &json!({"name":"art.cdr", "dataBase64":vectorcraft_format::base64_encode(&package)})).unwrap(); + assert!(s.doc().unwrap().doc.layers.iter().any(|l| !l.children().unwrap().is_empty()), "{version}"); + } + for ext in ["cdr", "cdt"] { + let f = format(ext).unwrap(); + assert!(f.read && !f.write); + assert!(OPEN_EXTS.contains(&ext) && PLACE_EXTS.contains(&ext) && UNASSOCIATED_EXTS.contains(&ext), "{ext}"); + assert!(!SAVE_FORMATS.contains(&ext)); + } +} + +#[test] +fn layers_of_one_name_on_a_page_stay_apart_and_pages_share_them() { + let v = V(1100); + let rect = || synth::object(v, 1, &[(30, [v.coord(5.0), v.coord(5.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + let layer = |name: &str| synth::layer(v, [0, 0, 0, 0x98], name, vec![rect()]); + // Front to back: A, B, A on each of two pages. + let page = || synth::page(false, vec![layer("A"), layer("B"), layer("A")]); + let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), page(), page()]); + let (doc, _) = super::cdr::import(&file).unwrap(); + let names: Vec = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + assert_eq!(names, ["A", "B", "A"]); + assert!(doc.layers.iter().all(|l| l.children().unwrap().len() == 2), "one object from each page"); +} + +/// Pages that stack layers of the same names in another order keep their own order: the later +/// page gets a new layer rather than art under a layer it stacks above. A layer a later page adds +/// below the shared ones goes below them, and a page that shares no layer puts its layers on top. +#[test] +fn each_page_keeps_its_own_layer_order() { + let v = V(1100); + let rect = || synth::object(v, 1, &[(30, [v.coord(5.0), v.coord(5.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + let page = |names: &[&str]| synth::page(false, names.iter().map(|n| synth::layer(v, [0, 0, 0, 0x98], n, vec![rect()])).collect()); + // Front to back on each page. + for (second, want, counts) in [ + (&["A", "B"][..], vec!["A", "B", "A"], vec![1, 2, 1]), + (&["B", "A", "C"][..], vec!["C", "A", "B"], vec![1, 2, 2]), + (&["D", "C"][..], vec!["A", "B", "C", "D"], vec![1, 1, 1, 1]), + ] { + let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), page(&["B", "A"]), page(second)]); + let (doc, _) = super::cdr::import(&file).unwrap(); + let names: Vec = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + assert_eq!(names, want, "bottom to top, second page {second:?}"); + let got: Vec = doc.layers.iter().map(|l| l.children().unwrap().len()).collect(); + assert_eq!(got, counts, "second page {second:?}"); + } +} + +/// Pages that alternate between two orders of the same layers reuse the layers made for each +/// order instead of adding layers page after page. +#[test] +fn pages_in_alternating_layer_orders_reuse_their_layers() { + let v = V(1100); + let rect = || synth::object(v, 1, &[(30, [v.coord(5.0), v.coord(5.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + let page = |names: &[&str]| synth::page(false, names.iter().map(|n| synth::layer(v, [0, 0, 0, 0x98], n, vec![rect()])).collect()); + // Front to back on each page. + let mut kids = vec![chunk(b"vrsn", 1100u16.to_le_bytes().to_vec())]; + kids.extend((0..6).map(|i| if i % 2 == 0 { page(&["B", "A"]) } else { page(&["A", "B"]) })); + let (doc, _) = super::cdr::import(&synth::riff(1100, &kids)).unwrap(); + let names: Vec = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + assert_eq!(names, ["A", "B", "A"], "bottom to top"); + let got: Vec = doc.layers.iter().map(|l| l.children().unwrap().len()).collect(); + assert_eq!(got, [3, 6, 3]); +} + +#[test] +fn pages_and_the_guides_copied_onto_them_are_bounded() { + let v = V(1100); + let guide = |x: f64| { + let mut g = vec![0; 12]; + g.extend(90_000_000i32.to_le_bytes()); + g.extend([v.coord(x), v.coord(0.0), v.coord(x), v.coord(10.0), v.coord(x), v.coord(0.0)].concat()); + synth::object(v, 0x16, &[(16000, g)], None) + }; + let guides: Vec<_> = (0..200).map(|i| guide(f64::from(i))).collect(); + let mut kids = vec![chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), synth::page(true, vec![synth::layer(v, [0x0a, 0, 1, 0x98], "G", guides)])]; + kids.extend((0..1100).map(|_| synth::page(false, vec![]))); + let (doc, warnings) = super::cdr::import(&synth::riff(1100, &kids)).unwrap(); + assert_eq!(doc.artboards.len(), 1000); + let guides = doc.ruler_guides().len(); + assert!(guides <= 100_000, "{guides}"); + assert!(warnings.iter().any(|w| w.contains("past the import limits")), "{warnings:?}"); +} + +/// Layers are held to 10,000, the master page's and the pages' together; at the limit, guide +/// paths of angled guidelines go on the top layer. +#[test] +fn layers_are_bounded() { + let v = V(1100); + let rect = || synth::object(v, 1, &[(30, [v.coord(5.0), v.coord(5.0), v.coord(0.0), v.coord(0.0), v.coord(0.0), v.coord(0.0)].concat())], None); + let mut angled = vec![0; 12]; + angled.extend(45_000_000i32.to_le_bytes()); + angled.extend([v.coord(0.0), v.coord(0.0)].concat()); + let angled = synth::object(v, 0x16, &[(16000, angled)], None); + let page_layers = + (0..10_050).map(|i| synth::layer(v, [0, 0, 0, 0x98], &format!("L{i}"), if i == 0 { vec![angled.clone()] } else { vec![] })).collect(); + let master_layers = (0..10_050).map(|i| synth::layer(v, [0, 0, 1, 0x98], &format!("M{i}"), vec![rect()])).collect(); + for (page, guide_paths) in [(synth::page(false, page_layers), 1), (synth::page(true, master_layers), 0)] { + let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), page, synth::page(false, vec![])]); + let (doc, warnings) = super::cdr::import(&file).unwrap(); + assert_eq!(doc.layers.len(), 10_000); + assert!(warnings.iter().any(|w| w.contains("past the import limits")), "{warnings:?}"); + let guides = paths(&doc).iter().filter(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })).count(); + assert_eq!(guides, guide_paths); + } +} + +/// A guide path of an angled guideline runs from edge to edge of its page, so it moves with that +/// page's artboard and not with the page beside it. +#[test] +fn angled_guides_move_with_their_page() { + let v = V(1100); + let angled = |deg: i32, x: f64, y: f64| { + let mut g = vec![0; 12]; + g.extend((deg * 1_000_000).to_le_bytes()); + g.extend([v.coord(x), v.coord(y)].concat()); + synth::object(v, 0x16, &[(16000, g)], None) + }; + let page = |g| synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "G", vec![g])]); + let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), page(angled(45, 0.0, 0.0)), page(angled(30, 50.0, -40.0))]); + let (doc, _) = super::cdr::import(&file).unwrap(); + assert_eq!(doc.artboards.len(), 2); + let guide = |id: &vectorcraft_doc::NodeId| doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })); + let moving: Vec> = (0..2).map(|i| doc.art_moving_with(i, false).into_iter().filter(guide).collect()).collect(); + assert_eq!(moving[0].len(), 1, "{moving:?}"); + assert_eq!(moving[1].len(), 1, "{moving:?}"); + assert_ne!(moving[0], moving[1]); +} + +/// A page longer than the longest artboard opens at that length, and the warnings say so. +#[test] +fn pages_past_the_longest_artboard_are_cut_with_a_warning() { + let v = V(1100); + for (w, cut) in [(200_000.0, true), (100_000.0, false)] { + let doc = list(b"doc ", vec![synth::mcfg(v, w, 792.0)]); + let file = synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, synth::page(false, vec![])]); + let (doc, warnings) = super::cdr::import(&file).unwrap(); + assert_eq!(doc.artboards[0].rect.width().round(), if cut { 163_830.0 } else { w }, "{w}"); + assert_eq!(warnings.iter().any(|x| x.contains("longer than 163,830 pt")), cut, "{w}: {warnings:?}"); + } +} + +#[test] +fn fills_and_outlines_keep_their_colors_widths_caps_joins_and_dashes() { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::appearance::{AppearanceItem, LineCap, LineJoin}; + let v = V(1300); + let red = synth::color(5, [0, 0, 255, 0]); + let black = synth::color(2, [0, 0, 0, 100]); + // Line type 4: a dashed outline. + let pen = synth::Pen { line_type: 4, width: 2.0, cap: 1, join: 2 }; + let args = vec![ + (20, 1u32.to_le_bytes().to_vec()), + (10, 2u32.to_le_bytes().to_vec()), + (30, v.points(&[(0.0, 0.0, 0x08), (10.0, 0.0, 0x40), (10.0, 10.0, 0x48)])), + ]; + let styles = list( + b"doc ", + vec![list(b"filt", vec![chunk(b"fild", v.fill(1, &red))]), list(b"otlt", vec![chunk(b"outl", v.outline(2, pen, &black, &[3, 1]))])], + ); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 3, &args, None)])]); + let (doc, _) = super::cdr::import(&synth::riff(1300, &[chunk(b"vrsn", 1300u16.to_le_bytes().to_vec()), styles, page])).unwrap(); + let p = paths(&doc); + let [AppearanceItem::Fill(fill), AppearanceItem::Stroke(stroke)] = p[0].appearance.items.as_slice() else { + panic!("{:?}", p[0].appearance.items) + }; + assert_eq!(fill.paint, Paint::solid(Color::rgb(1.0, 0.0, 0.0))); + assert_eq!(stroke.paint, Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0))); + assert!((stroke.width - 2.0).abs() < 0.01, "{}", stroke.width); + assert_eq!((stroke.cap, stroke.join), (LineCap::Round, LineJoin::Bevel)); + // Dashes are stored in multiples of the width. + let dash = stroke.dash.as_ref().unwrap(); + assert!(dash.pattern.len() == 2 && (dash.pattern[0] - 6.0).abs() < 0.01 && (dash.pattern[1] - 2.0).abs() < 0.01, "{:?}", dash.pattern); +} + +/// An outline of width 0 opens as a hairline stroke, which draws; a thin outline keeps its width. +#[test] +fn outlines_of_width_0_open_as_hairlines() { + use vectorcraft_doc::appearance::AppearanceItem; + let v = V(1100); + let black = synth::color(2, [0, 0, 0, 100]); + let doc = list( + b"doc ", + vec![list( + b"otlt", + vec![ + chunk(b"outl", v.outline(2, synth::Pen { line_type: 2, width: 0.0, cap: 0, join: 0 }, &black, &[])), + chunk(b"outl", v.outline(3, synth::Pen { line_type: 2, width: 0.1, cap: 0, join: 0 }, &black, &[])), + ], + )], + ); + let rect = |outline: u32| synth::object(v, 1, &[(10, outline.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))], None); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect(2), rect(3)])]); + let (doc, _) = super::cdr::import(&synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, page])).unwrap(); + let widths: Vec = paths(&doc) + .iter() + .map(|n| match n.appearance.items.as_slice() { + [AppearanceItem::Stroke(s)] => s.width, + other => panic!("{other:?}"), + }) + .collect(); + // Bottom to top: the file lists the 0.1 pt outline last. + assert!(widths.len() == 2 && (widths[0] - 0.1).abs() < 0.01 && (widths[1] - 0.25).abs() < 1e-9, "{widths:?}"); +} + +/// An outline behind the fill becomes a stroke painted before the fill. +#[test] +fn outlines_behind_the_fill_paint_first() { + use vectorcraft_doc::appearance::AppearanceItem; + let v = V(1100); + let black = synth::color(2, [0, 0, 0, 100]); + let doc = list( + b"doc ", + vec![ + list(b"filt", vec![chunk(b"fild", v.fill(1, &synth::color(5, [0, 0, 255, 0])))]), + list( + b"otlt", + vec![ + chunk(b"outl", v.outline(2, synth::Pen { line_type: 0x12, width: 4.0, cap: 0, join: 0 }, &black, &[])), + chunk(b"outl", v.outline(3, synth::Pen { line_type: 0x02, width: 4.0, cap: 0, join: 0 }, &black, &[])), + ], + ), + ], + ); + let rect = |outline: u32| { + let args = vec![(20, 1u32.to_le_bytes().to_vec()), (10, outline.to_le_bytes().to_vec()), (30, v.rect(10.0, 10.0, 0.0))]; + synth::object(v, 1, &args, None) + }; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect(2), rect(3)])]); + let (doc, _) = super::cdr::import(&synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, page])).unwrap(); + let p = paths(&doc); + assert_eq!(p.len(), 2); + // The file lists objects front to back; the document stacks them bottom to top. + let (behind, over) = (&p[1].appearance.items, &p[0].appearance.items); + assert!(matches!(behind.as_slice(), [AppearanceItem::Stroke(_), AppearanceItem::Fill(_)]), "{behind:?}"); + assert!(matches!(over.as_slice(), [AppearanceItem::Fill(_), AppearanceItem::Stroke(_)]), "{over:?}"); +} + +/// A container whose outline is behind its fill opens as a group of that outline below a clipping +/// group whose clipping path keeps only the fill. +#[test] +fn a_container_outline_behind_the_fill_stays_below_its_contents() { + use vectorcraft_doc::appearance::AppearanceItem; + let v = V(1100); + let black = synth::color(2, [0, 0, 0, 100]); + let rect = |w: f64, extra: Vec<(u32, Vec)>| { + let mut args = vec![(20, 1u32.to_le_bytes().to_vec()), (30, v.rect(w, w, 0.0))]; + args.extend(extra); + synth::object(v, 1, &args, None) + }; + let doc = list( + b"doc ", + vec![ + list(b"filt", vec![chunk(b"fild", v.fill(1, &synth::color(5, [0, 0, 255, 0])))]), + list(b"otlt", vec![chunk(b"outl", v.outline(2, synth::Pen { line_type: 0x12, width: 4.0, cap: 0, join: 0 }, &black, &[]))]), + synth::clpt(vec![(5, vec![rect(10.0, vec![])])]), + ], + ); + let container = rect(40.0, vec![synth::container(5), (10, 2u32.to_le_bytes().to_vec())]); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![container])]); + let (doc, _) = super::cdr::import(&synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, page])).unwrap(); + let layer = doc.layers.last().and_then(|l| l.children()).unwrap(); + let [both] = layer.as_slice() else { panic!("{layer:?}") }; + let NodeKind::Group { children: both, clip: false } = &both.kind else { panic!("{:?}", both.kind) }; + let [outline, group] = both.as_slice() else { panic!("{both:?}") }; + assert!(matches!(outline.appearance.items.as_slice(), [AppearanceItem::Stroke(_)]), "{:?}", outline.appearance.items); + let NodeKind::Group { children, clip: true } = &group.kind else { panic!("{:?}", group.kind) }; + assert!(matches!(children[0].appearance.items.as_slice(), [AppearanceItem::Fill(_)]), "{:?}", children[0].appearance.items); +} + +/// A container and the group it clips open as a clipping group: the container's shape first, as +/// the clipping path keeping its fill, then the clipped shapes. +#[test] +fn containers_open_as_clipping_groups() { + let v = V(1100); + let rect = |w: f64, extra: Vec<(u32, Vec)>| { + let mut args = vec![(20, 1u32.to_le_bytes().to_vec()), (30, v.rect(w, w, 0.0))]; + args.extend(extra); + synth::object(v, 1, &args, None) + }; + let doc = list( + b"doc ", + vec![ + list(b"filt", vec![chunk(b"fild", v.fill(1, &synth::color(5, [0, 0, 255, 0])))]), + synth::clpt(vec![(5, vec![rect(10.0, vec![]), rect(20.0, vec![])])]), + ], + ); + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![rect(40.0, vec![synth::container(5)])])]); + let (doc, warnings) = super::cdr::import(&synth::riff(1100, &[chunk(b"vrsn", 1100u16.to_le_bytes().to_vec()), doc, page])).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + let layer = doc.layers.last().and_then(|l| l.children()).unwrap(); + let [group] = layer.as_slice() else { panic!("{layer:?}") }; + let NodeKind::Group { children, clip: true } = &group.kind else { panic!("{:?}", group.kind) }; + assert_eq!(children.len(), 3); + assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. })); + assert_eq!(children[0].appearance.items.len(), 1, "the container keeps its fill"); + assert!(children[1..].iter().all(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. }))); +} + +/// An object with a lens or transparency opens opaque, and the warnings say so. +#[test] +fn lenses_and_transparency_are_named_in_the_warnings() { + let v = V(1200); + let args = vec![(30, v.rect(10.0, 10.0, 0.0)), (8000, vec![5, 0, 0, 0])]; + let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "L", vec![synth::object(v, 1, &args, None)])]); + let (doc, warnings) = super::cdr::import(&synth::riff(1200, &[chunk(b"vrsn", 1200u16.to_le_bytes().to_vec()), page])).unwrap(); + assert_eq!(paths(&doc).len(), 1); + assert_eq!(warnings, ["CDR lenses and object transparency were not applied, and the objects they are on show opaque"]); +} + +/// A uniform transparency, a winding flag and hidden and locked flags of a drawing of version 16 +/// open as the object's opacity, blend mode and fill rule and as hidden and locked nodes, without +/// a warning. +#[test] +fn transparency_winding_and_flags_open_on_the_art() { + let v = V(1600); + let args = vec![(30, v.rect(10.0, 10.0, 0.0)), synth::transparency(40.0, 29), (14001, vec![1, 0, 0, 0])]; + let object = synth::flagged(synth::object(v, 1, &args, None), [0x10, 0, 0, 8]); + let layers = vec![ + synth::layer(v, [0, 0, 0, 0x98], "Shown", vec![object]), + synth::layer(v, [0, 1, 0, 0x98], "Hidden", vec![synth::object(v, 1, &args[..1], None)]), + ]; + let file = synth::file_of(1600, vec![synth::page(false, layers)]); + let (doc, warnings) = super::cdr::import(&file).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + // Bottom to top: "Hidden", then "Shown". + let states: Vec<(String, bool)> = doc.layers.iter().map(|l| (l.name.clone().unwrap_or_default(), l.visible)).collect(); + assert_eq!(states, [("Hidden".to_string(), false), ("Shown".to_string(), true)]); + let shown = doc.layers[1].children().unwrap(); + let [n] = shown.as_slice() else { panic!("{shown:?}") }; + assert!(matches!(n.kind, NodeKind::Path { rule: vectorcraft_doc::geom::FillRule::NonZero, .. }), "{:?}", n.kind); + assert!((n.opacity - 0.6).abs() < 1e-6 && n.blend == vectorcraft_color::BlendMode::Overlay, "{} {:?}", n.opacity, n.blend); + assert!(n.locked && n.visible); +} + +/// A drawing whose open left things out is not written over unasked: the file stays as it was +/// until the write says `acknowledgeLoss`. +#[test] +fn a_drawing_the_open_left_things_out_of_is_not_written_over_unasked() { + let d = std::env::temp_dir().join(format!("vc-cdr-lossy-{}", std::process::id())); + std::fs::create_dir_all(&d).unwrap(); + let src = d.join("drawing.cdr"); + let original = synth::sample_file(1300, true); + std::fs::write(&src, &original).unwrap(); + let mut s = Session::new(); + let opened = s.execute("document.open", &json!({ "path": src.to_string_lossy() })).unwrap(); + assert!(opened["warnings"].to_string().contains("text, bitmaps"), "{opened}"); + let e = s.execute("document.export", &json!({ "path": src.to_string_lossy(), "format": "svg" })).unwrap_err().to_string(); + assert!(e.contains("acknowledgeLoss"), "{e}"); + assert_eq!(std::fs::read(&src).unwrap(), original); + s.execute("document.export", &json!({ "path": src.to_string_lossy(), "format": "svg", "acknowledgeLoss": true })).unwrap(); + assert_ne!(std::fs::read(&src).unwrap(), original); + std::fs::remove_dir_all(d).ok(); +} + +#[test] +fn other_versions_and_damaged_drawings_say_why() { + let mut s = Session::new(); + // A RIFF file that names version 2: files of versions 1 and 2 are not RIFF files. + let e = open_bytes(&mut s, "old.cdr", &synth::riff(200, &[]), None).unwrap_err().to_string(); + assert!(e.contains("can't be read (RIFF files of versions before 3 are not read)"), "{e}"); + let e = open_bytes(&mut s, "new.cdr", &synth::riff(2800, &[]), None).unwrap_err().to_string(); + assert!(e.contains("CDR 28 drawings can't be opened: VectorCraft reads versions 1 to 27"), "{e}"); + // A file that starts like one of version 1 or 2 but whose offsets don't fit it. + let e = open_bytes(&mut s, "odd.cdr", b"WLe\0 and no more", None).unwrap_err().to_string(); + assert!(e.contains("can't be read (not a CDR drawing)"), "{e}"); + // A package cut short, and one whose drawing is encrypted (flag bit 0 of its directory entry). + let package = synth::sample_file(1400, false); + let e = open_bytes(&mut s, "cut.cdr", &package[..package.len() / 2], None).unwrap_err().to_string(); + assert!(e.contains("can't be read (damaged package directory)"), "{e}"); + let mut encrypted = package.clone(); + let dir = package.windows(4).position(|w| w == b"PK\x01\x02").unwrap(); + encrypted[dir + 8] |= 1; + let e = open_bytes(&mut s, "locked.cdr", &encrypted, None).unwrap_err().to_string(); + assert!(e.contains("can't be read (encrypted packages are not read)"), "{e}"); + let mut big = synth::riff(1100, &[]); + big[4..8].copy_from_slice(&u32::MAX.to_le_bytes()); + // A declared size past the end keeps what the file holds. + assert!(open_bytes(&mut s, "cut.cdr", &big, None).is_ok()); +} diff --git a/crates/engine/src/cmd/fileio/tests_cmx.rs b/crates/engine/src/cmd/fileio/tests_cmx.rs new file mode 100644 index 0000000000..527c0be1be --- /dev/null +++ b/crates/engine/src/cmd/fileio/tests_cmx.rs @@ -0,0 +1,145 @@ +//! `.cmx` files: Open and Place, by extension and by content, mapped to artboards, layers, groups, +//! paths, solid paint and strokes, with their warnings and refusals. + +use super::*; +use serde_json::json; +use vectorcraft_cdr::synth_cmx::*; +use vectorcraft_doc::{Node, NodeKind}; + +fn paths(nodes: &[std::sync::Arc], out: &mut Vec) { + for n in nodes { + match &n.kind { + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => paths(children, out), + _ => out.push((**n).clone()), + } + } +} + +fn warnings(r: &serde_json::Value) -> Vec { + r["warnings"].as_array().map(|w| w.iter().filter_map(|w| w.as_str().map(str::to_string)).collect()).unwrap_or_default() +} + +#[test] +fn a_cmx_file_opens_as_editable_art() { + let mut s = Session::new(); + let r = open_bytes(&mut s, "drawing.cmx", &sample(), None).unwrap(); + assert_eq!(r["format"], "cmx"); + assert!(warnings(&r).is_empty(), "{r}"); + let doc = &s.doc().unwrap().doc; + // One 210 x 297 mm page. + assert_eq!(doc.artboards.len(), 1); + let ab = doc.artboards[0].rect; + assert_eq!((ab.width().round(), ab.height().round()), (595.0, 842.0)); + // Bottom to top: the layer drawn first is at the bottom. + let names: Vec = doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + assert_eq!(names, ["Art", "Top"]); + let art = doc.layers[0].children().unwrap(); + assert_eq!(art.len(), 2); + assert!(matches!(art[1].kind, NodeKind::Group { .. }), "the group drawn after the red square is above it"); + let mut all = Vec::new(); + paths(&doc.layers, &mut all); + assert_eq!(all.len(), 4); + // The red square: 100 mm on a side, centered on the page, with a fill and a stroke. + let red = &all[0]; + let b = doc.bounds_of(&[red.id], false).unwrap(); + let mm = 72.0 / 25.4; + assert!((b.width() - 100.0 * mm).abs() < 0.01 && (b.center().x - ab.center().x).abs() < 0.01, "{b:?}"); + assert_eq!(red.appearance.items.len(), 2); + // The square whose line type draws no outline has a fill only. + assert_eq!(all[1].appearance.items.len(), 1); +} + +#[test] +fn detection_by_content_and_place() { + let bytes = sample(); + let mut s = Session::new(); + // A renamed file is found by its content, and a .cmx extension alone reads it as one. + assert_eq!(open_bytes(&mut s, "renamed.bin", &bytes, None).unwrap()["format"], "cmx"); + assert_eq!(detect("drawing.png", &bytes).map(|f| f.id), Some("cmx")); + assert_eq!(detect("drawing.cmx", b"").map(|f| f.id), Some("cmx")); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + s.execute("file.place", &json!({"name":"art.cmx", "dataBase64":vectorcraft_format::base64_encode(&bytes)})).unwrap(); + assert!(s.doc().unwrap().doc.layers.iter().any(|l| !l.children().unwrap().is_empty())); + let f = format("cmx").unwrap(); + assert!(f.read && !f.write); + assert!(OPEN_EXTS.contains(&"cmx") && PLACE_EXTS.contains(&"cmx") && UNASSOCIATED_EXTS.contains(&"cmx")); + assert!(!SAVE_FORMATS.contains(&"cmx")); +} + +#[test] +fn what_is_left_out_is_named_in_the_warnings() { + let mut children = vec![cont(b'4', 1e-7)]; + children.push(page(&[ + begin_page(None), + begin_layer("L", None), + instr(66, &fields(&[field(1, &[0; 8])])), + square(&attrs_fill_type(2), 0, 0, 1000), + square(&attrs(Some(1), Some(1), true), 0, 0, 1000), + ])); + children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rota"))); + children.push(arrowheads(&[(1, 0)])); + let mut s = Session::new(); + let w = warnings(&open_bytes(&mut s, "drawing.cmx", &riff(&children), None).unwrap()); + assert_eq!( + w, + [ + "CMX text, images, rectangles, ellipses, clipping paths and other objects VectorCraft doesn't read yet were left out", + "CMX fills other than uniform colors were left out", + "CMX outline arrowheads were left out", + "CMX lenses were not applied", + ] + ); +} + +#[test] +fn a_file_the_open_left_things_out_of_is_not_written_over_unasked() { + let d = std::env::temp_dir().join(format!("vc-cmx-loss-{}", std::process::id())); + std::fs::create_dir_all(&d).unwrap(); + let src = d.join("drawing.cmx"); + let mut children = vec![cont(b'4', 1e-7), page(&[begin_page(None), square(&attrs_fill_type(2), 0, 0, 1000)])]; + children.extend(tables()); + let original = riff(&children); + std::fs::write(&src, &original).unwrap(); + let mut s = Session::new(); + s.execute("document.open", &json!({ "path": src.to_string_lossy() })).unwrap(); + let e = s.execute("document.export", &json!({ "path": src.to_string_lossy(), "format": "svg" })).unwrap_err().to_string(); + assert!(e.contains("acknowledgeLoss"), "{e}"); + assert_eq!(std::fs::read(&src).unwrap(), original); + std::fs::remove_dir_all(d).ok(); +} + +#[test] +fn files_that_are_not_read_say_why() { + let mut s = Session::new(); + let mut rifx = sample(); + rifx[..4].copy_from_slice(b"RIFX"); + let e = open_bytes(&mut s, "a.cmx", &rifx, None).unwrap_err().to_string(); + assert!(e.contains("this CMX file can't be read (big-endian CMX files are not read)"), "{e}"); + let e = open_bytes(&mut s, "b.cmx", &riff(&[cont(b'2', 1e-3)]), None).unwrap_err().to_string(); + assert!(e.contains("this CMX file can't be read (CMX files with 16-bit coordinates are not read)"), "{e}"); + let e = open_bytes(&mut s, "c.cmx", &riff(&[]), None).unwrap_err().to_string(); + assert!(e.contains("this CMX file can't be read (damaged CMX header)"), "{e}"); + let e = open_bytes(&mut s, "d.cmx", b"not a cmx file", None).unwrap_err().to_string(); + assert!(e.contains("this CMX file can't be read (not a CMX file)"), "{e}"); +} + +#[test] +fn a_layer_without_a_name_is_named_by_its_place() { + // An empty layer, which is left out, then a layer named only by spaces: it comes in unnamed, + // and the importer numbers it by its place among the layers it keeps, as for a `.cdr` drawing. + let p = page(&[ + begin_page(None), + begin_layer("Grid", None), + end_layer(), + begin_layer(" ", None), + square(&attrs(Some(2), None, false), 0, 0, 1000), + end_layer(), + ]); + let mut children = vec![cont(b'4', 1e-7), p]; + children.extend(tables()); + let mut s = Session::new(); + let r = open_bytes(&mut s, "drawing.cmx", &riff(&children), None).unwrap(); + assert!(warnings(&r).is_empty(), "{r}"); + let names: Vec = s.doc().unwrap().doc.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect(); + assert_eq!(names, ["Layer 1"]); +} 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_pdf13.rs b/crates/engine/src/cmd/fileio/tests_pdf13.rs index 99daa023a5..7c0aa4a74b 100644 --- a/crates/engine/src/cmd/fileio/tests_pdf13.rs +++ b/crates/engine/src/cmd/fileio/tests_pdf13.rs @@ -166,6 +166,14 @@ fn the_flattener_preset_and_options_apply() { assert!(!transparency(&kept).is_empty() && !warnings.iter().any(|w| w.contains("flattened"))); } +#[test] +fn pdf_1_3_files_flatten_without_alpha_whatever_the_options() { + let mut s = session(); + let p = json!({"compatibility": "1.3", "preserveEditing": false, "flattener": {"balance": 0, "preserveAlpha": true}}); + let (pdf, _) = export(&mut s, p); + assert!(pdf.starts_with(b"%PDF-1.3") && transparency(&pdf).is_empty()); +} + #[test] fn pdf_1_3_files_are_encrypted_with_40_bit_rc4_and_can_be_linearised() { let mut s = session(); diff --git a/crates/engine/src/cmd/fileio/tests_pdfx.rs b/crates/engine/src/cmd/fileio/tests_pdfx.rs index 188e0158ca..424bf3a6b6 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfx.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfx.rs @@ -171,6 +171,226 @@ fn a_pdfx_file_that_leaves_out_the_document_bleed_warns() { assert!(!left_out(&warnings), "{warnings:?}"); } +/// A 200 × 100 pt document with no art, bleed `bleed` (pt). +fn bleed_session(bleed: Value) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + s.execute("document.setup", &json!({ "bleed": bleed })).unwrap(); + s +} + +/// A rectangle from (x0, y0) to (x1, y1) without a stroke, on the current layer. +fn plain_rect(s: &mut Session, [x0, y0, x1, y1]: [f64; 4]) -> Value { + let id = s.execute("shape.rectangle", &json!({"x": x0, "y": y0, "width": x1 - x0, "height": y1 - y0})).unwrap()["id"].clone(); + s.execute("paint.setStroke", &json!({"ids": [id], "none": true})).unwrap(); + id +} + +/// The warnings of a PDF that carries the document's bleed that say art stops short of it. +fn short_of_bleed(s: &mut Session) -> Vec { + let (_, warnings) = pdf(s, json!({"bleed": {"useDocument": true}})); + warnings.into_iter().filter(|w| super::pdf::is_short_of_bleed(w)).collect() +} + +const MM: f64 = 72.0 / 25.4; + +/// A bleed raised from 2 mm to 5 mm leaves a background that filled the old bleed, and a band +/// placed against the trim edge, short of the new one: the export warns once, counting both. +#[test] +fn art_that_reaches_the_trim_edge_but_stops_short_of_the_bleed_warns() { + let mut s = bleed_session(json!(2.0 * MM)); + let (b, w, h) = (2.0 * MM, 200.0, 100.0); + plain_rect(&mut s, [-b, -b, w + b, h + b]); + plain_rect(&mut s, [0.0, 0.0, w, 20.0]); + // At 2 mm the background reaches the bleed; the band stops at the trim edge. + assert_eq!(short_of_bleed(&mut s), ["1 object reaches the trim edge but stops short of the bleed"]); + s.execute("document.setup", &json!({"bleed": 5.0 * MM})).unwrap(); + assert_eq!(short_of_bleed(&mut s), ["2 objects reach the trim edge but stop short of the bleed"]); + // The PDF/X presets carry the document's bleed. + let (_, warnings) = pdf(&mut s, json!({"preset": "PDF/X-4:2010"})); + assert!(warnings.iter().any(|w| super::pdf::is_short_of_bleed(w)), "{warnings:?}"); + // A PDF/X file with a bleed on the top alone leaves out the rest of the document's bleed, and + // the background and the band stop short at the top: the warning comes right after + // BLEED_LEFT_OUT. + let (_, warnings) = pdf(&mut s, json!({"standard": "pdfX4", "bleed": {"top": 9}})); + assert_eq!(warnings.first().map(String::as_str), Some(super::pdf::BLEED_LEFT_OUT), "{warnings:?}"); + assert_eq!(warnings.get(1).map(String::as_str), Some("2 objects reach the trim edge but stop short of the bleed"), "{warnings:?}"); + // A page without the bleed (the default preset) doesn't warn, and neither does a page of the art's bounds. + let (_, warnings) = pdf(&mut s, json!({})); + assert!(!warnings.iter().any(|w| super::pdf::is_short_of_bleed(w)), "{warnings:?}"); + let (_, warnings) = pdf(&mut s, json!({"bleed": {"useDocument": true}, "useArtboards": false})); + assert!(!warnings.iter().any(|w| super::pdf::is_short_of_bleed(w)), "{warnings:?}"); + // An explicit bleed counts too, and the Summary lists the warning. + let (_, warnings) = pdf(&mut s, json!({"bleed": {"top": 9, "bottom": 9, "left": 9, "right": 9}})); + assert!(warnings.iter().any(|w| super::pdf::is_short_of_bleed(w)), "{warnings:?}"); + let v = s.execute("document.pdfSettings", &json!({"bleed": {"useDocument": true}, "includeDocument": true})).unwrap(); + assert!(v["warnings"].as_array().unwrap().iter().any(|w| super::pdf::is_short_of_bleed(w.as_str().unwrap())), "{v}"); + // A group counts once, measured by its visible members: a hidden member that fills the bleed + // doesn't hide a visible one at the trim edge. + let mut s = bleed_session(json!(9)); + let fill = plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]); + let band = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + let side = plain_rect(&mut s, [0.0, 40.0, 20.0, 60.0]); + s.execute("object.group", &json!({"ids": [fill, band, side]})).unwrap(); + s.execute("object.hide", &json!({"ids": [fill]})).unwrap(); + assert_eq!(short_of_bleed(&mut s), ["1 object reaches the trim edge but stops short of the bleed"]); + // A clip group is measured by the art inside its clipping path, not by a clipping path that + // reaches the bleed edge. + let mut s = bleed_session(json!(9)); + let art = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + let clip = plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]); + s.execute("select.set", &json!({"ids": [art, clip]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + assert_eq!(short_of_bleed(&mut s).len(), 1); + // A clipping path that paints a fill reaching the trim edge counts, though the art it clips is + // inside: in a clip group, and as an object of its own in a clipping layer. + let mut s = bleed_session(json!(9)); + let art = plain_rect(&mut s, [20.0, 30.0, 60.0, 60.0]); + let clip = plain_rect(&mut s, [0.0, 0.0, 200.0, 100.0]); + s.execute("select.set", &json!({"ids": [art, clip]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + assert!(short_of_bleed(&mut s).is_empty()); + s.execute("paint.setFill", &json!({"ids": [clip], "color": "#ff0000"})).unwrap(); + assert_eq!(short_of_bleed(&mut s).len(), 1); + let mut s = bleed_session(json!(9)); + let clipping = s.execute("layer.new", &json!({})).unwrap()["id"].clone(); + plain_rect(&mut s, [20.0, 30.0, 60.0, 60.0]); + let clip = plain_rect(&mut s, [0.0, 0.0, 200.0, 100.0]); + s.execute("layer.clippingMask.toggle", &json!({"id": clipping})).unwrap(); + assert!(short_of_bleed(&mut s).is_empty()); + s.execute("paint.setFill", &json!({"ids": [clip], "color": "#ff0000"})).unwrap(); + assert_eq!(short_of_bleed(&mut s).len(), 1); + // A hidden brushed member doesn't keep a group's visible art at the trim edge from counting. + let mut s = bleed_session(json!(9)); + let brushed = plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]); + s.execute("brush.apply", &json!({"ids": [brushed], "name": "Charcoal"})).unwrap(); + let band = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + s.execute("object.group", &json!({"ids": [brushed, band]})).unwrap(); + s.execute("object.hide", &json!({"ids": [brushed]})).unwrap(); + assert_eq!(short_of_bleed(&mut s).len(), 1); + // A clipping layer clips its art to the clipping path's geometry, not to the stroke around it: + // the stroke reaches the trim edge, but the art it clips stops 5 pt inside. + let mut s = bleed_session(json!(9)); + let clipping = s.execute("layer.new", &json!({})).unwrap()["id"].clone(); + plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]); + let clip = plain_rect(&mut s, [5.0, 5.0, 195.0, 95.0]); + s.execute("layer.clippingMask.toggle", &json!({"id": clipping})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [clip], "color": "#ff0000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [clip], "weight": 10})).unwrap(); + assert_eq!(short_of_bleed(&mut s), ["1 object reaches the trim edge but stops short of the bleed"]); +} + +/// No warning for art that already fills the bleed, art inside the trim, a document without a +/// bleed, art on hidden, non-printing or template layers, a side without a bleed, area type, a +/// masked object, or a `.ai` save. +#[test] +fn art_that_fills_the_bleed_or_stays_inside_does_not_warn() { + let mut s = bleed_session(json!(9)); + plain_rect(&mut s, [-9.0, -9.0, 209.0, 109.0]); + plain_rect(&mut s, [-20.0, 40.0, 50.0, 60.0]); + plain_rect(&mut s, [10.0, 10.0, 190.0, 90.0]); + assert!(short_of_bleed(&mut s).is_empty()); + // A document without a bleed has nothing to fall short of. + let mut s = bleed_session(json!(0)); + plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + assert!(short_of_bleed(&mut s).is_empty()); + // Layers that don't print. + for props in [json!({"visible": false}), json!({"printable": false}), json!({"template": true})] { + let mut s = bleed_session(json!(9)); + let layer = s.execute("layer.new", &json!({})).unwrap()["id"].clone(); + plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + let mut p = props.clone(); + p["id"] = layer; + s.execute("layer.setProps", &p).unwrap(); + assert!(short_of_bleed(&mut s).is_empty(), "{props}"); + } + // A hidden object, and a group whose hidden member is the one at the trim edge. + let mut s = bleed_session(json!(9)); + let id = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + s.execute("object.hide", &json!({"ids": [id]})).unwrap(); + assert!(short_of_bleed(&mut s).is_empty()); + let mut s = bleed_session(json!(9)); + let edge = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + let inside = plain_rect(&mut s, [10.0, 30.0, 50.0, 60.0]); + s.execute("object.group", &json!({"ids": [edge, inside]})).unwrap(); + s.execute("object.hide", &json!({"ids": [edge]})).unwrap(); + assert!(short_of_bleed(&mut s).is_empty()); + // Art that lies in the bleed alone, away from the trim edge. + let mut s = bleed_session(json!(9)); + plain_rect(&mut s, [20.0, -5.0, 60.0, -3.0]); + assert!(short_of_bleed(&mut s).is_empty()); + // A guide in a group at the trim edge. + let mut s = bleed_session(json!(9)); + let guide = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + s.execute("view.guides.make", &json!({})).unwrap(); + let inside = plain_rect(&mut s, [10.0, 30.0, 50.0, 60.0]); + s.execute("object.group", &json!({"ids": [guide, inside]})).unwrap(); + assert!(short_of_bleed(&mut s).is_empty()); + // A brushed stroke, whose brush art can paint past its visual bounds, is not measured. + let mut s = bleed_session(json!(9)); + let id = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + s.execute("brush.apply", &json!({"ids": [id], "name": "Charcoal"})).unwrap(); + assert!(short_of_bleed(&mut s).is_empty()); + // A path with no fill and no stroke paints nothing. + let mut s = bleed_session(json!(9)); + let id = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + s.execute("paint.setFill", &json!({"ids": [id], "none": true})).unwrap(); + assert!(short_of_bleed(&mut s).is_empty()); + // An object at 0% opacity draws nothing. + let mut s = bleed_session(json!(9)); + let id = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + s.execute("object.setProps", &json!({"ids": [id], "opacity": 0})).unwrap(); + assert!(short_of_bleed(&mut s).is_empty()); + // A clipping layer whose clipping path lies inside the trim draws none of its art at the edge. + let mut s = bleed_session(json!(9)); + let clipping = s.execute("layer.new", &json!({})).unwrap()["id"].clone(); + plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + plain_rect(&mut s, [10.0, 10.0, 60.0, 60.0]); + s.execute("layer.clippingMask.toggle", &json!({"id": clipping})).unwrap(); + assert!(short_of_bleed(&mut s).is_empty()); + // A bleed on the top alone: art short at the left doesn't count, art short at the top does. + let mut s = bleed_session(json!([9, 0, 0, 0])); + plain_rect(&mut s, [0.0, 30.0, 40.0, 60.0]); + assert!(short_of_bleed(&mut s).is_empty()); + plain_rect(&mut s, [60.0, 0.0, 100.0, 40.0]); + assert_eq!(short_of_bleed(&mut s).len(), 1); + // Area type is bounded by its frame, not its glyphs: a frame at the trim edge is not measured. + let mut s = bleed_session(json!(9)); + s.execute("text.create", &json!({"x": 0, "y": 0, "text": "Title", "size": 12, "area": {"width": 200, "height": 40}})).unwrap(); + assert!(short_of_bleed(&mut s).is_empty()); + // An opacity mask decides what shows of the object, so a masked object is not measured. + let mut s = bleed_session(json!(9)); + let band = plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + let mask = plain_rect(&mut s, [20.0, 30.0, 60.0, 60.0]); + s.execute("transparency.makeOpacityMask", &json!({"ids": [band, mask]})).unwrap(); + assert!(short_of_bleed(&mut s).is_empty()); + // A `.ai` save with a bleed doesn't warn: the check is PDF export's. + let mut s = bleed_session(json!(9)); + plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + assert_eq!(short_of_bleed(&mut s).len(), 1); + let r = s.execute("document.export", &json!({"format": "ai", "bleed": {"useDocument": true}})).unwrap(); + assert!(!r["warnings"].to_string().contains("short of the bleed"), "{}", r["warnings"]); +} + +/// The warning changes neither the art nor the page boxes. +#[test] +fn the_bleed_warning_changes_no_geometry_and_no_page_box() { + let mut s = bleed_session(json!(9)); + plain_rect(&mut s, [0.0, 0.0, 200.0, 20.0]); + let before = s.doc().unwrap().doc.clone(); + let v = s.execute("document.exportPdf", &json!({"bleed": {"useDocument": true}})).unwrap(); + assert!(v["warnings"].as_array().unwrap().iter().any(|w| super::pdf::is_short_of_bleed(w.as_str().unwrap())), "{v}"); + assert_eq!(s.doc().unwrap().doc, before); + let info = s.execute("document.pdfInfo", &json!({"name": "x.pdf", "dataBase64": v["dataBase64"]})).unwrap(); + let boxes = &info["pageInfo"][0]["boxes"]; + let side = |b: &Value| { + let n: Vec = b.as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect(); + (((n[2] - n[0]) * 100.0).round() / 100.0, ((n[3] - n[1]) * 100.0).round() / 100.0) + }; + assert_eq!(side(&boxes["trim"]), (200.0, 100.0), "{info}"); + assert_eq!(side(&boxes["bleed"]), (218.0, 118.0), "{info}"); +} + /// The ink amounts (0..1) `doc` shows at `p` in its images (the topmost image there). fn image_inks_at(doc: &vectorcraft_doc::Document, p: vectorcraft_geom::Point) -> Option<[f32; 4]> { fn visit(n: &vectorcraft_doc::Node, out: &mut Vec) { diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index 249a3f320c..881519fbda 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -602,6 +602,56 @@ fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() { assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again"); } +/// Unembed keeps the clip group of the clipping path an embedded PSD file's image came with, with a +/// path and with a folder, and so do relinking to the written file, placing it and opening it. +#[test] +fn unembed_keeps_the_clipping_path_of_an_embedded_psd() { + let dir = vectorcraft_testkit::TempDir::new("psd-unembed-clip"); + // An RGB file is kept as a PNG, a CMYK one as a TIFF. + let cmyk = psd(1, 4, (100, 50), 8, 4, &[], &triangle_resources(), &[], &raw(&[&[0; 5000], &[255; 5000], &[255; 5000], &[0; 5000]])); + let files = [("rgb", red_psd(&triangle_resources())), ("cmyk", cmyk)]; + for ((kind, file), folder) in files.iter().flat_map(|f| [(f, false), (f, true)]) { + let data = vectorcraft_format::base64_encode(file); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [50, 25]})).unwrap(); + let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap())); + let before = clip_group(&s.doc().unwrap().doc, group); + // Without an extension the image is written in the format it is stored in. + let path = if folder { + let out = dir.join(format!("folder-{kind}")); + std::fs::create_dir_all(&out).unwrap(); + let r = s.execute("links.unembed", &json!({"ids": [image.0], "folder": out})).unwrap(); + r["unembedded"][0]["path"].as_str().unwrap().to_string() + } else { + let r = s.execute("links.unembed", &json!({"id": image.0, "path": dir.join(format!("written-{kind}"))})).unwrap(); + r["path"].as_str().unwrap().to_string() + }; + let ext = if *kind == "rgb" { ["png"].as_slice() } else { ["tif", "tiff"].as_slice() }; + assert!(ext.contains(&super::extension(&path).as_str()), "{kind}: {path}"); + for step in ["unembed", "relink"] { + if step == "relink" { + s.execute("links.relink", &json!({"ids": [image.0], "path": path})).unwrap(); + } + let d = &s.doc().unwrap().doc; + let NodeKind::Image(im) = &d.node(image).unwrap().kind else { panic!("an image") }; + assert!(im.link.is_some(), "linked to the file written"); + assert_eq!(clip_group(d, group), before, "{kind}, {step}, folder: {folder}"); + } + // Placing the written file gives the same clip group as placing the PSD file did. + let r = s.execute("file.place", &json!({"path": path, "at": [50, 25]})).unwrap(); + let placed = NodeId(r["ids"][0].as_u64().unwrap()); + let (anchors, even_odd, _) = clip_group(&s.doc().unwrap().doc, placed); + assert_eq!((anchors, even_odd), (before.0.clone(), true), "{kind}, place"); + // Opening it gives a document of the image in that clip group. + s.execute("document.open", &json!({"path": path})).unwrap(); + let d = &s.doc().unwrap().doc; + let top = d.layers[0].children().and_then(|c| c.first()).map(|c| c.id).expect("an object"); + let (anchors, even_odd, _) = clip_group(d, top); + assert_eq!((anchors, even_odd), (before.0.clone(), true), "{kind}, open"); + } +} + /// The PNG a PSD file's merged image is kept as holds the clipping path the file names, and only a /// text chunk within the size limit that reads as a path gives one back. #[test] diff --git a/crates/engine/src/cmd/fileio/tests_screens.rs b/crates/engine/src/cmd/fileio/tests_screens.rs index c7c258b304..74356b6f31 100644 --- a/crates/engine/src/cmd/fileio/tests_screens.rs +++ b/crates/engine/src/cmd/fileio/tests_screens.rs @@ -610,6 +610,35 @@ fn include_bleed_pdfx_rows_do_not_warn_about_the_bleed() { assert!(warned(&export(&mut s, json!({"includeBleed": true, "selection": "one", "formats": row})))); } +/// A PDF row with a bleed warns about art that reaches an artboard's edge and stops short of the +/// bleed, with or without Include Bleed: the page's trim is the artboard either way. It doesn't +/// warn about art that reaches the bleed, or on a page of a selection's bounds. +#[test] +fn pdf_rows_warn_about_art_short_of_the_bleed_on_artboard_pages_only() { + let warned = |r: &Value| r["warnings"].as_array().unwrap().iter().any(|w| super::pdf::is_short_of_bleed(w.as_str().unwrap())); + let row = json!([{"format": "pdf", "bleed": {"useDocument": true}}]); + let mut s = session(1); + s.execute("document.setup", &json!({"bleed": 6})).unwrap(); + // Against the artboard's top edge. + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 10})).unwrap(); + assert!(warned(&export(&mut s, json!({"formats": row})))); + assert!(warned(&export(&mut s, json!({"includeBleed": true, "formats": row})))); + assert!(warned(&export(&mut s, json!({"includeBleed": true, "formats": [{"format": "pdf"}]}))), "the row takes the document's bleed"); + assert!(!warned(&export(&mut s, json!({"selection": "one", "formats": row})))); + assert!(!warned(&export(&mut s, json!({"includeBleed": true, "selection": "one", "formats": row})))); + // Out to the bleed edge on the top, left and right. + let mut s = session(1); + s.execute("document.setup", &json!({"bleed": 6})).unwrap(); + s.execute("shape.rectangle", &json!({"x": -6, "y": -6, "width": 52, "height": 16})).unwrap(); + assert!(!warned(&export(&mut s, json!({"formats": row})))); + assert!(!warned(&export(&mut s, json!({"includeBleed": true, "formats": row})))); + // Without a document bleed, a row's own bleed warns. + let mut s = session(1); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 10})).unwrap(); + let row = json!([{"format": "pdf", "bleed": {"top": 6, "bottom": 6, "left": 6, "right": 6}}]); + assert!(warned(&export(&mut s, json!({"includeBleed": true, "formats": row})))); +} + /// Each `[x0 y0 x1 y1]` that follows `key` in a PDF's bytes, in the order the file has them, read /// as text without VectorCraft's PDF reader (PDF 32000-1:2008, 14.11.2, Page Boundaries). fn raw_boxes(pdf: &[u8], key: &str) -> Vec<[f64; 4]> { diff --git a/crates/engine/src/cmd/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/freeform.rs b/crates/engine/src/cmd/freeform.rs index 71a5e36ccf..b238dd865a 100644 --- a/crates/engine/src/cmd/freeform.rs +++ b/crates/engine/src/cmd/freeform.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Add Freeform Point", [], None, - "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored → {index}", + "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its points); the points on a label's characters are not stored → {index}", has_doc, add_point ), @@ -28,7 +28,7 @@ pub fn specs() -> Vec { "Edit Freeform Point", [], None, - "{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}", + "{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}", has_doc, set_point ), @@ -37,7 +37,7 @@ pub fn specs() -> Vec { "Delete Freeform Point", [], None, - "{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go → {index}", + "{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go → {index}", has_doc, delete_point ), @@ -46,7 +46,7 @@ pub fn specs() -> Vec { "Add Freeform Line", [], None, - "{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order → {line}", + "{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order → {line}", has_doc, add_line ), @@ -55,7 +55,7 @@ pub fn specs() -> Vec { "Split Freeform Line", [], None, - "{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it → {index}", + "{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it → {index}", has_doc, split_line ), @@ -182,8 +182,9 @@ fn edit(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freefor let item = item_target(s, p, cmd)?; let stroke = edits_stroke(s, p, item, !s.fill_active, cmd)?; let item = item.of_kind(s, !stroke); - // The art of a graph design in a series keeps the design's gradient. - let ids = super::appearance::without_design_art(&s.doc()?.doc, item.targets(s, p)?, cmd)?; + // The art of a graph design in a series keeps the design's gradient; a Live Paint group's fill is on its faces and its + // stroke on its edges. + let ids = super::appearance::without_design_art(&s.doc()?.doc, item.targets_for(s, p, !stroke)?, cmd)?; if ids.is_empty() { return Err(bad(cmd, "select an object with a freeform gradient")); } diff --git a/crates/engine/src/cmd/globaledit.rs b/crates/engine/src/cmd/globaledit.rs index 29fbf97fac..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) { @@ -781,6 +781,7 @@ 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, 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. diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index af0f4cfcda..746749235b 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "Gradient", ["Window", "Gradient"], None, - "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label", + "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. Without `item`, a Live Paint group's faces take a fill edit and its edges take a stroke edit. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the paint the bucket paints with)", has_doc, edit_gradient ), @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Gradient Vector", [], None, - "{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without the placement this command sets, fitted to each label", + "{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without the placement this command sets, fitted to each label; without item, a Live Paint group's faces take a fill edit and its edges take a stroke edit", has_doc, set_gradient_geom ), @@ -42,7 +42,7 @@ pub fn specs() -> Vec { "Select Gradient Stop", [], None, - "{index: stop index (0 = the start) | null to clear} select a stop of the gradient behind the active proxy (the first selected object's, else the default paint): the stop the Gradient tool's annotator, the Gradient and Color panels and Delete/arrow keys act on; refused while an object of a symbol instance's art is selected → {index}", + "{index: stop index (0 = the start) | null to clear} select a stop of the gradient behind the active proxy (the first selected object's, else the default paint; the default paint's while the Live Paint Bucket is the active tool): the stop the Gradient tool's annotator, the Gradient and Color panels and Delete/arrow keys act on; refused while an object of a symbol instance's art is selected, except while the Live Paint Bucket is the active tool → {index}", always, select_stop ), @@ -61,7 +61,9 @@ pub(crate) fn active_gradient(s: &Session) -> Option { fn select_stop(s: &mut Session, p: &Value) -> Result { const C: &str = "gradient.selectStop"; // No document is needed for the default paint's gradient, so this does not use `refuse_symbol_part`. - if s.active().is_some_and(|st| st.selection.symbol_part.is_some()) { + // While the Live Paint Bucket is active the proxies show the default paint, whose stops can be + // selected with a part picked. + if s.tool_id() != super::paint::LIVE_PAINT_BUCKET && s.active().is_some_and(|st| st.selection.symbol_part.is_some()) { return Err(super::brushsym::part_only()); } let index = match p.get("index") { @@ -82,15 +84,21 @@ fn select_stop(s: &mut Session, p: &Value) -> Result { /// Whose gradient a selected stop belongs to: the active document, its first selected object /// (None: the default paint), whether a part of a symbol instance's art is picked, the proxy in -/// front and the Appearance panel's active item. Selecting other art, picking a part of the -/// instance, toggling the proxy or picking another item leaves no stop selected. +/// front, the Appearance panel's active item and whether the Live Paint Bucket is the active tool +/// (its proxies show the default paint). Selecting other art, picking a part of the instance, +/// toggling the proxy, picking another item or choosing the bucket or leaving it leaves no stop +/// selected. #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct StopOwner { doc: Option, object: Option, + /// The object whose paint the active proxy shows: a Live Paint group without faces (or edges) + /// first in the selection shows the next object's. + source: Option, part: bool, fill: bool, item: Option, + bucket: bool, } impl StopOwner { @@ -99,9 +107,11 @@ impl StopOwner { Self { doc: s.active, object: st.and_then(|d| d.selection.objects.first().copied()), + source: s.proxy_source(!s.fill_active).map(|(n, _)| n.id), part: st.is_some_and(|d| d.selection.symbol_part.is_some()), fill: s.fill_active, item: s.appearance_item(), + bucket: s.tool_id() == super::paint::LIVE_PAINT_BUCKET, } } } @@ -525,15 +535,18 @@ fn apply_gradient_edit_in_model( fn edit_gradient(s: &mut Session, p: &Value) -> Result { const C: &str = "paint.editGradient"; + // While the Live Paint Bucket is active, the gradient it paints with changes; the selection keeps its own. + let bucket = super::paint::bucket_color_params(s, p, C)?; + let p = bucket.as_ref().unwrap_or(p); let item = item_target(s, p, C)?; let stroke = edits_stroke(s, p, item, !s.fill_active, C)?; check_switches(p, &["reverse", "dither"], C)?; check_numbers(p, &["angle"], C)?; let item = item.of_kind(s, !stroke); - let ids = item.targets(s, p)?; - // Objects were given or selected, even when all of them are graph design art left out below: the stroke mode is then - // not one for new art. - let selected = !ids.is_empty(); + let (ids, skipped) = item.targets_and_skipped(s, p, !stroke)?; + // Objects were given or selected, even when all of them are graph design art left out below, or Live Paint group parts + // of the other kind left out above: the stroke mode is then not one for new art. + let selected = !ids.is_empty() || skipped; let ids = super::appearance::drop_design_art_rows(s, ids, item, !stroke, C)?; // How the gradient lies on a stroke (the panel's Stroke buttons). let mode = match str_param(p, "strokeMode") { @@ -619,7 +632,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { })?; if let Some(m) = mode && !selected - && p.get("ids").is_none() + && (bucket.is_some() || p.get("ids").is_none()) && let Some(st) = s.new_art_stroke_mut() { st.gradient_mode = m; @@ -769,7 +782,10 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result { let item = item.of_kind(s, !stroke); let targets = match item { ItemTarget::Top => { - leaf_targets(s, &super::given_objects(s, p, C)?.map_or_else(|| selected_roots(s), |ids| Ok(outermost(&s.doc()?.doc, ids)))?)? + let roots = super::given_objects(s, p, C)?.map_or_else(|| selected_roots(s), |ids| Ok(outermost(&s.doc()?.doc, ids)))?; + // A Live Paint group's fill gradient is on its faces and its stroke gradient on its edges. + let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &roots, !stroke); + leaf_targets(s, &roots)?.into_iter().filter(|id| !skipped.contains(id)).collect() } _ => item.targets(s, p)?, }; diff --git a/crates/engine/src/cmd/gradpresets.rs b/crates/engine/src/cmd/gradpresets.rs index 037033ea8a..c8eaa07135 100644 --- a/crates/engine/src/cmd/gradpresets.rs +++ b/crates/engine/src/cmd/gradpresets.rs @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Apply Gradient Preset", [], None, - "{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops, method, spread and repeats (a freeform preset's: the first three), and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient → {name, ids: the objects painted (none: only the default changed)}", + "{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops, method, spread and repeats (a freeform preset's: the first three), and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes, by the active proxy) → {name, ids: the objects painted (none: only the default changed)}", has_doc, apply ), @@ -207,6 +207,10 @@ fn apply(s: &mut Session, p: &Value) -> Result { const C: &str = "gradient.presets.apply"; let name = name_param(p, C)?; let preset = s.gradient_preset(name).ok_or_else(|| bad(C, format!("no gradient preset `{name}` (see gradient.presets.list)")))?; + // While the Live Paint Bucket is active, the gradient it paints with changes, chosen by the + // active proxy rather than the selection's Appearance row (as paint.editGradient chooses). + let bucket = super::paint::bucket_color_params(s, p, C)?; + let p = bucket.as_ref().unwrap_or(p); let stroke = edits_stroke(s, p, item_target(s, p, C)?, !s.fill_active, C)?; let g = &preset.gradient; let mut edit = p.clone(); diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index b74dd97454..5d50fb9c39 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -7406,6 +7406,81 @@ fn the_last_label_of_a_kind_edited_together_sets_what_it_keeps() { assert_eq!(kept(&s), "#ff0000"); } +/// A column graph, a 10 pt square with one red fill row, and the category labels Q1, Q2 and Q3: Q1 and Q3 have one red +/// fill row, Q2 a hidden red fill row under a green one, and Q1's row is then painted blue, which the kind keeps. +/// Returns the graph, the square and the three labels. +fn labels_with_hidden_and_shown_rows(s: &mut Session) -> (NodeId, NodeId, [NodeId; 3]) { + use vectorcraft_doc::{AppearanceItem, FillLayer}; + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(s, "column"); + let square = NodeId(s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + let labels = ["Q1", "Q2", "Q3"].map(|t| text_id(s, id, "Axes", t)); + let fill = |hex: &str, visible: bool| { + AppearanceItem::Fill(FillLayer { visible, ..FillLayer::new(Paint::solid(vectorcraft_color::Color::from_hex(hex).unwrap())) }) + }; + s.edit("Rows", |d, _| { + for (l, items) in [ + (square, vec![fill("#ff0000", true)]), + (labels[0], vec![fill("#ff0000", true)]), + (labels[1], vec![fill("#ff0000", false), fill("#00ff00", true)]), + (labels[2], vec![fill("#ff0000", true)]), + ] { + d.node_mut(l).unwrap().appearance.items = items; + } + Ok(()) + }) + .unwrap(); + s.execute("appearance.setItem", &json!({"ids": [labels[0].0], "index": 0, "color": "#0000ff"})).unwrap(); + assert_eq!(kept_category_fill(s, id), Some("#0000ff".into())); + (id, square, labels) +} + +/// The fill of the category label rows graph `id` keeps, as a hex color. +fn kept_category_fill(s: &Session, id: NodeId) -> Option { + spec(s, id).label_styles.categories_rows.and_then(|r| r.paint.fill).and_then(|p| p.color()).map(|c| c.to_hex()) +} + +/// Row edits on several labels at once, with a plain object among them, keep for the kind what the last label whose shown +/// row the edit wrote shows, also when that row comes out as it was; a label whose hidden row the edit wrote is left out. +/// One undo takes it back. Covers `appearance.setItem`, `appearance.duplicateItem` and `paint.setFill` with `item`. +#[test] +fn row_edits_on_several_labels_keep_the_last_written_shown_row() { + let edits = [ + ("appearance.setItem", json!({"index": 0, "color": "#ff0000"})), + ("appearance.duplicateItem", json!({"index": 0})), + ("paint.setFill", json!({"item": 0, "color": "#ff0000"})), + ]; + for (cmd, mut p) in edits { + let mut s = Session::new(); + let (id, square, [_, q2, q3]) = labels_with_hidden_and_shown_rows(&mut s); + // Q3 shows red before and after the edit; Q2 shows green over the hidden row the edit writes. + p["ids"] = json!([q3.0, square.0, q2.0]); + s.execute(cmd, &p).unwrap(); + assert_eq!(kept_category_fill(&s, id), Some("#ff0000".into()), "{cmd}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(kept_category_fill(&s, id), Some("#0000ff".into()), "{cmd}: undo"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(kept_category_fill(&s, id), Some("#ff0000".into()), "{cmd}: redo"); + s.execute("edit.undo", &json!({})).unwrap(); + // Only the hidden row of a label: the kind keeps blue. + let steps = s.doc().unwrap().history.undo.len(); + p["ids"] = json!([square.0, q2.0]); + s.execute(cmd, &p).unwrap(); + assert_eq!(kept_category_fill(&s, id), Some("#0000ff".into()), "{cmd}: hidden row only"); + while s.doc().unwrap().history.undo.len() > steps { + s.execute("edit.undo", &json!({})).unwrap(); + } + // Q2's shown green row, written as it was: the kind keeps green. + p["ids"] = json!([q2.0]); + p[if cmd == "paint.setFill" { "item" } else { "index" }] = json!(1); + if cmd != "appearance.duplicateItem" { + p["color"] = json!("#00ff00"); + } + s.execute(cmd, &p).unwrap(); + assert_eq!(kept_category_fill(&s, id), Some("#00ff00".into()), "{cmd}: the shown row written as it was"); + } +} + /// A label's object opacity and blend mode set without a row (`transparency.set` without `item`) are kept for its kind. #[test] fn a_labels_object_opacity_and_blend_mode_are_kept_for_its_kind() { diff --git a/crates/engine/src/cmd/kinsokusets.rs b/crates/engine/src/cmd/kinsokusets.rs new file mode 100644 index 0000000000..8a62c4d8b0 --- /dev/null +++ b/crates/engine/src/cmd/kinsokusets.rs @@ -0,0 +1,353 @@ +//! Type › Kinsoku Shori Settings…: the document's custom Kinsoku Shori sets +//! ([`vectorcraft_doc::KinsokuSet`]). Each set lists the characters that may not start a line, +//! those that may not end one, the hanging punctuation Burasagari hangs, and the inseparable +//! sequences Bunri-Kinshi keeps together. A paragraph chooses one by name in Kinsoku Set +//! (`text.setFormat {kinsoku: name}`) and holds a copy of it, which an edit of the set replaces. +//! +//! Behavior reference: the help page +//! . +//! The name rules, the limits and Hard as the set a deleted set's paragraphs take are VectorCraft's +//! own. + +use std::collections::HashMap; +use std::sync::Arc; + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::graph::LabelStyles; +use vectorcraft_doc::text::{KINSOKU_CATEGORY_MAX, KINSOKU_NAME_MAX, KINSOKU_SEQUENCE, KINSOKU_SETS_MAX}; +use vectorcraft_doc::{Document, Kinsoku, KinsokuSet, Node, NodeKind, ParaStyle}; + +use super::textstyles::each_node_with_text_mut; +use super::typecmd::refresh_bounds; +use super::{CommandSpec, Result, Session, bad, cmd, has_doc}; + +/// The command Type › Kinsoku Shori Settings…'s OK runs, and the menu item's. +pub const SET: &str = "type.kinsokuSets.set"; + +/// The keys a set may give. +const SET_KEYS: [&str; 6] = ["name", "from", "cannotStart", "cannotEnd", "hanging", "inseparable"]; + +pub fn specs() -> Vec { + vec![ + cmd!( + query "type.kinsokuSets.list", + "Kinsoku Sets", + [], + None, + "{} the active document's custom Kinsoku Shori sets, and the paragraphs, paragraph styles and graphs (in the paragraph attributes they keep for their labels) using each → {sets: [{name, cannotStart: characters, cannotEnd: characters, hanging: characters, inseparable: [sequence], paragraphs, styles, graphs}]}", + has_doc, + list + ), + cmd!( + query "type.kinsokuSets.base", + "Kinsoku Set Base", + [], + None, + "{base: \"none\"|\"hard\"|\"soft\"|name of a custom set (any case), name?} the categories of a built-in or custom set, as a new set based on it starts (Type › Kinsoku Shori Settings…'s New Set): Hard and Soft list the characters they keep off a line's start and end, the East Asian comma and full stop as hanging punctuation, and the pairs Bunri-Kinshi keeps together; None lists nothing → {set: {name, cannotStart, cannotEnd, hanging, inseparable}}", + has_doc, + base + ), + cmd!( + "type.kinsokuSets.set", + "Kinsoku Shori Settings…", + ["Type"], + None, + "{sets: [{name, from?: the name the set had (rename), cannotStart?: characters, cannotEnd?: characters, hanging?: characters, inseparable?: [sequence of 2..16 characters]}]} replace the active document's custom Kinsoku Shori sets (Type › Kinsoku Shori Settings…'s OK), as one undo step, none when nothing changes. Cannot Start Line characters never start a line and Cannot End Line characters never end one; Hanging Punctuation characters hang outside a line's end with Burasagari; while Bunri-Kinshi is on, a line never breaks inside an inseparable sequence. cannotStart, cannotEnd and hanging keep each character once, sorted, and inseparable keeps each sequence once, sorted (a sequence may repeat a character); each category holds at most 4096 characters (the sequences count each of their characters); a control or space character fails the call, as do an unknown key and a `from` the document has no set of. Names are trimmed, unique in any case, at most 128 characters, never None, Hard or Soft; at most 256 sets. A set given the name of a set the document has (any case) and no `from` is that set. Every paragraph and paragraph style using a set takes its new characters and name; one using a set left out takes Hard. The built-in None, Hard and Soft can't be changed or deleted → {sets}", + has_doc, + set + ), + ] +} + +/// Call `f` with every node in `d`'s layers (opacity masks included), symbols, graph designs, +/// pattern tiles and brush art, the trees [`each_node_with_text_mut`] reaches. +fn each_node(d: &Document, f: &mut impl FnMut(&Node)) { + let brushes = vectorcraft_brush::library(d); + let trees = d.layers.iter().map(|l| &**l).chain(d.symbols.iter().map(|s| &*s.art)).chain(d.graph_designs.iter().map(|g| &*g.art)); + let patterns = d.patterns.iter().chain(d.pattern_edit.iter().filter_map(|pe| pe.original.as_ref())); + let trees = trees.chain(patterns.flat_map(|p| p.art.iter().map(|a| &**a))).chain(brushes.iter().flat_map(|b| b.art())); + for tree in trees { + vectorcraft_doc::swatches::walk_with_masks(tree, &mut |n| f(n)); + } +} + +/// Call `f` with every paragraph of the type [`each_node`] reaches. +fn each_paragraph(d: &Document, f: &mut impl FnMut(&ParaStyle)) { + each_node(d, &mut |node| { + if let NodeKind::Text(t) = &node.kind { + (0..t.paragraph_count()).for_each(|i| f(t.para_at(i))); + } + }); +} + +/// How many paragraphs, paragraph styles and graphs (in the paragraph attributes they keep for +/// their labels) use each set of the document, by lowercased name. +fn uses(s: &Session) -> Result> { + let mut n: HashMap = HashMap::new(); + let d = &s.doc()?.doc; + each_paragraph(d, &mut |p| { + if let Some(set) = &p.kinsoku_set { + n.entry(set.name.to_lowercase()).or_default().0 += 1; + } + }); + for st in d.para_styles.iter() { + if let Some(name) = st.attrs.get("kinsoku_set").and_then(|v| v.get("name")).and_then(Value::as_str) { + n.entry(name.to_lowercase()).or_default().1 += 1; + } + } + each_node(d, &mut |node| { + let Some(g) = node.extras().graph.as_deref() else { return }; + let mut l = g.label_styles.clone(); + let mut names: Vec = label_paras(&mut l).filter_map(|p| p.kinsoku_set.as_ref().map(|k| k.name.to_lowercase())).collect(); + names.sort(); + names.dedup(); + for name in names { + n.entry(name).or_default().2 += 1; + } + }); + Ok(n) +} + +fn list(s: &mut Session, _: &Value) -> Result { + let uses = uses(s)?; + let sets: Vec = s + .doc()? + .doc + .kinsoku_sets + .iter() + .map(|set| { + let (paragraphs, styles, graphs) = uses.get(&set.name.to_lowercase()).copied().unwrap_or_default(); + let mut v = json!(set); + if let Some(o) = v.as_object_mut() { + o.insert("paragraphs".into(), json!(paragraphs)); + o.insert("styles".into(), json!(styles)); + o.insert("graphs".into(), json!(graphs)); + } + v + }) + .collect(); + Ok(json!({ "sets": sets })) +} + +/// The set `name` names: a built-in one (`none`, `hard`, `soft`) or a custom set of `sets` (any +/// case). +fn named_base(sets: &[KinsokuSet], name: &str) -> Option { + match name { + "none" => Some(vectorcraft_text::kinsoku_set_from(Kinsoku::None, "")), + "hard" => Some(vectorcraft_text::kinsoku_set_from(Kinsoku::Hard, "")), + "soft" => Some(vectorcraft_text::kinsoku_set_from(Kinsoku::Soft, "")), + _ => KinsokuSet::named(sets, name.trim()).cloned(), + } +} + +fn base(s: &mut Session, p: &Value) -> Result { + const C: &str = "type.kinsokuSets.base"; + let from = p.get("base").and_then(Value::as_str).ok_or_else(|| bad(C, "give base: \"none\", \"hard\", \"soft\" or a set's name"))?; + let mut set = named_base(&s.doc()?.doc.kinsoku_sets, from).ok_or_else(|| bad(C, format!("no Kinsoku set named `{from}`")))?; + set.name = match p.get("name") { + None | Some(Value::Null) => String::new(), + Some(Value::String(n)) => n.clone(), + Some(_) => return Err(bad(C, "name must be text")), + }; + Ok(json!({ "set": set })) +} + +/// A category of single characters from `v` (text, one character after another): empty when left +/// out. Text far longer than a category holds is refused before it is read. +fn chars(v: Option<&Value>, key: &str, name: &str, c: &str) -> Result> { + match v { + None | Some(Value::Null) => Ok(Vec::new()), + Some(Value::String(text)) => { + if text.chars().count() > KINSOKU_CATEGORY_MAX * 4 { + return Err(bad(c, format!("`{name}`: {key} must be at most {KINSOKU_CATEGORY_MAX} characters"))); + } + Ok(text.chars().collect()) + } + Some(_) => Err(bad(c, format!("`{name}`: {key} must be text, one character after another"))), + } +} + +/// Set `v` from command parameters, its name trimmed, with the name it had (`from`, trimmed) when +/// it gives one. +fn parse_set(v: &Value, c: &str) -> Result<(KinsokuSet, Option)> { + let o = v.as_object().ok_or_else(|| bad(c, "each set must be {name, cannotStart?, cannotEnd?, hanging?, inseparable?}"))?; + if let Some(k) = o.keys().find(|k| !SET_KEYS.contains(&k.as_str())) { + return Err(bad(c, format!("unknown key `{k}`; a set takes {}", SET_KEYS.join(", ")))); + } + // A null value is refused rather than read as a key left out. + if let Some(k) = o.iter().find_map(|(k, v)| v.is_null().then_some(k)) { + return Err(bad(c, format!("`{k}` can't be null; leave it out instead"))); + } + let raw = o.get("name").and_then(Value::as_str).ok_or_else(|| bad(c, "each set needs a name"))?; + let name = KinsokuSet::clean_name(raw).ok_or_else(|| { + bad(c, format!("`{raw}` can't name a Kinsoku set (1 to {KINSOKU_NAME_MAX} characters, no control characters, not None, Hard or Soft)")) + })?; + let from = match o.get("from") { + None | Some(Value::Null) => None, + Some(Value::String(f)) => Some(f.trim().to_string()), + Some(_) => return Err(bad(c, format!("`{name}`: from must be text"))), + }; + let inseparable = match o.get("inseparable") { + None | Some(Value::Null) => Vec::new(), + Some(Value::Array(list)) => { + if list.len() > KINSOKU_CATEGORY_MAX { + return Err(bad(c, format!("`{name}`: inseparable: at most {KINSOKU_CATEGORY_MAX} characters in all"))); + } + list.iter() + .map(|s| { + s.as_str().map(str::to_string).ok_or_else(|| { + bad( + c, + format!( + "`{name}`: inseparable must be a list of {} to {} characters each", + KINSOKU_SEQUENCE.start(), + KINSOKU_SEQUENCE.end() + ), + ) + }) + }) + .collect::>>()? + } + Some(_) => return Err(bad(c, format!("`{name}`: inseparable must be a list of sequences"))), + }; + let mut set = KinsokuSet { + cannot_start: chars(o.get("cannotStart"), "cannotStart", &name, c)?, + cannot_end: chars(o.get("cannotEnd"), "cannotEnd", &name, c)?, + hanging: chars(o.get("hanging"), "hanging", &name, c)?, + inseparable, + name, + }; + set.normalize(); + set.check().map_err(|e| bad(c, format!("`{}`: {e}", set.name)))?; + Ok((set, from)) +} + +/// Make `after` the active document's custom sets, as one undo step (none when nothing changes). +/// `renamed` maps the lowercased name of each set of the document that is kept to the index in +/// `after` of what it becomes; a set it leaves out is deleted, and its paragraphs and paragraph +/// styles take Hard. +fn replace(s: &mut Session, after: Vec, renamed: HashMap) -> Result<()> { + let before = s.doc()?.doc.kinsoku_sets.to_vec(); + let after_arcs: Vec> = after.iter().cloned().map(Arc::new).collect(); + // The paragraph value of each set of the document as it was: the new set, or none (Hard). + let next = |old: &KinsokuSet| -> Option>> { + let key = old.name.to_lowercase(); + before.iter().any(|b| b.name.to_lowercase() == key).then(|| renamed.get(&key).and_then(|&i| after_arcs.get(i).cloned())) + }; + let fix = |p: &mut ParaStyle| -> bool { + let Some(old) = p.kinsoku_set.as_deref() else { return false }; + let Some(new) = next(old) else { return false }; + if new.as_deref() == Some(old) { + return false; + } + if new.is_none() { + p.kinsoku = Kinsoku::Hard; + } + p.kinsoku_set = new; + true + }; + let mut texts_change = false; + each_paragraph(&s.doc()?.doc, &mut |p| texts_change |= !texts_change && fix(&mut p.clone())); + // A graph draws its labels again from the paragraph attributes it keeps for them. + let fix_labels = |l: &mut LabelStyles| label_paras(l).fold(false, |changed, p| fix(p) | changed); + each_node(&s.doc()?.doc, &mut |n| { + texts_change |= !texts_change && n.extras().graph.as_deref().is_some_and(|g| fix_labels(&mut g.label_styles.clone())); + }); + let style_attrs = |attrs: &Map| -> Option> { + let old: KinsokuSet = serde_json::from_value(attrs.get("kinsoku_set")?.clone()).ok()?; + let new = next(&old)?; + if new.as_deref() == Some(&old) { + return None; + } + let mut m = attrs.clone(); + match new { + Some(set) => m.insert("kinsoku_set".into(), json!(set)), + None => { + m.insert("kinsoku".into(), json!(Kinsoku::Hard)); + m.insert("kinsoku_set".into(), Value::Null) + } + }; + Some(m) + }; + let styles_change = s.doc()?.doc.para_styles.iter().any(|st| style_attrs(&st.attrs).is_some()); + if before == after && !texts_change && !styles_change { + return Ok(()); + } + s.edit("Kinsoku Shori Settings", |d, _| { + *d.kinsoku_sets = after.clone(); + for st in d.para_styles.iter_mut() { + if let Some(m) = style_attrs(&st.attrs) { + st.attrs = m; + } + } + each_node_with_text_mut(d, &mut |n| { + if let Some(g) = n.extras_if_any().and_then(|e| e.graph.as_deref_mut()) { + fix_labels(&mut g.label_styles); + } + if let NodeKind::Text(t) = &mut n.kind { + let mut changed = false; + for p in t.para_styles_mut() { + changed |= fix(p); + } + if changed { + refresh_bounds(t); + } + } + Ok(()) + }) + }) +} + +/// The paragraph attributes graph label styles `l` keep: the value axis, the categories and the +/// legend. +fn label_paras(l: &mut LabelStyles) -> impl Iterator { + [&mut l.values_para, &mut l.categories_para, &mut l.legend_para].into_iter().flatten() +} + +fn set(s: &mut Session, p: &Value) -> Result { + let list = + p.get("sets").and_then(Value::as_array).ok_or_else(|| bad(SET, "give sets: [{name, cannotStart?, cannotEnd?, hanging?, inseparable?}…]"))?; + if list.len() > KINSOKU_SETS_MAX { + return Err(bad(SET, format!("a document keeps at most {KINSOKU_SETS_MAX} Kinsoku sets"))); + } + let parsed = list.iter().map(|v| parse_set(v, SET)).collect::>>()?; + let mut names = std::collections::HashSet::new(); + for (set, _) in &parsed { + if !names.insert(set.name.to_lowercase()) { + return Err(bad(SET, format!("two Kinsoku sets are named `{}`", set.name))); + } + } + let before = s.doc()?.doc.kinsoku_sets.to_vec(); + let has = |n: &str| before.iter().any(|b| KinsokuSet::same_name(&b.name, n)); + // Which set of the document each given set continues: the one `from` names, else the one of + // its own name that no other set's `from` claims. + let mut renamed: HashMap = HashMap::new(); + for (i, (set, from)) in parsed.iter().enumerate() { + if let Some(f) = from { + if !has(f) { + return Err(bad(SET, format!("`{}`: the document has no Kinsoku set named `{f}`", set.name))); + } + if renamed.insert(f.to_lowercase(), i).is_some() { + return Err(bad(SET, format!("two Kinsoku sets come from `{f}`"))); + } + } + } + for (i, (set, from)) in parsed.iter().enumerate() { + let key = set.name.to_lowercase(); + if from.is_none() && has(&set.name) && !renamed.contains_key(&key) { + renamed.insert(key, i); + } + } + let after: Vec = parsed.into_iter().map(|(set, _)| set).collect(); + replace(s, after.clone(), renamed)?; + Ok(json!({ "sets": after })) +} + +/// The custom set of the active document that `text.setFormat`'s `kinsoku` names (any case), as a +/// paragraph holds it. +pub(crate) fn chosen(s: &Session, name: &str) -> Result>> { + Ok(KinsokuSet::named(&s.doc()?.doc.kinsoku_sets, name.trim()).cloned().map(Arc::new)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/kinsokusets/tests.rs b/crates/engine/src/cmd/kinsokusets/tests.rs new file mode 100644 index 0000000000..1d1c8980c0 --- /dev/null +++ b/crates/engine/src/cmd/kinsokusets/tests.rs @@ -0,0 +1,458 @@ +use serde_json::{Value, json}; +use vectorcraft_doc::{Kinsoku, NodeId, NodeKind}; + +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s +} + +fn names(s: &Session) -> Vec { + s.doc().unwrap().doc.kinsoku_sets.iter().map(|k| k.name.clone()).collect() +} + +fn steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn text(s: &Session, id: u64) -> vectorcraft_doc::TextObject { + match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("not text"), + } +} + +/// Two paragraphs of area type, the second one selected by its range. +fn type_object(s: &mut Session) -> u64 { + s.execute("text.create", &json!({"x": 10, "y": 10, "text": "あいう\nかきく", "area": {"width": 100, "height": 100}})).unwrap()["id"] + .as_u64() + .unwrap() +} + +fn tight() -> Value { + json!({"name": "Tight", "cannotStart": "」。、う", "cannotEnd": "「", "hanging": "、。", "inseparable": ["——"]}) +} + +/// Kinsoku Shori Settings' OK replaces the document's custom sets as one undo step (none when +/// nothing changes); each category keeps each character once, sorted; the sets are listed with +/// their users, saved with the document and undone with it. +#[test] +fn kinsoku_sets_are_set_as_one_undo_step_and_saved() { + let mut s = session(); + let before = steps(&s); + let r = s.execute("type.kinsokuSets.set", &json!({"sets": [tight(), {"name": " Loose ", "cannotStart": "ーーッ"}]})).unwrap(); + assert_eq!(r["sets"][1]["name"], "Loose"); + assert_eq!(r["sets"][1]["cannotStart"], "ッー"); + assert_eq!(names(&s), ["Tight", "Loose"]); + assert_eq!(steps(&s), before + 1); + s.execute("type.kinsokuSets.set", &json!({"sets": [tight(), {"name": "Loose", "cannotStart": "ッー"}]})).unwrap(); + assert_eq!(steps(&s), before + 1, "the same sets again change nothing"); + let listed = s.execute("type.kinsokuSets.list", &json!({})).unwrap(); + assert_eq!((listed["sets"][0]["name"].clone(), listed["sets"][0]["paragraphs"].clone()), (json!("Tight"), json!(0))); + let reopened = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + assert_eq!(*reopened.kinsoku_sets, *s.doc().unwrap().doc.kinsoku_sets); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(names(&s).is_empty()); + // A document without sets saves none. + let saved = vectorcraft_format::save(&s.doc().unwrap().doc, false); + assert!(!String::from_utf8_lossy(&saved).contains("kinsoku_sets")); +} + +/// The sets are checked before anything changes: a built-in name, a blank or too-long name, two +/// sets of one name in any case, an unknown key, a sequence of one character or with a space, a +/// control character, a `from` the document has no set of, a null value, and more than 256 sets +/// all fail. +#[test] +fn kinsoku_sets_refuse_what_a_set_cannot_hold() { + let mut s = session(); + s.execute("type.kinsokuSets.set", &json!({"sets": [tight()]})).unwrap(); + let before = steps(&s); + let long = "x".repeat(129); + for bad in [ + json!([{"name": "Hard"}]), + json!([{"name": "soft"}]), + json!([{"name": " "}]), + json!([{"name": long}]), + json!([{"name": "A"}, {"name": "a"}]), + json!([{"name": "A", "strict": true}]), + json!([{"name": "A", "inseparable": ["あ"]}]), + json!([{"name": "A", "inseparable": ["あ い"]}]), + json!([{"name": "A", "inseparable": "あい"}]), + json!([{"name": "A", "cannotStart": "あ\u{7}"}]), + json!([{"name": "A", "cannotStart": ["あ"]}]), + json!([{"name": "A", "from": "Missing"}]), + json!([{"name": "A", "from": "Tight"}, {"name": "B", "from": "tight"}]), + json!([{"name": "Tight", "from": "Tight", "cannotStart": null}]), + json!([{"name": "Tight", "from": null}]), + json!([{"name": "A", "inseparable": null}]), + json!((0..257).map(|i| json!({"name": format!("S{i}")})).collect::>()), + ] { + assert!(s.execute("type.kinsokuSets.set", &json!({"sets": bad})).is_err(), "{bad}"); + } + assert!(s.execute("type.kinsokuSets.set", &json!({})).is_err()); + assert_eq!((names(&s), steps(&s)), (vec!["Tight".to_string()], before), "a refused call changes nothing"); +} + +/// Kinsoku Set chooses a custom set by name (any case) for the paragraphs `text.setFormat` sets: each +/// holds a copy of it beside Hard, in one undo step; a name the document has no set of fails the call +/// and changes nothing; a built-in set takes the custom one's place. Paragraph styles carry it. +#[test] +fn text_set_format_chooses_a_custom_set_per_paragraph() { + let mut s = session(); + s.execute("type.kinsokuSets.set", &json!({"sets": [tight()]})).unwrap(); + let id = type_object(&mut s); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + assert!(s.execute("text.setFormat", &json!({"kinsoku": "Missing"})).is_err()); + assert!(text(&s, id).para_at(0).kinsoku_set.is_none(), "a refused call changes nothing"); + let before = steps(&s); + let second = "あいう\n".len(); + s.execute("text.setFormat", &json!({"kinsoku": "tight", "start": second, "end": second})).unwrap(); + assert_eq!(steps(&s), before + 1); + let t = text(&s, id); + assert!(t.para_at(0).kinsoku_set.is_none()); + let p = t.para_at(1); + assert_eq!((p.kinsoku_name(), p.kinsoku), ("Tight", Kinsoku::Hard)); + s.execute("text.setFormat", &json!({"kinsoku": "Tight", "start": second, "end": second})).unwrap(); + assert_eq!(steps(&s), before + 1, "the set the paragraph already has records nothing"); + // The file keeps the paragraph's copy. + let reopened = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let Some(NodeKind::Text(back)) = reopened.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") }; + assert_eq!(back.para_at(1).kinsoku_name(), "Tight"); + // A paragraph style captured from it carries the set; Soft replaces it. + s.execute("paraStyle.new", &json!({"name": "Tight Body", "id": id, "start": second, "end": second})).unwrap(); + s.execute("text.setFormat", &json!({"kinsoku": "soft"})).unwrap(); + assert!(text(&s, id).para_at(1).kinsoku_set.is_none()); + assert_eq!(text(&s, id).para_at(1).kinsoku, Kinsoku::Soft); + s.execute("paraStyle.apply", &json!({"name": "Tight Body", "id": id})).unwrap(); + assert_eq!(text(&s, id).para_at(0).kinsoku_name(), "Tight"); + assert_eq!(text(&s, id).para_at(1).kinsoku_name(), "Tight"); +} + +/// A paragraph style that gives only a built-in Kinsoku Set replaces a custom set on the paragraphs +/// it is applied to: the style keeps Kinsoku Set's custom set with its built-in choice. One whose +/// attributes give only a custom set (written by hand into a file) brings Hard with it. +#[test] +fn a_style_with_a_built_in_kinsoku_set_replaces_a_custom_set() { + let mut s = session(); + s.execute("type.kinsokuSets.set", &json!({"sets": [tight()]})).unwrap(); + let id = type_object(&mut s); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + for (style, kinsoku, name) in [("Soft Only", "soft", "Soft"), ("None Only", "none", "None"), ("Hard Only", "hard", "Hard")] { + s.execute("text.setFormat", &json!({"kinsoku": "Tight"})).unwrap(); + assert_eq!(text(&s, id).para_at(0).kinsoku_name(), "Tight"); + s.execute("paraStyle.new", &json!({"name": style, "attrs": {"kinsoku": kinsoku}})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": style, "id": id})).unwrap(); + let t = text(&s, id); + assert_eq!((t.para_at(0).kinsoku_name(), t.para_at(1).kinsoku_name()), (name, name), "{style}"); + } + s.execute("text.setFormat", &json!({"kinsoku": "soft"})).unwrap(); + let only_set = serde_json::Map::from_iter([("kinsoku_set".to_string(), tight_set(&s))]); + let def = vectorcraft_doc::TextStyleDef { name: "Set Only".into(), attrs: only_set }; + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).para_styles.push(def); + s.execute("paraStyle.apply", &json!({"name": "Set Only", "id": id})).unwrap(); + assert_eq!(text(&s, id).para_at(0).kinsoku_name(), "Tight"); +} + +fn tight_set(s: &Session) -> Value { + json!(s.doc().unwrap().doc.kinsoku_sets[0]) +} + +/// Redefining a paragraph style's Kinsoku Set changes the paragraphs that use the style's set and +/// keeps a paragraph's own custom set: the set and Hard beside it change together. +#[test] +fn redefining_a_style_keeps_a_paragraphs_own_custom_set() { + let mut s = session(); + s.execute("type.kinsokuSets.set", &json!({"sets": [tight(), {"name": "Loose"}]})).unwrap(); + let id = type_object(&mut s); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {"kinsoku_set": tight_set(&s)}})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": "Body", "id": id})).unwrap(); + let second = "あいう\n".len(); + s.execute("text.setFormat", &json!({"kinsoku": "Loose", "start": second, "end": second})).unwrap(); + s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"kinsoku": "soft"}})).unwrap(); + let t = text(&s, id); + assert_eq!((t.para_at(0).kinsoku_name(), t.para_at(1).kinsoku_name()), ("Soft", "Loose")); +} + +/// A paragraph style's custom set is one of the document's, by name in any case, with the +/// document's characters; a name the document has no set of fails the call. +#[test] +fn a_styles_custom_set_is_one_of_the_documents() { + let mut s = session(); + s.execute("type.kinsokuSets.set", &json!({"sets": [tight()]})).unwrap(); + assert!(s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {"kinsoku_set": {"name": "Missing"}}})).is_err()); + s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {"kinsoku_set": {"name": "tight", "cannotStart": "x"}}})).unwrap(); + let listed = s.execute("paraStyle.list", &json!({})).unwrap(); + let body = listed["styles"].as_array().unwrap().iter().find(|st| st["name"] == "Body").unwrap().clone(); + assert_eq!(body["attrs"]["kinsoku_set"], tight_set(&s)); + assert!(s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"kinsoku_set": {"name": "Missing"}}})).is_err()); +} + +/// A custom set goes with Hard and has a name a custom set can have: a paragraph style call that +/// gives one beside None or Soft, or with a blank or built-in name, fails and leaves the styles as +/// they were, and one beside Hard is kept. +#[test] +fn a_styles_custom_set_given_beside_none_or_soft_fails_the_call() { + let mut s = session(); + s.execute("type.kinsokuSets.set", &json!({"sets": [tight()]})).unwrap(); + s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {"kinsoku_set": tight_set(&s)}})).unwrap(); + let styles = |s: &Session| s.doc().unwrap().doc.para_styles.clone(); + let before = styles(&s); + for kinsoku in ["none", "soft"] { + let attrs = json!({"kinsoku": kinsoku, "kinsoku_set": tight_set(&s)}); + assert!(s.execute("paraStyle.new", &json!({"name": "Other", "attrs": attrs})).is_err(), "new with {kinsoku}"); + assert!(s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": attrs})).is_err(), "setAttrs with {kinsoku}"); + assert_eq!(styles(&s), before, "{kinsoku}"); + } + for name in ["", " ", "Hard", "soft"] { + let attrs = json!({"kinsoku_set": {"name": name}}); + assert!(s.execute("paraStyle.new", &json!({"name": "Other", "attrs": attrs})).is_err(), "new named `{name}`"); + assert!(s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": attrs})).is_err(), "setAttrs named `{name}`"); + assert_eq!(styles(&s), before, "`{name}`"); + } + let attrs = json!({"kinsoku": "hard", "kinsoku_set": tight_set(&s)}); + s.execute("paraStyle.new", &json!({"name": "Other", "attrs": attrs})).unwrap(); + let other = styles(&s).into_iter().find(|st| st.name == "Other").unwrap(); + assert_eq!(other.attrs["kinsoku_set"], tight_set(&s)); +} + +/// Editing a set gives every paragraph and paragraph style using it the new characters, renaming it +/// (`from`) the new name too, and deleting it sets them to Hard: each in one undo step, which undo +/// takes back with the set. Paragraphs using no set, or another set, stay as they are. +#[test] +fn editing_renaming_and_deleting_a_set_updates_its_users() { + let mut s = session(); + s.execute("type.kinsokuSets.set", &json!({"sets": [tight(), {"name": "Other", "cannotStart": "ー"}]})).unwrap(); + let id = type_object(&mut s); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let second = "あいう\n".len(); + s.execute("text.setFormat", &json!({"kinsoku": "Tight", "start": 0, "end": 0})).unwrap(); + s.execute("text.setFormat", &json!({"kinsoku": "Other", "start": second, "end": second})).unwrap(); + s.execute("paraStyle.new", &json!({"name": "Uses Tight", "id": id, "start": 0, "end": 0})).unwrap(); + let style_set = |s: &Session| s.doc().unwrap().doc.para_styles.iter().find(|st| st.name == "Uses Tight").unwrap().attrs["kinsoku_set"].clone(); + assert_eq!(style_set(&s)["name"], "Tight"); + let listed = s.execute("type.kinsokuSets.list", &json!({})).unwrap(); + assert_eq!((listed["sets"][0]["paragraphs"].clone(), listed["sets"][0]["styles"].clone()), (json!(1), json!(1))); + + // Edit: 「 may end a line now, and う may start one. + let before = steps(&s); + let edited = json!({"name": "Tight", "cannotStart": "」。、", "hanging": "、。", "inseparable": ["——"]}); + s.execute("type.kinsokuSets.set", &json!({"sets": [edited, {"name": "Other", "cannotStart": "ー"}]})).unwrap(); + assert_eq!(steps(&s), before + 1); + let p = text(&s, id).para_at(0).clone(); + assert_eq!(p.kinsoku_set.as_ref().unwrap().cannot_start, ['、', '。', '」']); + assert!(p.kinsoku_set.as_ref().unwrap().cannot_end.is_empty()); + assert_eq!(style_set(&s)["cannotStart"], "、。」"); + assert_eq!(text(&s, id).para_at(1).kinsoku_name(), "Other", "another set's paragraph stays"); + + // Rename: the users take the new name. + let renamed = json!({"name": "Strict", "from": "Tight", "cannotStart": "」。、", "hanging": "、。", "inseparable": ["——"]}); + s.execute("type.kinsokuSets.set", &json!({"sets": [renamed, {"name": "Other", "cannotStart": "ー"}]})).unwrap(); + assert_eq!(names(&s), ["Strict", "Other"]); + assert_eq!(text(&s, id).para_at(0).kinsoku_name(), "Strict"); + assert_eq!(style_set(&s)["name"], "Strict"); + + // Delete: its users take Hard, in one step that undo takes back. + let before = steps(&s); + s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "Other", "cannotStart": "ー"}]})).unwrap(); + assert_eq!(steps(&s), before + 1); + let p = text(&s, id).para_at(0).clone(); + assert_eq!((p.kinsoku_set.is_none(), p.kinsoku), (true, Kinsoku::Hard)); + assert_eq!(style_set(&s), Value::Null); + assert_eq!(text(&s, id).para_at(1).kinsoku_name(), "Other"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(text(&s, id).para_at(0).kinsoku_name(), "Strict"); + assert_eq!(style_set(&s)["name"], "Strict"); + assert_eq!(names(&s), ["Strict", "Other"]); +} + +/// Type pasted into another document brings its custom sets: a missing set is added, the +/// document's set of that name with the same characters is used, and one with other characters +/// keeps its own and the pasted set comes in under a free name, so editing the document's set +/// leaves the pasted paragraphs alone. A paragraph style that comes along takes the same set. A +/// document with no room for another set gives the pasted paragraphs Hard. +#[test] +fn pasted_type_brings_its_kinsoku_sets() { + let mut s = session(); + s.execute("type.kinsokuSets.set", &json!({"sets": [tight()]})).unwrap(); + let id = type_object(&mut s); + s.execute("paraStyle.new", &json!({"name": "Tight Body", "attrs": {"kinsoku_set": tight_set(&s)}})).unwrap(); + s.execute("paraStyle.apply", &json!({"name": "Tight Body", "id": id})).unwrap(); + let source = s.doc().unwrap().doc.kinsoku_sets[0].clone(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + let pasted = |s: &mut Session| -> (vectorcraft_doc::TextObject, Value) { + let v = s.execute("edit.paste", &json!({})).unwrap(); + (text(s, v["ids"][0].as_u64().unwrap()), v) + }; + let style_set = |s: &Session| s.doc().unwrap().doc.para_styles.iter().find(|st| st.name == "Tight Body").unwrap().attrs["kinsoku_set"].clone(); + + // Pasted back after the set was edited: the document's set as it is now, laid out anew. + s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "Tight", "cannotStart": "いうかきく"}]})).unwrap(); + let (t, _) = pasted(&mut s); + let now = s.doc().unwrap().doc.kinsoku_sets[0].clone(); + assert_eq!(t.para_at(0).kinsoku_set.as_deref(), Some(&now)); + let mut fresh = t.clone(); + crate::cmd::typecmd::refresh_bounds(&mut fresh); + assert!(fresh == t, "the pasted type is laid out with the document's set"); + + // A document without the set. + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let (t, _) = pasted(&mut s); + assert_eq!(names(&s), ["Tight"]); + assert_eq!(t.para_at(1).kinsoku_set.as_deref(), Some(&source)); + assert_eq!(style_set(&s), json!(source)); + let (_, again) = pasted(&mut s); + assert_eq!((again["added"].clone(), names(&s)), (json!(0), vec!["Tight".to_string()]), "a second paste uses the set the first added"); + + // A document whose set of that name has other characters. + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "TIGHT", "cannotStart": "ー"}]})).unwrap(); + let (t, v) = pasted(&mut s); + assert_eq!(names(&s), ["TIGHT", "Tight 2"]); + let p = t.para_at(0); + assert_eq!((p.kinsoku_name(), p.kinsoku_set.as_deref().map(|k| &k.cannot_start)), ("Tight 2", Some(&source.cannot_start))); + assert_eq!(style_set(&s)["name"], "Tight 2"); + assert!(v["renamed"].as_array().unwrap().contains(&json!({"kind": "kinsokuSet", "from": "Tight", "to": "Tight 2"})), "{v}"); + let kept = json!(s.doc().unwrap().doc.kinsoku_sets[1]); + s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "TIGHT", "cannotStart": "ッ"}, kept]})).unwrap(); + let users = s.execute("type.kinsokuSets.list", &json!({})).unwrap(); + assert_eq!(users["sets"][0]["paragraphs"], 0, "editing the document's own set leaves the pasted paragraphs alone: {users}"); + + // A document with no room for another set. + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let full: Vec = (0..256).map(|i| json!({"name": format!("Set {i}")})).collect(); + s.execute("type.kinsokuSets.set", &json!({"sets": full})).unwrap(); + let (t, _) = pasted(&mut s); + assert_eq!(names(&s).len(), 256); + let p = t.para_at(0); + assert_eq!((p.kinsoku_set.is_none(), p.kinsoku), (true, Kinsoku::Hard)); + assert_eq!(style_set(&s), Value::Null); +} + +/// A pasted set whose name, at the longest a name can be, the document's set with other +/// characters already has comes in under a free name that fits: the number takes the place of the +/// name's last characters, and a space left at the end of them is dropped. A second paste uses +/// the set the first added. +#[test] +fn a_pasted_set_with_the_longest_name_comes_in_under_a_name_that_fits() { + for (long, fitted) in + [("あ".repeat(128), format!("{} 2", "あ".repeat(126))), (format!("{} いい", "あ".repeat(125)), format!("{} 2", "あ".repeat(125)))] + { + let mut s = session(); + s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": long, "cannotStart": "」"}]})).unwrap(); + let id = type_object(&mut s); + s.execute("text.setFormat", &json!({"ids": [id], "kinsoku": long})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": long, "cannotStart": "ー"}]})).unwrap(); + let v = s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(names(&s), [long.clone(), fitted.clone()]); + let t = text(&s, v["ids"][0].as_u64().unwrap()); + let p = t.para_at(0); + assert_eq!((p.kinsoku_name(), p.kinsoku_set.as_deref().map(|k| k.cannot_start.clone())), (fitted.as_str(), Some(vec!['」']))); + let again = s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!( + (again["added"].clone(), names(&s)), + (json!(0), vec![long.clone(), fitted.clone()]), + "a second paste uses the set the first added" + ); + } +} + +/// The Kinsoku Sets a graph keeps for its labels (value axis, categories, legend), and those its +/// labels are drawn with now. +fn graph_label_sets(s: &Session, id: u64) -> (Vec, Vec) { + let n = s.doc().unwrap().doc.node(NodeId(id)).unwrap().clone(); + let l = n.extras().graph.as_deref().unwrap().label_styles.clone(); + let kept = [l.values_para, l.categories_para, l.legend_para].into_iter().flatten().map(|p| p.kinsoku_name().to_string()).collect(); + let mut drawn = vec![]; + n.walk(&mut |m| { + if let NodeKind::Text(t) = &m.kind { + drawn.push(t.para_at(0).kinsoku_name().to_string()); + } + }); + (kept, drawn) +} + +/// A graph's labels keep a custom set as type does. Pasted into a document whose set of that name +/// has other characters, they take the copy the paste adds, also once the graph is drawn again. +/// Editing a set gives the graph's kept attributes the new characters, and deleting it gives them +/// Hard. +#[test] +fn graph_labels_keep_their_custom_set() { + let mut s = session(); + s.execute("type.kinsokuSets.set", &json!({"sets": [tight()]})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4"; + let id = s.execute("graph.create", &json!({"type": "column", "x": 10, "y": 10, "width": 300, "height": 200, "csv": csv})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("text.setFormat", &json!({"kinsoku": "Tight"})).unwrap(); + let (kept, drawn) = graph_label_sets(&s, id); + assert_eq!(kept, ["Tight"; 3]); + assert!(!drawn.is_empty() && drawn.iter().all(|k| k == "Tight"), "{drawn:?}"); + s.execute("edit.copy", &json!({})).unwrap(); + + // Pasted where the set of that name has other characters: the labels take the added copy. + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "TIGHT", "cannotStart": "ー"}]})).unwrap(); + let pasted = s.execute("edit.paste", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + assert_eq!(names(&s), ["TIGHT", "Tight 2"]); + s.execute("graph.setData", &json!({"id": pasted, "csv": csv})).unwrap(); + let (kept, drawn) = graph_label_sets(&s, pasted); + assert_eq!(kept, ["Tight 2"; 3]); + assert!(drawn.iter().all(|k| k == "Tight 2"), "the labels drawn again keep the copy: {drawn:?}"); + + // A second copy becomes a symbol's art. + let in_symbol = s.execute("edit.paste", &json!({})).unwrap()["ids"][0].clone(); + s.execute("symbol.new", &json!({"name": "Chart", "ids": [in_symbol]})).unwrap(); + let symbol_starts = |s: &Session| { + let mut out = vec![]; + s.doc().unwrap().doc.symbols.iter().find(|x| x.name == "Chart").unwrap().art.walk(&mut |n| { + if let Some(g) = n.extras().graph.as_deref() { + out.push(g.label_styles.values_para.as_ref().unwrap().kinsoku_set.as_deref().unwrap().cannot_start.clone()); + } + }); + out + }; + assert_eq!(symbol_starts(&s).len(), 1); + let listed = s.execute("type.kinsokuSets.list", &json!({})).unwrap(); + assert_eq!((listed["sets"][1]["name"].clone(), listed["sets"][1]["graphs"].clone()), (json!("Tight 2"), json!(2)), "{listed}"); + assert_eq!(listed["sets"][0]["graphs"], 0); + + // Edited, then deleted: the kept attributes follow the set, so the labels drawn again do too. + let edited = json!({"name": "Tight 2", "cannotStart": "ー"}); + s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "TIGHT", "cannotStart": "ー"}, edited]})).unwrap(); + let l = &s.doc().unwrap().doc.node(NodeId(pasted)).unwrap().extras().graph.as_deref().unwrap().label_styles; + assert_eq!(l.values_para.as_ref().unwrap().kinsoku_set.as_deref().unwrap().cannot_start, ['ー']); + assert_eq!(symbol_starts(&s), [vec!['ー']], "a graph in a symbol's art too"); + s.execute("type.kinsokuSets.set", &json!({"sets": [{"name": "TIGHT", "cannotStart": "ー"}]})).unwrap(); + s.execute("graph.setData", &json!({"id": pasted, "csv": csv})).unwrap(); + let (kept, drawn) = graph_label_sets(&s, pasted); + assert_eq!(kept, ["Hard"; 3]); + assert!(drawn.iter().all(|k| k == "Hard"), "{drawn:?}"); +} + +/// New Set's starting point: Hard and Soft give their characters, None gives an empty set, and a +/// custom set (any case) gives its own; an unknown base fails. +#[test] +fn a_new_set_starts_from_a_built_in_or_custom_set() { + let mut s = session(); + s.execute("type.kinsokuSets.set", &json!({"sets": [tight()]})).unwrap(); + let hard = s.execute("type.kinsokuSets.base", &json!({"base": "hard", "name": "New"})).unwrap(); + let soft = s.execute("type.kinsokuSets.base", &json!({"base": "soft"})).unwrap(); + let start = |v: &Value| v["set"]["cannotStart"].as_str().unwrap().to_string(); + assert!(start(&hard).contains('ー') && !start(&soft).contains('ー') && start(&soft).contains('」')); + assert_eq!(hard["set"]["name"], "New"); + assert_eq!(hard["set"]["hanging"], "、。,.。、"); + assert_eq!(hard["set"]["inseparable"].as_array().unwrap().len(), 5); + let none = s.execute("type.kinsokuSets.base", &json!({"base": "none"})).unwrap(); + assert_eq!(none["set"]["cannotStart"], ""); + let custom = s.execute("type.kinsokuSets.base", &json!({"base": "TIGHT"})).unwrap(); + assert_eq!(custom["set"]["cannotEnd"], "「"); + assert!(s.execute("type.kinsokuSets.base", &json!({"base": "Missing"})).is_err()); +} diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 7a7f2b8e08..f7632f2652 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -13,6 +13,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{Artboard, ArtboardSide, Document, LAYER_COLORS, LayerColor, Node, NodeId, NodeKind, Scaling}; use vectorcraft_geom::{Affine, Rect}; +use super::buildcmds::LivePaintMove; use super::{ CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, checked_id, checked_ids_param, checked_node, checked_nodes_param, cmd, color_value, f64_or, has_doc, has_selection, ids_param, index, object_param, ok, str_param, switch_or, @@ -83,7 +84,7 @@ pub fn specs() -> Vec { "Layer Options…", ["Window", "Layers"], None, - "{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step", + "{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked, and `ids` may name ruler guides (their `guide.list` id), which hide or lock on their own. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already. One undo step", has_doc, set_props ), @@ -110,7 +111,7 @@ pub fn specs() -> Vec { "Move Rows", [], None, - "{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, group or Intertwine group (on top of its contents). Layers go only in layers or at the top level, objects in layers, groups and Intertwine groups; an object placed beside a top-level layer goes inside it. An object placed in an Intertwine group becomes a member drawn in its row's order, with no arranged areas, and one placed in a group that is a member becomes part of that member; one that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused. A member moved out of its Intertwine group drops its arranged areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own (with no member, it is removed). A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies, which may also go above or below a row they copy (the target among `ids`). Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}", + "{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer, group or Intertwine group (on top of its contents). Layers go only in layers or at the top level, objects in layers, groups and Intertwine groups; an object placed beside a top-level layer goes inside it. An object placed in an Intertwine group becomes a member drawn in its row's order, with no arranged areas, and one placed in a group that is a member becomes part of that member; one that is or holds an Intertwine group, a Repeat, a graph or a Live Paint group is refused. A member moved out of its Intertwine group drops its arranged areas, and a group left with one member is replaced by that member, or becomes a plain group of it when the group has an opacity, blending, appearance, mask, lock or hidden state of its own (with no member, it is removed). A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies, which may also go above or below a row they copy (the target among `ids`). A row that goes into a Live Paint group from elsewhere joins its paths as livePaint.merge adds them, and the group is selected (paths, compound paths, groups of them and Live Paint groups; anything else is refused and nothing moves); a row that goes into or leaves a Live Paint group's paths makes the group's faces and edges again, keeping the paint of those that stay. Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids} (a row that joined a Live Paint group is listed as the group)", has_doc, move_rows ), @@ -119,7 +120,7 @@ pub fn specs() -> Vec { "Reorder", [], None, - "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too)", + "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", has_doc, move_node ), @@ -625,12 +626,22 @@ fn highlight(s: &mut Session, p: &Value) -> Result { "add" | "toggle" => {} other => return Err(bad(C, format!("mode is set, add or toggle, not `{other}`"))), } + // `rows` keeps the highlight order. With more than 8 ids, `held` holds the same rows as a set and + // answers each lookup; with fewer, each lookup searches `rows`. + let mut held: Option> = (ids.len() > 8).then(|| rows.iter().copied().collect()); let mut last = None; for id in ids { - if mode == "toggle" && rows.contains(&id) { + let has = held.as_ref().map_or_else(|| rows.contains(&id), |h| h.contains(&id)); + if mode == "toggle" && has { rows.retain(|r| *r != id); - } else if !rows.contains(&id) { + if let Some(h) = &mut held { + h.remove(&id); + } + } else if !has { rows.push(id); + if let Some(h) = &mut held { + h.insert(id); + } last = Some(id); } } @@ -651,6 +662,10 @@ fn set_props(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return Err(bad(C, "no rows")); } + if let Some(v) = str_param(p, "name").filter(|v| !v.trim().is_empty()) { + let name = if xml_id { vectorcraft_doc::xml_id::to_object_name(v) } else { v.to_string() }; + super::buildcmds::check_part_name(&s.doc()?.doc, &ids, &name)?; + } s.edit("Layer Options", |d, sel| { for id in &ids { apply_options(d.node_mut(*id).ok_or(EngineError::NoNode(*id))?, p, xml_id); @@ -807,7 +822,15 @@ fn move_rows(s: &mut Session, p: &Value) -> Result { if parent.is_some_and(|p| locked_within(d, p)) { return Err(EngineError::Other("the layer or group is locked".into())); } - let label = if copy { "Duplicate Rows" } else { "Move Rows" }; + // Rows that go into a Live Paint group join its paths, as Live Paint › Merge adds them. + let live_paint = LivePaintMove::plan(d, &ids, parent, copy)?; + let label = if live_paint.joins() { + "Merge Live Paint" + } else if copy { + "Duplicate Rows" + } else { + "Move Rows" + }; // Where each moved row comes from (a copy has a new id, so it comes from nowhere), and the // Intertwine groups it leaves. let from: std::collections::HashMap> = ids.iter().map(|i| (*i, d.parent_of(*i))).collect(); @@ -848,6 +871,7 @@ fn move_rows(s: &mut Session, p: &Value) -> Result { } let placed: Vec<(NodeId, Option)> = out.iter().map(|o| (*o, from.get(o).copied().flatten())).collect(); super::intertwine::settle_members(d, &placed, &left)?; + let out = live_paint.finish(d, sel, &out)?; sel.prune(d); sel.deselect_uneditable(d); Ok(out) @@ -870,11 +894,14 @@ fn move_node(s: &mut Session, p: &Value) -> Result { if let Some(what) = super::intertwine::refused_in(d, parent, n) { return Err(bad(C, format!("{what} can't be intertwined"))); } + let live_paint = LivePaintMove::plan(d, &[id], parent, false)?; + let label = if live_paint.joins() { "Merge Live Paint" } else { "Reorder" }; let from = d.parent_of(id); let left = super::intertwine::groups_of(d, &[id]); - s.edit("Reorder", |d, sel| { + s.edit(label, |d, sel| { d.move_node(id, parent, index)?; super::intertwine::settle_members(d, &[(id, from)], &left)?; + live_paint.finish(d, sel, &[id])?; sel.prune(d); sel.deselect_uneditable(d); Ok(()) diff --git a/crates/engine/src/cmd/layerpanel.rs b/crates/engine/src/cmd/layerpanel.rs index 5400e66728..b88f6ce636 100644 --- a/crates/engine/src/cmd/layerpanel.rs +++ b/crates/engine/src/cmd/layerpanel.rs @@ -132,7 +132,7 @@ pub fn specs() -> Vec { "Locate Object", ["Window", "Layers"], None, - "{id?, layersOnly?} (default: the last selected object) highlight the object's row; the Layers panel opens the layers around it and scrolls to it, also when the row was already highlighted →{id, ancestry: [layer…, id]}. layersOnly (default false; the panel sends true while Show Layers Only is on, as Locate Layer) highlights the innermost layer or sublayer holding the object instead, or a layer id itself → {id: layer, objectId, ancestry: [layer…]}", + "{id?, layersOnly?} (default: the frontmost selected object in the stacking order) highlight the object's row; the Layers panel opens the layers around it, and scrolls to its row when the row is in the list, also when the row was already highlighted (Show Layers Only, a search, the filter, or editing an opacity mask on another layer can leave the row out) → {id, ancestry: [layer…, id]}. layersOnly (default false; the panel sends true while Show Layers Only is on, as Locate Layer) highlights the innermost layer or sublayer holding the object instead, or a layer id itself → {id: layer, objectId, ancestry: [layer…]}", has_doc, locate ), @@ -437,7 +437,8 @@ fn locate(s: &mut Session, p: &Value) -> Result { let id = object_param(p, "id", "layer.locate")?; let layers_only = switch_or(p, "layersOnly", false, "layer.locate")?; let st = s.doc_mut()?; - let id = id.or_else(|| st.selection.objects.last().copied()).ok_or_else(|| bad("layer.locate", "nothing selected"))?; + // With no id, the frontmost selected object in the stacking order, whatever order it was selected in. + let id = id.or_else(|| st.selection.in_paint_order(&st.doc).last().copied()).ok_or_else(|| bad("layer.locate", "nothing selected"))?; let mut ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?; if layers_only { // Locate Layer: the innermost layer or sublayer holding the object (a layer locates itself). diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 55c6612494..392d6340c6 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Unembed", [], None, - "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds. One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors", + "{id?: an embedded image (default: the one selected), path?, ids?: [image ids] (instead of id; one id is the same as id), folder?} write the image's pixels to the file at path (PNG, JPEG, GIF or WebP as stored, other images as PNG; a path ending in .png/.jpg/.jpeg/.gif/.webp/.tif/.tiff/.bmp converts them) and link the image to it, keeping its bounds; written as stored (here and with folder), an image from a PSD or PSB file keeps the clip group of the clipping path that file names, and the file written keeps the path, so Open, Place, Relink and Update Links read the file with that clip group. One undo step → {id, path}; no path → {name, dataBase64} (nothing changes: there is no file to link to). With folder: write each embedded image of ids or id (default: the selected embedded images) to a new file in folder, as stored (as PNG when that format is not one of VectorCraft's raster file formats), named after the image (characters a file name can't hold become _; Image when nothing is left), with Name 2 … Name 99 when the name is taken; a file already there is never replaced. Linked images among ids are left as they are. Each image links to its file and keeps its bounds. One undo step (undo does not remove the files); when a file can't be written, the files this call wrote are removed and nothing changes → {unembedded: [{id, path}], skipped: [ids of linked images]}; id with ids, path with folder, and ids of more or fewer than one image without folder are errors", has_doc, unembed ), @@ -634,7 +634,8 @@ pub(crate) fn readable_and_kept(blob: ImageBlob, unread: bool, linked: bool) -> /// The linked image file `bytes` (read from `path`, when there is one), read with its preview: a /// DCS file's plates, else its image ([`super::place::dcs::raster`]); an error when its pixels -/// can't be read ([`readable`]). +/// can't be read ([`readable`]). A PNG or TIFF that Unembed wrote from a PSD or PSB file's image +/// is read with the clipping path it keeps ([`fileio::raster_image`]). fn linked_image(bytes: &[u8], path: Option<&str>) -> Result { let mut img = super::place::dcs::raster(bytes, path)?; img.blob = readable(img.blob, kept_unread(bytes), true)?; diff --git a/crates/engine/src/cmd/live/blend.rs b/crates/engine/src/cmd/live/blend.rs index a2cb0e3f91..cfb87afdb3 100644 --- a/crates/engine/src/cmd/live/blend.rs +++ b/crates/engine/src/cmd/live/blend.rs @@ -214,6 +214,25 @@ fn spine_points_param(p: &Value, cmd: &str) -> Result> { list.iter().map(|i| i.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(wrong)).collect() } +/// Whether linking handle `out` of spine point `index` at `q` would leave the blend's spine as it +/// is (false when the blend or the point is not there, for the edit to report it). +fn spine_link_unchanged(s: &Session, p: &Value, cmd: &str, index: usize, out: bool, q: Point) -> Result { + let id = match crate::cmd::object_param(p, "id", cmd)? { + Some(id) => Some(id), + None => selected_of(s, is_blend).first().copied(), + }; + let d = &s.doc()?.doc; + let Some(NodeKind::Blend { children, spec }) = id.and_then(|id| d.node(id)).map(|n| &n.kind) else { return Ok(false) }; + let Some((path, _)) = live::pin_spine(children, spec) else { return Ok(false) }; + Ok(path.subpaths.first().is_some_and(|sp| { + sp.anchors.get(index).is_some_and(|a| { + let mut linked = *a; + linked.link_handle(out, q, sp.has_segment(index, !out)); + linked == *a + }) + })) +} + pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result { const C: &str = "object.blend.spine.moveAnchor"; let index = index_param(p, "anchor", C)?; @@ -225,15 +244,33 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result { Some(_) => return Err(bad(C, "handle must be in or out")), }; let independent = switch_or(p, "independent", false, C)?; + let link = switch_or(p, "link", false, C)?; let with = spine_points_param(p, C)?; // Any `with`, even an empty list, asks to move points, which a handle drag doesn't. if handle.is_some() && p.get("with").is_some_and(|v| !v.is_null()) { return Err(bad(C, "`with` moves points, not a handle")); } + if link && independent { + return Err(bad(C, "`link` and `independent` cannot both be true")); + } + if link && handle.is_none() { + return Err(bad(C, "`link` places a handle: give `handle`")); + } + if link && let Some(out) = handle { + // A spine point the linked handles would leave as it is records no undo step. + if spine_link_unchanged(s, p, C, index, out, q)? { + return ok(); + } + } edit_spine(s, p, C, "Reshape Spine", |sp, anchors, keys| { + let pull_out = handle.is_some_and(|out| sp.has_segment(index, !out)); let a = sp.anchors.get_mut(index).ok_or_else(|| bad(C, "no such spine point"))?; if let Some(out) = handle { - a.set_handle(out, q, independent); + if link { + a.link_handle(out, q, pull_out); + } else { + a.set_handle(out, q, independent); + } return Ok(()); } let delta = q - a.p; diff --git a/crates/engine/src/cmd/live/commands.rs b/crates/engine/src/cmd/live/commands.rs index 79b2915aa0..991ebf103c 100644 --- a/crates/engine/src/cmd/live/commands.rs +++ b/crates/engine/src/cmd/live/commands.rs @@ -99,7 +99,7 @@ pub fn specs() -> Vec { "Move Spine Point", [], None, - "{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path", + "{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool, link?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`; `link` makes the point smooth with the other handle in line at its own length, a retracted one pulled out to the moved handle's length where a segment leaves the point on its side; `link` needs `handle` and cannot go with `independent`). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path", has_doc, spine_move_anchor ), diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index defc405514..a1464ebcef 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -133,7 +133,7 @@ pub fn specs() -> Vec { "Create Object Mosaic…", ["Object"], None, - "{columns=10, rows=10 (whole numbers, kept within 1..1000), width?, height? (new size in pt; default the image's), spacingX=0, spacingY=0 (pt between tiles), gray?: bool, deleteRaster?: bool} a group of rectangles coloured by the selected image's average tile colours → {id, tiles}", + "{columns=10, rows=10 (whole numbers, kept within 1..1000), width?, height? (new size in pt, 0.1..1000000; default the image's), percentages?: bool (width and height are percentages of the image's size, default 100), constrain?: \"width\"|\"height\"|null (Constrain Ratio: the mosaic keeps the image's proportions, the named side's size leads and the other side's is worked out from it, both growing or shrinking in proportion to keep the sizes within 0.1..1000000), useRatio?: bool|\"width\"|\"height\" (square tiles as drawn, spacing taken off: the count on the side named, or with true on the constrained side, columns by default, stays and the other is the count, 1..1000, whose tiles come closest to square), spacingX=0, spacingY=0 (pt between tiles), gray?: bool, deleteRaster?: bool} a group of rectangles colored by the selected image's average tile colors → {id, tiles, columns, rows}", has_image, object_mosaic ), @@ -970,7 +970,23 @@ pub(crate) fn has_image(s: &Session) -> std::result::Result<(), String> { } } -fn object_mosaic(s: &mut Session, p: &Value) -> Result { +/// What `object.createObjectMosaic` makes from its params: the image, the tile counts, the tiles' +/// placement, their size and spacing in image pixels, and the options. +struct MosaicPlan { + id: NodeId, + im: ImageObject, + cols: u32, + rows: u32, + xf: Affine, + tile: (f64, f64), + gap: (f64, f64), + gray: bool, + delete: bool, +} + +/// The mosaic `object.createObjectMosaic` would make from `p`, worked out without decoding the +/// image or changing the document. +fn mosaic_plan(s: &Session, p: &Value) -> Result { const C: &str = "object.createObjectMosaic"; let st = s.doc()?; let id = st @@ -980,28 +996,97 @@ fn object_mosaic(s: &mut Session, p: &Value) -> Result { .copied() .find(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_)))) .ok_or_else(|| bad(C, "select an image"))?; - let node = st.doc.node(id).cloned().ok_or(EngineError::NoNode(id))?; + let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?; let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) }; - let blob = st.doc.images.get(&im.key).filter(|b| !b.bytes.is_empty()).ok_or_else(|| bad(C, "the image has no embedded pixels"))?; - let raster = vectorcraft_trace::Raster::decode(&blob.bytes).map_err(|e| bad(C, e.to_string()))?; - let cols = whole_or(p, "columns", 10, C)?.clamp(1, 1000) as u32; - let rows = whole_or(p, "rows", 10, C)?.clamp(1, 1000) as u32; + if !st.doc.images.get(&im.key).is_some_and(|b| !b.bytes.is_empty()) { + return Err(bad(C, "the image has no embedded pixels")); + } + let mut cols = whole_or(p, "columns", 10, C)?.clamp(1, 1000) as u32; + let mut rows = whole_or(p, "rows", 10, C)?.clamp(1, 1000) as u32; let gray = switch_or(p, "gray", false, C)?; - let colors = vectorcraft_trace::mosaic(&raster, cols, rows); + let percentages = switch_or(p, "percentages", false, C)?; + // A side named "width" (true) or "height" (false), as `constrain` and `useRatio` take it. + let side = |key: &str, v: &Value, also: &str| match v.as_str() { + Some("width") => Ok(true), + Some("height") => Ok(false), + _ => Err(bad(C, format!("`{key}` must be one of {}", format_args!("\"width\", \"height\"{also} or null")))), + }; + let constrain = match p.get("constrain") { + None | Some(Value::Null) => None, + Some(v) => Some(side("constrain", v, "")?), + }; + // Use Ratio's kept side: true keeps Constrain Ratio's side (the width when it is left out). + let use_ratio = match p.get("useRatio") { + None | Some(Value::Null | Value::Bool(false)) => None, + Some(Value::Bool(true)) => Some(constrain.unwrap_or(true)), + Some(v) => Some(side("useRatio", v, ", true, false")?), + }; // Tiles in image space, placed by the image transform (scaled to a new size if asked). let b = node.geometric_bounds().ok_or_else(|| bad(C, "image has no bounds"))?; check_numbers(p, &["width", "height", "spacingX", "spacingY"], C)?; - let (nw, nh) = (f64_or(p, "width", b.width()).max(0.1), f64_or(p, "height", b.height()).max(0.1)); - let resize = Affine::translate(b.origin().to_vec2()) - * Affine::scale_non_uniform(nw / b.width().max(1e-9), nh / b.height().max(1e-9)) - * Affine::translate(-b.origin().to_vec2()); + let (bw, bh) = (b.width().max(1e-9), b.height().max(1e-9)); + // A size given (pt, or % of the image's) is from 0.1 to 1,000,000; one left out is the image's. + let size = |key: &str, base: f64| -> Result { + let Some(x) = p.get(key).and_then(Value::as_f64) else { return Ok(base) }; + let (min, max) = (0.1, 1_000_000.0); + if !(min..=max).contains(&x) { + return Err(bad(C, format!("`{key}` must be between {min} and {max} (got {x})"))); + } + Ok(if percentages { base * x / 100.0 } else { x }) + }; + let (mut nw, mut nh) = (size("width", bw)?, size("height", bh)?); + // Constrain Ratio keeps the image's proportions: the named side leads and the other follows. + match constrain { + Some(true) => nh = nw * bh / bw, + Some(false) => nw = nh * bw / bh, + None => {} + } + // A size under 0.1 pt grows to 0.1 pt, in proportion while Constrain Ratio keeps it. A side + // Constrain Ratio works out above 1,000,000 pt shrinks to 1,000,000 pt, the other with it. + let (nw, nh) = match constrain { + Some(_) => { + let k = (0.1 / nw.min(nh)).max(1.0).min(1_000_000.0 / nw.max(nh)); + // Proportions over 10,000,000 to 1 leave no size with both sides within the range. + if nw.min(nh) * k < 0.1 * (1.0 - 1e-9) { + return Err(bad(C, "the image's proportions leave no size with both sides between 0.1 and 1000000 pt")); + } + (nw * k, nh * k) + } + None => (nw.max(0.1), nh.max(0.1)), + }; + let resize = Affine::translate(b.origin().to_vec2()) * Affine::scale_non_uniform(nw / bw, nh / bh) * Affine::translate(-b.origin().to_vec2()); let xf = resize * im.xf; - let (tw, th) = (im.width as f64 / cols as f64, im.height as f64 / rows as f64); - // Spacing is in points; convert to image pixels along each axis. + // Points per image pixel along each of the image's axes (the image may be turned). let ppx = (xf * Point::new(1.0, 0.0) - xf * Point::ZERO).hypot().max(1e-9); let ppy = (xf * Point::new(0.0, 1.0) - xf * Point::ZERO).hypot().max(1e-9); - let (gx, gy) = ((f64_or(p, "spacingX", 0.0).max(0.0) / ppx).min(tw * 0.9), (f64_or(p, "spacingY", 0.0).max(0.0) / ppy).min(th * 0.9)); + let (sx, sy) = (f64_or(p, "spacingX", 0.0).max(0.0), f64_or(p, "spacingY", 0.0).max(0.0)); + let (iw, ih) = (im.width as f64, im.height as f64); + // Use Ratio: square tiles as drawn, spacing taken off, from the count on the kept side, + // measured along the image's axes. + match use_ratio { + Some(true) => rows = mosaic_square_count(cols, iw * ppx, ih * ppy, sx, sy), + Some(false) => cols = mosaic_square_count(rows, ih * ppy, iw * ppx, sy, sx), + None => {} + } + let (tw, th) = (iw / cols as f64, ih / rows as f64); + // Spacing is in points; convert to image pixels along each axis. + let gap = ((sx / ppx).min(tw * 0.9), (sy / ppy).min(th * 0.9)); let delete = switch_or(p, "deleteRaster", false, C)?; + Ok(MosaicPlan { id, im: im.as_ref().clone(), cols, rows, xf, tile: (tw, th), gap, gray, delete }) +} + +/// The tile counts (columns, rows) `object.createObjectMosaic` would use with `p`, Use Ratio +/// included, without making the mosaic (the dialog's Use Ratio button shows them). +pub fn mosaic_counts(s: &Session, p: &Value) -> Result<(u32, u32)> { + mosaic_plan(s, p).map(|m| (m.cols, m.rows)) +} + +fn object_mosaic(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.createObjectMosaic"; + let MosaicPlan { id, im, cols, rows, xf, tile: (tw, th), gap: (gx, gy), gray, delete } = mosaic_plan(s, p)?; + let blob = s.doc()?.doc.images.get(&im.key).ok_or_else(|| bad(C, "the image has no embedded pixels"))?; + let raster = vectorcraft_trace::Raster::decode(&blob.bytes).map_err(|e| bad(C, e.to_string()))?; + let colors = vectorcraft_trace::mosaic(&raster, cols, rows); let (gid, n) = s.edit("Create Object Mosaic", |d, sel| { let mut tiles = vec![]; for r in 0..rows { @@ -1039,7 +1124,32 @@ fn object_mosaic(s: &mut Session, p: &Value) -> Result { sel.set([gid]); Ok((gid, n)) })?; - Ok(json!({ "id": gid.0, "tiles": n })) + Ok(json!({ "id": gid.0, "tiles": n, "columns": cols, "rows": rows })) +} + +/// The tile count along one side of an Object Mosaic whose tiles, as drawn, come closest to square +/// (Use Ratio): `kept` tiles span `kept_len` on the other side, and this side is `other_len` long. +/// Each tile is its cell less the gap on its side (`kept_gap`, `other_gap`), and a gap takes at +/// most 90% of a cell, as the tiles are drawn. Within 1..1000, the smaller count on a tie; all +/// lengths in points. +pub(crate) fn mosaic_square_count(kept: u32, kept_len: f64, other_len: f64, kept_gap: f64, other_gap: f64) -> u32 { + let drawn = |len: f64, n: u32, gap: f64| { + let cell = len / n.max(1) as f64; + cell - gap.max(0.0).min(cell * 0.9) + }; + let side = drawn(kept_len, kept, kept_gap); + if !(side.is_finite() && side > 0.0 && other_len.is_finite() && other_len > 0.0) { + return 1; + } + // A tile on this side shrinks as the count grows: find the first count whose tile is no wider + // than `side`, then take it or the count before it, whichever is closer. + let (mut lo, mut hi) = (1u32, 1000u32); + while lo < hi { + let mid = (lo + hi) / 2; + if drawn(other_len, mid, other_gap) > side { lo = mid + 1 } else { hi = mid } + } + let off = |n: u32| (drawn(other_len, n, other_gap) - side).abs(); + if lo > 1 && off(lo - 1) <= off(lo) { lo - 1 } else { lo } } fn polygon_path(pts: &[Point]) -> PathData { diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index 84812dad97..d9d0905140 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -206,9 +206,10 @@ impl Session { } /// After each command: with New Art Has Basic Appearance off, new art takes the appearance of - /// the first selected object (so the last selection's once nothing is selected). + /// the first selected object (so the last selection's once nothing is selected). Not while the + /// Live Paint Bucket is the active tool: the fill and stroke are the colors it paints with. pub(crate) fn inherit_new_art(&mut self) { - if self.prefs.new_art_basic { + if self.prefs.new_art_basic || self.tool_id() == super::paint::LIVE_PAINT_BUCKET { return; } let Some(st) = self.active() else { return }; @@ -227,9 +228,11 @@ impl Session { if !self.prefs.new_art_basic { return; } - let has_paint = self - .proxy_source(false) - .is_some_and(|(n, _)| matches!(n.kind, NodeKind::Text(_)) || !n.appearance.items.is_empty() || n.extras().colorize.is_some()); + // A Live Paint group with edges and no faces shows only a stroke. + let has_paint = [false, true].into_iter().any(|stroke| { + self.proxy_source(stroke) + .is_some_and(|(n, _)| matches!(n.kind, NodeKind::Text(_)) || !n.appearance.items.is_empty() || n.extras().colorize.is_some()) + }); if !has_paint { return; } diff --git a/crates/engine/src/cmd/object/align.rs b/crates/engine/src/cmd/object/align.rs index d55fdda7b2..2b6e1b7e10 100644 --- a/crates/engine/src/cmd/object/align.rs +++ b/crates/engine/src/cmd/object/align.rs @@ -218,12 +218,32 @@ pub(super) fn align(s: &mut Session, p: &Value) -> Result { let ids = selected_roots(s)?; let m = measure(s, p, "object.align")?; let (h, v) = direction(p, "object.align")?; - choice(p, "object.align", "to", &["selection", "artboard", "key"])?; + let to = choice(p, "object.align", "to", &["selection", "artboard", "key", "auto"])?; check_switches(p, &["patterns"], "object.align")?; check_numbers(p, &["artboard"], "object.align")?; if h.is_none() && v.is_none() { return Err(bad("object.align", "give horizontal or vertical")); } + // Resolve only the explicit automatic target at this step, without changing the caller's + // parameters or selection. The existing reference/anchor/guide paths receive a concrete target. + let automatic_params = if to == Some("auto") { + let selection = &s.doc()?.selection; + let to = if selection.has_key() { + "key" + } else if selection.anchors.is_empty() && selection.len() == 1 { + "artboard" + } else { + "selection" + }; + let Some(mut params) = p.as_object().cloned() else { + return Err(bad("object.align", "expected an object of align parameters")); + }; + params.insert("to".into(), Value::String(to.into())); + Some(Value::Object(params)) + } else { + None + }; + let p = automatic_params.as_ref().unwrap_or(p); // Anchor points selected with Direct Selection align themselves, as in Illustrator (#1180). if !s.doc()?.selection.anchors.is_empty() { return align_anchors(s, p, &ids, (h, v)); diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index ff0b22b31b..a0f292fecf 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -334,6 +334,9 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result { if matches!(st.doc.node(id).ok_or(EngineError::NoNode(id))?.kind, NodeKind::Text(_)) { return Err(bad("object.isolate", "type objects can't be isolated")); } + if st.doc.node(id).is_some_and(|n| n.is_ruler_guide()) { + return Err(bad("object.isolate", "ruler guides can't be isolated")); + } let isolation = st.doc.node(id).filter(|n| n.extras().shaper.is_some()).and_then(|n| n.children()).and_then(|c| c.first()).map_or(id, |n| n.id); // A hidden or locked object, one in a hidden or locked group or layer, and a guide path while @@ -371,16 +374,21 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result { } /// Leaving isolation mode in `isolated` for `next` (None: out of isolation mode) adds the paths drawn -/// in the Live Paint group isolation put new art in to that group, as `livePaint.merge` does, in one -/// undo step ([`crate::cmd::buildcmds::merge_drawn_in_isolation`]), unless `next` is that group or is -/// inside it; → the group when paths were added. +/// in each Live Paint group that is `isolated` or holds it to that group, as `livePaint.merge` does, +/// innermost group first, one undo step per group ([`crate::cmd::buildcmds::merge_drawn_in_isolation`]). +/// A group that `next` is or is inside is skipped, since isolation stays in it. → the outermost group +/// that paths were added to. fn add_drawn_live_paint(s: &mut Session, isolated: NodeId, next: Option) -> Result> { let d = &s.doc()?.doc; - let Some(g) = crate::cmd::buildcmds::isolated_live_paint(d, isolated) else { return Ok(None) }; - if next.is_some_and(|n| d.ancestry(n).is_some_and(|a| a.contains(&g))) { - return Ok(None); + let stays = next.and_then(|n| d.ancestry(n)).unwrap_or_default(); + let left: Vec = crate::cmd::buildcmds::isolated_live_paints(d, isolated).into_iter().filter(|g| !stays.contains(g)).collect(); + let mut added = None; + for g in left { + if crate::cmd::buildcmds::merge_drawn_in_isolation(s, g)? { + added = Some(g); + } } - Ok(crate::cmd::buildcmds::merge_drawn_in_isolation(s, g)?.then_some(g)) + Ok(added) } pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 4be83d7da6..2f80e3b6c6 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -241,7 +241,7 @@ pub fn specs() -> Vec { "Enter Isolation Mode", [], None, - "{id?} isolate a group, a layer or a single object (default: the first selected object); type, a hidden or locked object, an object in a hidden or locked group or layer, and a guide path while Lock Guides is on are refused, and so is every object while an opacity mask is edited", + "{id?} isolate a group, a layer or a single object (default: the first selected object); type, a ruler guide, a hidden or locked object, an object in a hidden or locked group or layer, and a guide path while Lock Guides is on are refused, and so is every object while an opacity mask is edited", crate::cmd::maskedit::outside_mask_editing, isolate ), @@ -250,7 +250,7 @@ pub fn specs() -> Vec { "Exit Isolation Mode", [], None, - "{all?: bool (default false)} leave isolation mode; from an isolated sublayer, go up one level to its parent layer instead (the next call goes up again), unless all is true or the parent layer is hidden or locked; no undo step for the move up; while a symbol is edited, a group isolated in its art goes back to the symbol's layer first, with or without all; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same", + "{all?: bool (default false)} leave isolation mode; from an isolated sublayer, go up one level to its parent layer instead (the next call goes up again), unless all is true or the parent layer is hidden or locked; no undo step for the move up; while a symbol is edited, a group isolated in its art goes back to the symbol's layer first, with or without all; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same. Leaving a Live Paint group drawn in another isolated Live Paint group, and that group too, does this for each, innermost first, one undo step each", has_doc, exit_isolation ), @@ -259,7 +259,7 @@ pub fn specs() -> Vec { "Object Properties", [], None, - "{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's opacity and blend mode for every label or line of its kind", + "{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's opacity and blend mode for every label or line of its kind. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already", has_doc, set_props ), @@ -268,7 +268,7 @@ pub fn specs() -> Vec { "Align", ["Window", "Align"], None, - "{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes, geometry effects and projected 3D art), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, to the artboard (#1180), or, aligning to the key with a key anchor (select.key {id, anchor}), to the key anchor, which stays put", + "{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\"|\"auto\" (\"auto\": resolve at each call from the current selection: the key object, key anchor or key guide while set, else the artboard for exactly one selected object without selected anchors, else the selection; default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", or \"auto\" choosing the artboard, the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes, geometry effects and projected 3D art), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, to the artboard (#1180), or, aligning to the key with a key anchor (select.key {id, anchor}), to the key anchor, which stays put", has_selection_or_guides, align ), 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/transform.rs b/crates/engine/src/cmd/object/transform.rs index 7b1a97b4b3..f86d777e71 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -326,14 +326,15 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result { // Guides keep to the page's axes; art and anchors move along the constrain angle's. let (gx, gy) = (dx, dy); let (dx, dy) = along_constrain_angle(dx, dy, s.prefs.constrain_angle); - if !s.doc()?.selection.anchors.is_empty() { + let objects = transforms_objects(p); + if objects && !s.doc()?.selection.anchors.is_empty() { // When the anchors move by 0, the document and its undo history stay as they are. 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"), "interpolate": p.get("interpolate") })); } - if s.doc()?.selection.is_empty() { + if objects && s.doc()?.selection.is_empty() { let copy = bool_or(p, "copy", false); // When guides move by 0 without a copy, the document and its undo history stay as they are. if gx == 0.0 && gy == 0.0 && !copy { @@ -342,6 +343,21 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result { return crate::cmd::docmenu::guide_move(s, &json!({ "dx": gx, "dy": gy, "copy": copy })); } let ids = selected_roots_to_transform(s)?; + if !objects && !bool_or(p, "copy", false) { + // Pattern-only nudges of art without a pattern change nothing, including undo history. + if !bool_or(p, "patterns", s.prefs.transform_pattern_tiles) { + return ok(); + } + let st = s.doc()?; + let paths = st.doc.index_paths(ids.iter().copied()); + let mut uses_patterns = false; + for node in ids.iter().filter_map(|id| paths.get(id)).filter_map(|path| st.doc.node_at(path)) { + node.walk(&mut |n| uses_patterns |= vectorcraft_doc::pattern::uses_pattern(n, None)); + } + if !uses_patterns { + return ok(); + } + } apply_transform_moving_guides(s, "Move", ids, Affine::translate((dx, dy)), p, true, Some(Vec2::new(gx, gy))) } 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/paint.rs b/crates/engine/src/cmd/paint.rs index fddd6cdd9c..071c5f9862 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -4,7 +4,9 @@ use std::borrow::Cow; use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Color, GradientPaint, Paint}; -use vectorcraft_doc::{Appearance, CharStyle, Document, GraySource, Node, NodeId, NodeKind}; +use vectorcraft_doc::appearance::{FillLayer, StrokeLayer}; +use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Document, GraySource, Node, NodeId, NodeKind}; +use vectorcraft_tools::builder::{edges, faces, is_live_paint}; use super::appearance::{ItemTarget, edit_items, edit_items_then, item_target, row_targets}; use super::gradient::{item_paint_bounds, place_paint, place_run_paint, run_paint_mut, run_stroke_weight, unplaced}; @@ -14,6 +16,10 @@ use super::{ }; use crate::{DocState, EngineError}; +/// The Live Paint Bucket's tool id. While it is active, a fill or stroke color chosen for no +/// object in particular is the color it paints with ([`apply_paint`]). +pub(crate) const LIVE_PAINT_BUCKET: &str = "livePaintBucket"; + pub fn specs() -> Vec { vec![ cmd!( @@ -21,7 +27,7 @@ pub fn specs() -> Vec { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the color the bucket paints with) and the selection keeps its paint → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", has_doc, |s, p| set_paint(s, p, true) ), @@ -30,7 +36,7 @@ pub fn specs() -> Vec { "Stroke", [], None, - "{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill)} same as paint.setFill, for the stroke; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill", + "{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill)} same as paint.setFill, for the stroke; without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill", has_doc, |s, p| { set_paint(s, p, false) } ), @@ -39,7 +45,7 @@ pub fn specs() -> Vec { "Swap Fill and Stroke", [], Some("Shift+X"), - "{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md)", + "{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. A Live Paint group's faces take the stroke its edges share and its edges take the fill its faces share, a gradient fitted to each face or edge; a group whose faces' fills or edges' strokes differ (a freeform gradient counts as differing), or that has no face or no edge, keeps its paint. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change", has_doc, swap ), @@ -48,7 +54,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 (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)", + "{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. A Live Paint group's faces get no fill and its edges get a 0.5 pt black stroke, in place of their whole appearance and also when the Default Graphic Style is redefined, and with only Live Paint groups selected (or in ids) the defaults become no fill and a 0.5 pt black stroke (with New Art Has Basic Appearance off, new art then takes the selection's appearance, as after any command). 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). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change", has_doc, default_paint ), @@ -69,7 +75,7 @@ pub fn specs() -> Vec { "None", [], Some("/"), - "{} set the active proxy (fill or stroke) to None, as paint.setFill or paint.setStroke with none does → {objects}", + "{} set the active proxy (fill or stroke) to None, as paint.setFill or paint.setStroke with none does (while the Live Paint Bucket is the active tool, only the default changes) → {objects}", has_doc, |s, _| { let f = s.fill_active; @@ -96,7 +102,7 @@ pub fn proxy_specs() -> Vec { "Invert", [], None, - "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md); no undo step when no color changes → {changed}", + "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path; a Live Paint group recolors its faces' fills or its edges' strokes) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, or while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md); no undo step when no color changes → {changed}", has_doc, |s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert) ), @@ -105,7 +111,7 @@ pub fn proxy_specs() -> Vec { "Complement", [], None, - "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, the default; no undo step when no color changes → {changed}", + "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; a Live Paint group recolors its faces' fills or its edges' strokes as with paint.invert; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, or while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), the default; no undo step when no color changes → {changed}", has_doc, |s, p| proxy_recolor(s, p, "paint.complement", "Complement", &|c: Color| c.complement_keep_model()) ), @@ -114,7 +120,7 @@ pub fn proxy_specs() -> Vec { "Apply Last Color", [], Some(","), - "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default → {objects} (as paint.setFill)", + "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), to the default only) → {objects} (as paint.setFill)", has_doc, |s, p| { let paint = Paint::solid(s.last_solid); @@ -126,7 +132,7 @@ pub fn proxy_specs() -> Vec { "Apply Last Gradient", [], Some("."), - "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default → {objects} (as paint.setFill)", + "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), to the default only) → {objects} (as paint.setFill)", has_doc, |s, p| { let paint = super::gradient::unplaced(&Paint::Gradient(Box::new(s.last_gradient.clone()))); @@ -154,7 +160,7 @@ pub fn proxy_specs() -> Vec { "Fill and Stroke", [], None, - "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors)}", + "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, a Live Paint group's first face's fill and first edge's stroke, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, a Live Paint group counting with its faces' fills and its edges' strokes, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors)}", always, proxies ), @@ -178,10 +184,11 @@ impl Session { /// The fill and stroke the Fill/Stroke proxies show: the Appearance panel's active item (in the /// first selected object's own stack) for the proxy of its kind, else the first selected - /// object's (a group's first painted object's; type: its first run's), else the defaults for - /// new art. When the object whose fill the proxy shows is a gradient mesh with points picked - /// ([`Session::fill_mesh_points`]), the fill is its first picked point's color, which a solid - /// fill color changes. + /// object's (a group's first painted object's; a Live Paint group's first face's fill and first + /// edge's stroke, or the next selected object's when it has no face or edge; type: its first + /// run's), else the defaults for new art. When the object whose fill the proxy shows is a + /// gradient mesh with points picked ([`Session::fill_mesh_points`]), the fill is its first + /// picked point's color, which a solid fill color changes. pub fn proxy_paints(&self) -> (Paint, Paint) { let points = self.fill_mesh_points(); let show = |stroke: bool| match self.proxy_source(stroke) { @@ -196,8 +203,12 @@ impl Session { /// The object whose fill (or stroke) the proxy shows, with the Appearance panel's active item /// when it stands for it (see [`Session::proxy_paints`]); None: the defaults for new art. With /// an object of a dynamic symbol instance selected ([`DocState::selected_symbol_part`]), that - /// object as the instance draws it. + /// object as the instance draws it. None while the Live Paint Bucket is the active tool: the + /// proxies show the colors it paints with. pub(crate) fn proxy_source(&self, stroke: bool) -> Option<(Cow<'_, Node>, Option)> { + if self.tool_id() == LIVE_PAINT_BUCKET { + return None; + } let st = self.active()?; if let Some(part) = st.selected_symbol_part() { return Some((Cow::Owned(part), None)); @@ -207,9 +218,20 @@ impl Session { if first.appearance.item_of_kind(item, !stroke).is_some() { return Some((Cow::Borrowed(first), item)); } - let mut nodes = vec![]; - painted(first, true, &mut nodes); - nodes.first().map(|n| (Cow::Borrowed(*n), None)) + // A Live Paint group without faces (or edges) shows the next selected object's paint; any other + // object without a painted object shows the defaults for new art. + for id in st.selection.subjects() { + let Some(n) = st.doc.node(*id) else { continue }; + let mut nodes = vec![]; + painted(n, true, stroke, &mut nodes); + if let Some(n) = nodes.first() { + return Some((Cow::Borrowed(*n), None)); + } + if !is_live_paint(n) { + return None; + } + } + None } pub(crate) fn remember_paint_now(&mut self, p: &Paint) { @@ -250,21 +272,35 @@ fn same_in_proxy(a: &Paint, b: &Paint) -> bool { } } +/// The ids of the faces and edges of `n` when it is a Live Paint group, else none. +pub(crate) fn live_paint_parts(n: &Node) -> Vec { + if !is_live_paint(n) { + return vec![]; + } + faces(n).into_iter().chain(edges(n)).map(|part| part.id).collect() +} + /// The objects whose paints the proxies show for a selected `n`, the ones the paint commands /// change ([`leaf_targets`]): groups and layers stand for their contents (and so do blends and -/// other containers inside them), a compound path for its parts. -pub(crate) fn painted<'a>(n: &'a Node, top: bool, out: &mut Vec<&'a Node>) { +/// other containers inside them), a compound path for its parts. A Live Paint group stands for its +/// faces in the fill proxy (`stroke` false) and for its edges in the stroke proxy, the parts a fill +/// or a stroke given to it changes ([`live_paint_parts_skipped`]). +pub(crate) fn painted<'a>(n: &'a Node, top: bool, stroke: bool, out: &mut Vec<&'a Node>) { // A ruler guide has no paints. if n.is_ruler_guide() { return; } + if is_live_paint(n) { + out.extend(if stroke { edges(n) } else { faces(n) }.into_iter().map(|part| &**part)); + return; + } let expand = match n.kind { NodeKind::Group { .. } | NodeKind::Layer { .. } => true, NodeKind::Compound { .. } => false, _ => !top && n.is_container(), }; if expand { - n.children().into_iter().flatten().for_each(|c| painted(c, false, out)); + n.children().into_iter().flatten().for_each(|c| painted(c, false, stroke, out)); } else { out.push(n); } @@ -293,18 +329,31 @@ impl DocState { } // 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![]); + let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]); + // The faces and edges of the selected Live Paint groups: selected as well, they count with their group's. + let mut covered = std::collections::HashSet::new(); // 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); + if covered.contains(&n.id) { + continue; + } + covered.extend(live_paint_parts(n)); + painted(n, true, false, &mut fills); + painted(n, true, true, &mut strokes); } 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 set = if item.is_some() { + &selected + } else if stroke { + &strokes + } else { + &fills + }; 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(), @@ -331,7 +380,11 @@ impl DocState { impl Session { /// [`DocState::proxy_mixed`] of the active document for the Appearance panel's active item. /// A gradient mesh with points picked ([`Session::fill_mesh_points`]) counts with their colors. + /// Neither is mixed while the Live Paint Bucket is the active tool ([`Session::proxy_source`]). pub fn proxy_mixed(&self) -> (bool, bool) { + if self.tool_id() == LIVE_PAINT_BUCKET { + return (false, false); + } self.active().map_or((false, false), |st| st.proxy_mixed_with(self.appearance_item(), &self.fill_mesh_points())) } } @@ -478,6 +531,8 @@ fn apply_to_proxy(s: &mut Session, p: &Value, paint: Paint, cmd: &str) -> Result /// remember the paint. Replies `{objects}`: how many objects took the paint. pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) -> Result { let cmd = if fill { "paint.setFill" } else { "paint.setStroke" }; + let bucket = bucket_color_params(s, p, cmd)?; + let p = bucket.as_ref().unwrap_or(p); let focus = switch_or(p, "focus", true, cmd)?; let span = spans_targets(p, &paint).map_err(|e| bad(cmd, e))?; // Characters selected with the Type tool take the paint, not the whole type object (#1063). @@ -554,7 +609,7 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) } // Resolve the requested targets before mutating defaults or the active proxy. let item = item_target(s, p, cmd)?.of_kind(s, fill); - let selected = item.targets(s, p)?; + let selected = item.targets_for(s, p, fill)?; let ids = super::graph::paint_targets(&s.doc()?.doc, &selected); let of = super::appearance::reference_of(s, p, item, cmd)?; let paint = if span { @@ -682,6 +737,89 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) Ok(json!({"objects": ids.iter().collect::>().len()})) } +/// Is the Live Paint Bucket the active tool while `p` names no `ids`, `id` or `item`? A fill, +/// stroke or stroke weight chosen then is what the bucket paints with, so it goes to the defaults +/// and the selection keeps its paint. +pub(crate) fn for_bucket(s: &Session, p: &Value) -> bool { + // A null `ids` or `id` is no target, as `given_nodes` reads it; `item: null` names the top row. + s.tool_id() == LIVE_PAINT_BUCKET && ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) && p.get("item").is_none() +} + +/// `p` with `ids: []` when [`for_bucket`]: the paint goes to the defaults only. None otherwise. +/// A bad `target` or `aligned` is refused first, as it is without the bucket. +pub(crate) fn bucket_color_params(s: &Session, p: &Value, cmd: &str) -> Result> { + if !for_bucket(s, p) { + return Ok(None); + } + super::appearance::aligned(p, cmd)?; + super::appearance::targets_contents(p)?; + let mut v = p.as_object().cloned().unwrap_or_default(); + v.insert("ids".into(), json!([])); + Ok(Some(Value::Object(v))) +} + +/// The Live Paint groups in `roots` (or inside them), given or selected whole, with the ids of +/// their faces and of their edges, found where [`leaf_targets`] finds the objects a paint command +/// changes: a given or selected object other than a group or layer (a blend, say) and a compound +/// shape are painted as one object, and a Live Paint group kept among another one's hidden sources +/// is not one of them. The art of graph designs drawn in graph series is left out. +fn live_paint_groups(d: &Document, roots: &[NodeId]) -> Vec<(NodeId, Vec, Vec)> { + fn find<'a>(n: &'a Node, top: bool, out: &mut Vec<&'a Node>) { + let group = matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }); + if is_live_paint(n) { + out.push(n); + } else if (group || !top) && !n.is_compound_shape() && !matches!(n.kind, NodeKind::Compound { .. }) { + n.children().into_iter().flatten().for_each(|c| find(c, false, out)); + } + } + let mut found = vec![]; + for n in roots.iter().filter_map(|r| d.node(*r)) { + find(n, true, &mut found); + } + let mut seen = std::collections::HashSet::new(); + found.retain(|g| seen.insert(g.id)); + // A given or selected compound shape or compound path (or one inside a given or selected object) paints its members, + // also when one of them is given as well. A Live Paint group given inside one that is not given stays a Live Paint group. + let owns = |id: &NodeId| d.node(*id).is_some_and(|n| n.is_compound_shape() || matches!(n.kind, NodeKind::Compound { .. })); + let given: std::collections::HashSet = roots.iter().copied().collect(); + found.retain(|g| { + !d.ancestry(g.id).is_some_and(|up| { + let outer = up.iter().position(|a| given.contains(a)).unwrap_or(up.len()); + up.iter().skip(outer).any(|a| *a != g.id && owns(a)) + }) + }); + let kept: std::collections::HashSet = super::appearance::drop_design_art(d, found.iter().map(|g| g.id).collect()).into_iter().collect(); + let ids = |parts: Vec<&std::sync::Arc>| parts.into_iter().map(|part| part.id).collect(); + found.into_iter().filter(|g| kept.contains(&g.id)).map(|g| (g.id, ids(faces(g)), ids(edges(g)))).collect() +} + +/// Every object inside the Live Paint groups `groups` (faces, edges and the hidden source paths). +fn inside_live_paint(d: &Document, groups: &[(NodeId, Vec, Vec)]) -> std::collections::HashSet { + let mut out = std::collections::HashSet::new(); + for n in groups.iter().filter_map(|(g, _, _)| d.node(*g)) { + n.walk(&mut |c| { + if c.id != n.id { + out.insert(c.id); + } + }); + } + out +} + +/// The objects inside the Live Paint groups in `roots` (or inside them) that a fill (`fill`) or a +/// stroke given to the whole group leaves as they are: a fill paints the group's faces only, and a +/// stroke its edges only. Their edges (faces) and hidden source paths are left out. +pub(crate) fn live_paint_parts_skipped(d: &Document, roots: &[NodeId], fill: bool) -> std::collections::HashSet { + let groups = live_paint_groups(d, roots); + let mut out = inside_live_paint(d, &groups); + for (_, faces, edges) in &groups { + for id in if fill { faces } else { edges } { + out.remove(id); + } + } + out +} + /// The instance whose object is selected with Direct Selection, and that object's path /// ([`super::brushsym::selected_part`]), when `p` names no `ids`, `id` or `item`: the paint commands /// then change that object. A bad `target` or `aligned` is refused as it is for any other selection. @@ -986,18 +1124,62 @@ pub(super) fn restore_unpainted_stroke(ap: &mut Appearance, index: Option } } +/// The paint every one of `parts` has on top as its fill (`fill`) or stroke, swatch link included +/// and gradient placement left out ([`unplaced`]: each part fits it to its own bounds), or None +/// when they differ or there are none. A freeform gradient's points and their colors belong to the +/// part they sit on, so a freeform gradient on any part counts as a paint the parts do not share. +fn shared_paint(d: &Document, parts: &[NodeId], fill: bool) -> Option { + let mut paints = parts.iter().filter_map(|id| d.node(*id)).map(|n| if fill { n.appearance.fill_paint() } else { n.appearance.stroke_paint() }); + let first = paints.next()?; + let freeform = + |p: &Paint| matches!(p, Paint::Gradient(g) if g.gradient.kind == vectorcraft_color::GradientKind::Freeform || g.freeform.is_some()); + if freeform(&first) { + return None; + } + let first = unplaced(&first); + paints.all(|p| !freeform(&p) && unplaced(&p) == first).then_some(first) +} + fn swap(s: &mut Session, p: &Value) -> Result { + let bucket = bucket_color_params(s, p, "paint.swap")?; + let p = bucket.as_ref().unwrap_or(p); let targets = paint_targets(s, p)?; let given = !targets.is_empty(); - let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets); + // A whole Live Paint group: its faces take the stroke its edges share and its edges the fill its faces share. + let groups = live_paint_groups(&s.doc()?.doc, &super::targets(s, p)?); + let inside = inside_live_paint(&s.doc()?.doc, &groups); + let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets.into_iter().filter(|id| !inside.contains(id)).collect()); // Only design art was given or selected: nothing changes, the defaults included. - if given && ids.is_empty() { + if given && ids.is_empty() && groups.is_empty() { return ok(); } - if !ids.is_empty() { + if !ids.is_empty() || !groups.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 group whose faces' fills (or edges' strokes) differ or are freeform gradients, or that has no face or no edge, + // keeps its paint. + let swaps: Vec<(&[NodeId], &[NodeId], Paint, Paint)> = groups + .iter() + .filter_map(|(_, faces, edges)| { + Some((faces.as_slice(), edges.as_slice(), shared_paint(&before, faces, true)?, shared_paint(&before, edges, false)?)) + }) + .collect(); + let parts: Vec = groups.iter().flat_map(|(_, faces, edges)| faces.iter().chain(edges)).copied().collect(); super::overprint::edit_counted(s, "Swap Fill and Stroke", |d| { + for (faces, edges, fill, stroke) in &swaps { + for id in *faces { + if let Some(n) = d.node_mut(*id) { + n.appearance.set_fill(stroke.clone()); + } + } + for id in *edges { + if let Some(n) = d.node_mut(*id) { + restore_unpainted_stroke(&mut n.appearance, None, fill); + n.appearance.set_stroke(fill.clone()); + } + } + } + let parts_changed = super::appearance::count_changed(d, &before, &parts); for id in &ids { let Some(n) = d.node_mut(*id) else { continue }; if let NodeKind::Text(t) = &mut n.kind { @@ -1017,7 +1199,7 @@ fn swap(s: &mut Session, p: &Value) -> Result { // The swap writes the paint of the topmost fill and stroke, not their opacity. let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (false, false), true, false); let labels = super::graph::capture_label_changes(&before, d, &ids, false, None); - Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels)) + Ok(super::appearance::count_changed(d, &before, &ids) + parts_changed + usize::from(kept || labels)) })?; } if s.paint.stroke.is_none() && !s.paint.fill.is_none() && s.paint.stroke_width == 0.0 { @@ -1027,20 +1209,44 @@ fn swap(s: &mut Session, p: &Value) -> Result { ok() } +/// The weight of the stroke [`paint.default`](default_paint) gives the edges of a whole Live Paint group. +const LIVE_PAINT_DEFAULT_WEIGHT: f64 = 0.5; + fn default_paint(s: &mut Session, p: &Value) -> Result { + let bucket = bucket_color_params(s, p, "paint.default")?; + let p = bucket.as_ref().unwrap_or(p); let targets = paint_targets(s, p)?; let given = !targets.is_empty(); - let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets); + // A whole Live Paint group: its faces lose their fill and its edges take a black 0.5 pt stroke. + let groups = live_paint_groups(&s.doc()?.doc, &super::targets(s, p)?); + let inside = inside_live_paint(&s.doc()?.doc, &groups); + let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets.into_iter().filter(|id| !inside.contains(id)).collect()); // Only design art was given or selected: nothing changes, the defaults included. - if given && ids.is_empty() { + if given && ids.is_empty() && groups.is_empty() { return ok(); } - if !ids.is_empty() { + if !ids.is_empty() || !groups.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(); + let parts: Vec = groups.iter().flat_map(|(_, faces, edges)| faces.iter().chain(edges)).copied().collect(); super::overprint::edit_counted(s, "Default Fill and Stroke", |d| { + for (_, faces, edges) in &groups { + let face = Appearance { items: vec![AppearanceItem::Fill(FillLayer::new(Paint::None))], ..Appearance::default() }; + let edge = Appearance { + items: vec![AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), LIVE_PAINT_DEFAULT_WEIGHT))], + ..Appearance::default() + }; + for (ids, look) in [(faces, &face), (edges, &edge)] { + for id in ids { + if let Some(n) = d.node_mut(*id) { + n.appearance = look.clone().into(); + } + } + } + } + let parts_changed = super::appearance::count_changed(d, &before, &parts); for id in &ids { let Some(n) = d.node_mut(*id) else { continue }; match &mut n.kind { @@ -1067,10 +1273,20 @@ fn default_paint(s: &mut Session, p: &Value) -> Result { st.stroke = Paint::None; }); let lines = super::graph::capture_line_fill_stroke_rows(d, &ids); - Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels || lines)) + Ok(super::appearance::count_changed(d, &before, &ids) + parts_changed + usize::from(kept || labels || lines)) })?; } - super::newart::reset(s); + if ids.is_empty() && !groups.is_empty() { + // With only whole Live Paint groups given or selected, new art takes what their parts took, and nothing else. + s.paint = vectorcraft_tools::PaintDefaults { + fill: Paint::None, + stroke: Paint::solid(Color::BLACK), + stroke_width: LIVE_PAINT_DEFAULT_WEIGHT, + ..Default::default() + }; + } else { + super::newart::reset(s); + } ok() } @@ -1078,6 +1294,8 @@ fn default_paint(s: &mut Session, p: &Value) -> Result { /// default when there are none) and remember the first target's new paint. The Appearance panel's /// active item of the proxy's kind is recoloured in each selected object's own stack instead. fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result { + let bucket = bucket_color_params(s, p, cmd)?; + let p = bucket.as_ref().unwrap_or(p); let stroke = stroke_param(s, p, cmd)?; // An object of a dynamic symbol instance's art selected with Direct Selection: the solid color // it shows is recolored for this instance only. A gradient or pattern is refused, and so is type @@ -1174,11 +1392,20 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( if roots.is_empty() { return Ok(json!({ "changed": 0 })); } - let art = super::appearance::design_art_in(d, &roots).into_iter().collect(); - // The fill or stroke the proxy shows of each group among the roots, before the edit. + // A Live Paint group's fill is its faces' fills and its stroke its edges' strokes, also with `target: "contents"`; + // like any group, it recolors rows of its own as well. + let parts_skipped = live_paint_parts_skipped(d, &ids, !stroke); + let roots: Vec = roots.into_iter().filter(|id| !parts_skipped.contains(id)).collect(); + if roots.is_empty() { + return Ok(json!({ "changed": 0 })); + } + let mut art: std::collections::HashSet = super::appearance::design_art_in(d, &roots).into_iter().collect(); + art.extend(parts_skipped.iter().copied()); + // The fill or stroke the proxy shows of each group among the roots, before the edit (a Live Paint group shows + // its faces' or edges'). let own = |d: &Document, id: NodeId| { d.node(id) - .filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })) + .filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !is_live_paint(n)) .and_then(|n| n.proxy_paint_only(stroke, None)) .cloned() }; @@ -1196,7 +1423,8 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( shown_at = Some((*id, None)); break; } - if let Some(leaf) = super::appearance::drop_design_art(d, leaf_targets(s, &[*id])?).first() { + let leaves = leaf_targets(s, &[*id])?.into_iter().filter(|leaf| !parts_skipped.contains(leaf)).collect(); + if let Some(leaf) = super::appearance::drop_design_art(d, leaves).first() { shown_at = Some((*leaf, None)); break; } diff --git a/crates/engine/src/cmd/paint/tests.rs b/crates/engine/src/cmd/paint/tests.rs index 3da5d73d9e..77e061e993 100644 --- a/crates/engine/src/cmd/paint/tests.rs +++ b/crates/engine/src/cmd/paint/tests.rs @@ -11,7 +11,7 @@ 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 super::{live_paint_parts, painted, picked_colors, proxy_paint, same_in_proxy}; use crate::{DocState, Session}; thread_local! { @@ -38,17 +38,28 @@ fn walked(st: &DocState, item: Option, points: &[(NodeId, Vec)]) - return (false, false); } let ids: HashSet = st.selection.objects.iter().copied().collect(); - let (mut selected, mut nodes) = (vec![], vec![]); + let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]); + let mut covered = HashSet::new(); st.doc.walk(|n| { if ids.contains(&n.id) { selected.push(n); - painted(n, true, &mut nodes); + if !covered.contains(&n.id) { + covered.extend(live_paint_parts(n)); + painted(n, true, false, &mut fills); + painted(n, true, true, &mut strokes); + } } }); 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 set = if item.is_some() { + &selected + } else if stroke { + &strokes + } else { + &fills + }; 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(), diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 769cb530b0..13f7051223 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -67,7 +67,7 @@ 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), 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}", + "{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\"|name of a custom set (Kinsoku Set: Soft lets 々, ー and small kana start a line; a custom set of type.kinsokuSets.list, any case, keeps its own characters off a line's start and end, hangs its own hanging punctuation with burasagari and keeps its own inseparable sequences with bunriKinshi; a name the document has no set of fails the call), 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 the Kinsoku Set's overflowing hanging punctuation; 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, or with a custom set inside one of its inseparable sequences, 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: the Kinsoku Set's hanging punctuation ending an area type line hangs outside it: when it doesn't fit, or always; with None, Hard and Soft that is an East Asian comma or full stop, and a custom set hangs its own hanging characters; 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 ), @@ -755,11 +755,21 @@ fn set_format(s: &mut Session, p: &Value) -> Result { }; let kinsoku = match p.get("kinsoku") { None | Some(Value::Null) => None, + // A custom set (Type › Kinsoku Shori Settings…) by name: the paragraph holds a copy of it + // and keeps Hard, which builds without custom sets read. Some(v) => Some(match v.as_str() { - Some("none") => vectorcraft_doc::Kinsoku::None, - Some("hard") => vectorcraft_doc::Kinsoku::Hard, - Some("soft") => vectorcraft_doc::Kinsoku::Soft, - _ => return Err(bad(C, "`kinsoku` must be \"none\", \"hard\" or \"soft\"")), + Some("none") => (vectorcraft_doc::Kinsoku::None, None), + Some("hard") => (vectorcraft_doc::Kinsoku::Hard, None), + Some("soft") => (vectorcraft_doc::Kinsoku::Soft, None), + name => match name.map(|n| super::kinsokusets::chosen(s, n)).transpose()?.flatten() { + Some(set) => (vectorcraft_doc::Kinsoku::Hard, Some(set)), + None => { + return Err(bad( + C, + "`kinsoku` must be \"none\", \"hard\", \"soft\" or the name of a Kinsoku set of the document (type.kinsokuSets.list)", + )); + } + }, }), }; let kinsoku_type = match p.get("kinsokuType") { @@ -1058,8 +1068,9 @@ fn set_format(s: &mut Session, p: &Value) -> Result { if let Some(v) = mojikumi { para.mojikumi = v; } - if let Some(v) = kinsoku { - para.kinsoku = v; + if let Some((v, set)) = &kinsoku { + para.kinsoku = *v; + para.kinsoku_set = set.clone(); } if let Some(v) = kinsoku_type { para.kinsoku_type = v; diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 50e73f5a0d..8e7d7f7b0f 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -382,6 +382,7 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> { const EXCLUSIVE_KEYS: &[(&str, &str, &str)] = &[ ("addon.pathtools.cornerSet", "items", "ids"), ("addon.pathtools.cornerRemove", "items", "ids"), + ("addon.pathtools.bridge", "radius", "gap"), ("links.unembed", "id", "ids"), ("links.unembed", "path", "folder"), ]; diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 0960e5ca28..6d01cabd2a 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -50,7 +50,7 @@ pub fn specs() -> Vec { "Move Direction Handle", [], None, - "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool}", + "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, link?: bool, at?: [x,y]} 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; with link false, at moves the anchor and both handles before placing the chosen handle", has_doc, set_handle ), @@ -457,11 +457,19 @@ fn set_handle(s: &mut Session, p: &Value) -> Result { let ai = index_opt(p, "anchor", "path.setHandle")?.ok_or_else(|| bad("path.setHandle", "missing anchor"))?; let out = str_param(p, "which") != Some("in"); let pos = Point::new(f64_req(p, "x", "path.setHandle")?, f64_req(p, "y", "path.setHandle")?); + if switch_or(p, "link", false, "path.setHandle")? { + return link_handle(s, p, id, si, ai, out, pos); + } let independent = switch_or(p, "independent", false, "path.setHandle")?; + let at = match p.get("at").filter(|v| !v.is_null()) { + None => None, + Some(v) => Some(finite_numbers(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad("path.setHandle", "`at` must be [x, y]"))?), + }; // 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 // other handle of a smooth anchor, which need not give back the same value. if let Some(a) = anchor_of(s, id, si, ai)? + && at.is_none_or(|to| to == a.p) && (if out { a.h_out } else { a.h_in }) == pos && !(independent && a.kind != AnchorKind::Corner) { @@ -470,12 +478,145 @@ fn set_handle(s: &mut Session, p: &Value) -> Result { s.edit("Reshape", |d, _| { let path = path_mut(d, id)?; let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; - a.set_handle(out, pos, independent); + let old_point = a.p; + let old_handle = if out { a.h_out } else { a.h_in }; + if let Some(to) = at { + a.translate(to - a.p); + } + let handle = if out { a.h_out } else { a.h_in }; + let kind_changes = independent && a.kind != AnchorKind::Corner; + // Ordinary decimal moves can round `at - old_point` differently from the handle's + // translation. Within that calculation's roundoff, place the selected point exactly + // without realigning the other stored Smooth handle. Real edits still use set_handle. + let translation_roundoff = at.is_some_and(|to| { + let matches = |actual: f64, requested: f64, owner: f64, old: f64, new: f64| { + let scale = owner.abs().max(old.abs()).max(new.abs()).max(requested.abs()).max(1.0); + (actual - requested).abs() <= 4.0 * f64::EPSILON * scale + }; + to != old_point && matches(handle.x, pos.x, old_point.x, old_handle.x, to.x) && matches(handle.y, pos.y, old_point.y, old_handle.y, to.y) + }); + if !kind_changes && (handle == pos || translation_roundoff) { + if out { + a.h_out = pos; + } else { + a.h_in = pos; + } + } else { + a.set_handle(out, pos, independent); + } Ok(()) })?; 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 out { a.has_in() } else { a.has_out() }) && linked_already(a, out, pos)) + }) + }); + 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() +} + +/// Whether a smooth anchor `a` already has its `out` (or incoming) handle at `pos` and its other +/// handle exactly where [`Anchor::link_handle`] puts it for that handle at some positive length. +/// Turning the other handle again from its stored end measures its length anew, which can round +/// the end differently in the last bit; a handle that passes this test only gets that rounding, +/// and any other handle is turned. `p + u * len` here is the same arithmetic as in +/// `Anchor::link_handle`, `dir / l` included. +fn linked_already(a: &Anchor, out: bool, pos: Point) -> bool { + let (moved, other) = if out { (a.h_out, a.h_in) } else { (a.h_in, a.h_out) }; + let dir = a.p - pos; + let l = dir.x.hypot(dir.y); + if a.kind != AnchorKind::Smooth || moved != pos || !(l > 0.0 && l.is_finite()) { + return false; + } + let u = dir / l; + // The lengths that give each stored coordinate exactly; the smallest length both ranges hold + // is checked against the whole end. + let (mut lo, mut hi) = (0.0_f64, f64::INFINITY); + for (p, o, u) in [(a.p.x, other.x, u.x), (a.p.y, other.y, u.y)] { + if u == 0.0 { + if o != p { + return false; + } + continue; + } + let Some((first, last)) = lengths_onto(p, u, o) else { + return false; + }; + (lo, hi) = (lo.max(first), hi.min(last)); + } + lo <= hi && lo > 0.0 && lo.is_finite() && a.p + u * lo == other +} + +/// The lengths `len` for which `p + u * len` rounds to exactly `o`, as their smallest and largest, +/// for a `u` other than 0. The rounded sum moves the same way as `len`, so a range around the +/// unrounded answer is widened until it brackets `o` and then halved down to each end. +fn lengths_onto(p: f64, u: f64, o: f64) -> Option<(f64, f64)> { + let s = u.signum(); + let below = |len: f64| s * (p + u * len) < s * o; + let above = |len: f64| s * (p + u * len) > s * o; + let c = (o - p) / u; + let mut d = (o.abs() + p.abs()).max(f64::MIN_POSITIVE) * f64::EPSILON / u.abs(); + let mut bracket = None; + for _ in 0..64 { + if below(c - d) && above(c + d) { + bracket = Some((c - d, c + d)); + break; + } + d *= 2.0; + } + let (lo, hi) = bracket?; + let first = halve(lo, hi, |len| !below(len)).1; + let last = halve(lo, hi, above).0; + (first <= last).then_some((first, last)) +} + +/// Narrows `lo..hi`, where `pred` is false at `lo` and true at `hi` and changes once between +/// them, to two neighboring values with the same property. +fn halve(mut lo: f64, mut hi: f64, pred: impl Fn(f64) -> bool) -> (f64, f64) { + for _ in 0..2200 { + let m = lo + (hi - lo) / 2.0; + if m <= lo || m >= hi { + break; + } + if pred(m) { + hi = m; + } else { + lo = m; + } + } + (lo, hi) +} + /// `path.moveAnchor`: one anchor to (x, y), its handles keeping their offsets (the Anchor Point /// tool's Shift-drag). fn move_anchor(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 096f90bf36..9ff644ca6d 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -695,6 +695,7 @@ impl PlaceJob { /// the renderers' image store for the first frame that draws them /// ([`super::links::readable_and_kept`]). pub fn read(self) -> Result { + crate::cancel::check()?; let (mut loaded, slices) = load_sliced(&self.params, PLACE, self.target, true)?; let linked = loaded.link.is_some() && bool_or(&self.params, "link", true); match &mut loaded.art { @@ -1152,6 +1153,13 @@ pub fn read_info(p: &Value) -> Result { Ok(out) } +/// Resolution at a placed image's transform: 72 points per inch over each pixel axis. +pub(super) fn effective_ppi(xf: Affine) -> [f64; 2] { + let [a, b, c, d, ..] = xf.as_coeffs(); + let ppi = |x: f64, y: f64| Some(x.hypot(y)).filter(|l| *l > 1e-12).map_or(0.0, |l| 72.0 / l); + [ppi(a, b), ppi(c, d)] +} + pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result { const C: &str = "image.info"; let st = s.doc()?; @@ -1165,9 +1173,6 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result { let doc = super::links::with_brush_art(&st.doc); let n = doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?; let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) }; - // Effective resolution: 72 pt per inch over the points one pixel spans along each axis. - let [a, b, c, d, ..] = im.xf.as_coeffs(); - let ppi = |x: f64, y: f64| Some(x.hypot(y)).filter(|l| *l > 1e-12).map_or(0.0, |l| 72.0 / l); let size = n.geometric_bounds().unwrap_or_default(); // A linked file outside the read roots of the caller asking now is left unnamed, as in Link Info. let doc_path = super::links::LinkBase::of(st).doc; @@ -1179,7 +1184,7 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result { "colorMode": st.doc.images.get(&im.key).map_or("RGB", |b| color_mode(&b.bytes)), "pixelWidth": im.width, "pixelHeight": im.height, - "ppi": [ppi(a, b), ppi(c, d)], + "ppi": effective_ppi(im.xf), "width": size.width(), "height": size.height(), })) diff --git a/crates/engine/src/cmd/place/docx.rs b/crates/engine/src/cmd/place/docx.rs index 804e3fd6ae..6766b67c7c 100644 --- a/crates/engine/src/cmd/place/docx.rs +++ b/crates/engine/src/cmd/place/docx.rs @@ -171,8 +171,6 @@ fn parse(xml: &str, name: &str, cmd: &str) -> Result { craft_xml::Error::TooDeep(_) => bad(cmd, format!("`{name}` in the Word document nests elements more than {MAX_NESTING} deep")), _ => bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")), })?; - crate::cmd::xmlattrs::validate(xml.as_bytes(), opts.limits) - .map_err(|e| bad(cmd, format!("`{name}` in the Word document is not well-formed XML: {e}")))?; Ok(doc) } diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 80c8e7f2bf..e09e362550 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -46,6 +46,8 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.packaging.setRole", "addon.packaging.setRoleSwatch", "addon.pathtools.addPoints", + "addon.pathtools.boundingCircle", + "addon.pathtools.boundingRectangle", "addon.pathtools.bridge", "addon.pathtools.close", "addon.pathtools.commonTangents", @@ -88,6 +90,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.type.textTweaker", "addon.units.convert", "addon.units.selectionSize", + "app.toast", "appearance.addEffect", "appearance.addFill", "appearance.addStroke", @@ -177,6 +180,7 @@ pub(super) const ALLOWED: &[&str] = &[ "edit.duplicate", "edit.findNext", "edit.findReplace", + "edit.replaceMatch", "effect.apply", "effect.deferredStatus", "effect.duplicate", @@ -459,6 +463,7 @@ pub(super) const ALLOWED: &[&str] = &[ "path.mirrorCut", "path.moveAnchor", "path.moveAnchors", + "path.quickPen", "path.rectCut", "path.removeAnchor", "path.removeAnchors", @@ -555,6 +560,8 @@ pub(super) const ALLOWED: &[&str] = &[ "select.update", "shape.arc", "shape.circleThroughPoints", + "shape.curvatureCircle", + "shape.editFlare", "shape.ellipse", "shape.flare", "shape.line", @@ -597,6 +604,7 @@ pub(super) const ALLOWED: &[&str] = &[ "swatch.move", "swatch.new", "swatch.newGroup", + "swatch.renameGroup", "swatch.resetDefaults", "swatch.setSpot", "swatch.sortByKind", @@ -620,6 +628,7 @@ pub(super) const ALLOWED: &[&str] = &[ "symbol.replace", "symbol.selectInstances", "symbol.setCurrent", + "symbol.setDensity", "symbol.sortByName", "symbol.spray", "symbol.unused", @@ -658,6 +667,7 @@ pub(super) const ALLOWED: &[&str] = &[ "text.thread.remove", "text.touchType", "threeD.addGraphic", + "threeD.mapArt", "threeD.mapGraphic", "transparency.disableOpacityMask", "transparency.editOpacityMask", @@ -681,6 +691,9 @@ pub(super) const ALLOWED: &[&str] = &[ "type.fillPlaceholder", "type.fitHeadline", "type.insert", + "type.kinsokuSets.base", + "type.kinsokuSets.list", + "type.kinsokuSets.set", "type.opticalMarginAlignment", "type.orientation.horizontal", "type.orientation.vertical", @@ -689,6 +702,8 @@ pub(super) const ALLOWED: &[&str] = &[ "type.pathOptions", "type.resetHorizontalScale", "type.resetTracking", + "type.retype", + "type.retypeFonts", "type.ruby", "type.scaleTextAttributes", "type.size.decrease", diff --git a/crates/engine/src/cmd/preflight.rs b/crates/engine/src/cmd/preflight.rs new file mode 100644 index 0000000000..ebfaf5deeb --- /dev/null +++ b/crates/engine/src/cmd/preflight.rs @@ -0,0 +1,133 @@ +//! Production preflight: the existing output-aware type walk, linked-file probes and image +//! resolution calculation, returned as findings that the interface can locate and recheck. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; +use vectorcraft_text::{FontDb, FontMatch}; + +use super::{CommandSpec, Result, Session, bad, cmd, has_doc, number_or, text_param}; + +const COMMAND: &str = "document.preflight"; +const KINDS: [&str; 4] = ["fonts", "text", "links", "resolution"]; + +pub fn specs() -> Vec { + vec![cmd!( + query "document.preflight", + "Production Preflight", + [], + None, + "{output?: pdf|print|screen (pdf), minPpi?: 1..9600 (300, or 96 for screen), artboards?: [index, …] (0-based whole numbers; default all)} check the selected output without writing files or editing the document; print reuses the saved print settings with these artboards, pdf and screen check visible artwork on these artboards. Reuses output-aware font and overflow checks, Links file status and image.info effective resolution. Resource findings locate their first visible canvas owner; resolution inside resource art is reported as not checked because its placed scale can differ. → {output, minPpi, artboards, checks: [{kind: fonts|text|links|resolution, status: passed|failed|notChecked, count, notChecked}], findings: [{kind, code, ids (canvas objects), name, detail?, sourceId?, effectivePpi?, threshold?}], outputWarnings, limitations}; a pass covers only these checks, not certification of a produced file", + has_doc, + check + )] +} + +fn check(s: &mut Session, p: &Value) -> Result { + let output = text_param(p, "output", COMMAND)?.unwrap_or("pdf"); + if !matches!(output, "pdf" | "print" | "screen") { + return Err(bad(COMMAND, "output must be pdf, print or screen")); + } + let min_ppi = number_or(p, "minPpi", if output == "screen" { 96.0 } else { 300.0 }, COMMAND)?; + if !min_ppi.is_finite() || !(1.0..=9600.0).contains(&min_ppi) { + return Err(bad(COMMAND, "minPpi must be from 1 to 9600")); + } + let indices = match p.get("artboards").filter(|v| !v.is_null()) { + Some(v) => super::panelcmds::listed_artboards(&s.doc()?.doc, v, "artboards", COMMAND)?, + None => (0..s.doc()?.doc.artboards.len()).collect(), + }; + let context = if output == "print" { + super::print::preflight_context(s, &indices)? + } else { + let doc = &s.doc()?.doc; + let pages = indices.iter().filter_map(|i| doc.artboards.get(*i).map(|a| (a.rect, vectorcraft_geom::Affine::IDENTITY))).collect(); + super::print::PreflightContext { layers: vectorcraft_pdf::PrintLayers::Visible, pages, warnings: vec![] } + }; + let areas = context.pages.iter().map(|(r, _)| *r).collect::>(); + let st = s.doc()?; + let doc = st.doc.with_placed_art(); + let mut layers = doc.layers.clone(); + vectorcraft_pdf::keep_layers(&mut layers, context.layers); + let typed = super::fonts::preflight_type(&doc, &layers, &areas); + let statuses = super::links::statuses(st); + let mut findings = vec![]; + let db = FontDb::global(); + for (font, ids) in typed.fonts { + let code = match db.resolve(&font.0, &font.1).map(|(_, m)| m) { + None | Some(FontMatch::Missing) => "missingFont", + Some(FontMatch::Style) => "substitutedFont", + _ => continue, + }; + findings.push( + json!({ "kind": "fonts", "code": code, "ids": ids.iter().map(|i| i.0).collect::>(), "name": super::fonts::font_label(&font) }), + ); + } + for id in typed.overflow { + findings.push(finding("text", "overflow", id, &doc)); + } + let mut resolution_unchecked = 0usize; + for (source, owner) in typed.images { + if let Some((status, _, _)) = statuses.get(&source) { + let code = match status.as_str() { + "missing" => Some("missingLink"), + "modified" => Some("modifiedLink"), + _ => None, + }; + if let Some(code) = code { + let mut f = finding("links", code, owner, &doc); + f["sourceId"] = json!(source.0); + findings.push(f); + } + } + // A vector placed document has no single bitmap resolution. Its embedded artwork, and + // resources with their own coordinate systems, must never be certified at a local scale. + if doc.node(source).is_none() || source != owner { + resolution_unchecked += 1; + continue; + } + let Some(vectorcraft_doc::NodeKind::Image(im)) = doc.node(source).map(|n| &n.kind) else { + resolution_unchecked += 1; + continue; + }; + let bounds = doc.node(source).and_then(|n| vectorcraft_render::painted_bounds(&doc, n)); + let ppi = context + .pages + .iter() + .filter(|(area, _)| bounds.is_some_and(|b| area.intersect(b).area() > 0.0)) + .map(|(_, to_page)| super::place::effective_ppi(*to_page * im.xf)) + .reduce(|[a, b], [c, d]| [a.min(c), b.min(d)]); + let Some(ppi) = ppi else { + resolution_unchecked += 1; + continue; + }; + // Inverting the placed-size transform can round an exact threshold slightly down. + if ppi.iter().any(|n| !n.is_finite() || *n <= 0.0) { + resolution_unchecked += 1; + } else if ppi.iter().any(|n| *n < min_ppi * (1.0 - 1e-9)) { + let mut f = finding("resolution", "lowResolution", owner, &doc); + f["effectivePpi"] = json!(ppi); + f["threshold"] = json!(min_ppi); + findings.push(f); + } + } + let checks = KINDS.map(|kind| { + let count = findings.iter().filter(|f| f["kind"] == kind).count(); + let not_checked = if kind == "resolution" { resolution_unchecked } else { 0 }; + let status = if count > 0 { + "failed" + } else if not_checked > 0 { + "notChecked" + } else { + "passed" + }; + json!({ "kind": kind, "status": status, "count": count, "notChecked": not_checked }) + }); + Ok(json!({ + "output": output, "minPpi": min_ppi, "artboards": indices, "checks": checks, + "findings": findings, "outputWarnings": context.warnings, + "limitations": ["These checks do not certify an exported file.", "Resolution inside symbols, patterns, brushes, opacity masks and placed documents is not checked."] + })) +} + +fn finding(kind: &str, code: &str, id: NodeId, doc: &vectorcraft_doc::Document) -> Value { + json!({ "kind": kind, "code": code, "ids": [id.0], "name": doc.node(id).map(|n| n.display_name()).unwrap_or_else(|| id.0.to_string()) }) +} diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 774c450065..f66322498e 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -142,6 +142,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("interpolateControlPoints", "General", "Options", "Interpolate Control Points When Moving Anchors", bool), p!("usePreciseCursors", "General", "Options", "Use Precise Cursors", bool), p!("showToolTips", "General", "Options", "Show Tool Tips", bool), + p!("showToolCards", "General", "Options", "Show Tool Cards", bool), p!("showExternalScriptWarning", "General", "Options", "Show External Script Warning", bool), p!("antiAliasedArtwork", "General", "Options", "Anti-aliased Artwork", bool), p!("selectSameTintPercent", "General", "Options", "Select Same Tint %", bool), @@ -157,6 +158,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("scrubNumericFields", "General", "Options", "Scrub Numeric Fields by Dragging", bool), p!("trackpadRotateView", "General", "Options", "Trackpad Gesture to Rotate View", bool), p!("holdToolKeys", "General", "Options", "Hold a Tool Shortcut to Use the Tool Temporarily", bool), + p!("holdShortcuts", "General", "Options", "Hold Shortcuts", bool), + p!("keyHoldDelay", "General", "Options", "Hold Shortcut Delay", num(0.2, 1.0, "s")), p!("boundingBoxWhileMovingAndDrawing", "General", "Options", "Show Bounding Box While Moving and Drawing", bool), // Selection & Anchor Display p!("selectionTolerance", "Selection & Anchor Display", "Selection", "Tolerance", num(1.0, 8.0, "px")), @@ -453,6 +456,8 @@ pub const PREF_SPECS: &[PrefSpec] = &[ choice(&[("default", "Default"), ("object", "Transform Object Only"), ("pattern", "Transform Pattern Only"), ("both", "Transform Both")]) ), p!("useRegistrationPointForSymbol", "General", "Transform Panel", "Use Registration Point for Symbol", bool), + // The Transform panel menu: drawing a shape shows the panel. + p!("showOnShapeCreation", "General", "Transform Panel", "Show on Shape Creation", bool), // The Align panel menu's Align to Glyph Bounds: Align and Distribute measure type by its glyphs' ink. p!("alignGlyphBoundsPoint", "Type", "Align to Glyph Bounds", "Point Text", bool), p!("alignGlyphBoundsArea", "Type", "Align to Glyph Bounds", "Area Text", bool), diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 0826e848cf..8c507db007 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -147,6 +147,32 @@ fn preview(s: &mut Session, p: &Value) -> Result { Ok(v) } +/// Reuse the Print dialog's saved settings and page geometry for production preflight, without +/// printing, writing a file or duplicating its type warnings. +pub(super) struct PreflightContext { + pub layers: PrintLayers, + pub pages: Vec<(Rect, Affine)>, + pub warnings: Vec, +} + +pub(super) fn preflight_context(s: &Session, indices: &[usize]) -> Result { + let settings = + json!({ "settings": { "artboards": "range", "range": indices.iter().map(|i| (i + 1).to_string()).collect::>().join(",") } }); + let set = preset_or_saved("document.preflight", s, &s.doc()?.doc, &settings)?; + super::printadvanced::flattener("document.preflight", &set, &s.prefs.flattener_presets)?; + let mut pv = vectorcraft_pdf::preview(&s.doc()?.doc, &set).map_err(|e| pdf_error("document.preflight", e))?; + let pages = pv + .sheets + .iter() + .filter_map(|p| { + let to_page = Affine::new(p.transform); + on_page(Rect::new(p.area[0], p.area[1], p.area[2], p.area[3]), to_page, (p.width, p.height)).map(|area| (area, to_page)) + }) + .collect(); + pv.warnings.extend(pv.setting_notes); + Ok(PreflightContext { layers: set.print_layers, pages, warnings: pv.warnings }) +} + /// The parts of the document (document space) that the pages of `pv` print. fn areas(pv: &PrintPreview) -> Vec { pv.sheets diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index cb179148cc..1c3acf4e73 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -34,7 +34,7 @@ pub fn specs() -> Vec { "Recolor Artwork", ["Edit", "Edit Colors"], None, - "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what `group` is rewritten with, a null removing the group's swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the swatches it adds nothing; refused for a swatch that is not a colour); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", + "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null | \"keep\"] (what the color swatches of `group` are rewritten with, in order: a gradient, pattern or None swatch keeps its place and paint; a null removing the color swatch at its place and \"keep\" leaving that swatch its colour, without the Global Adjust (past the color swatches it adds nothing); default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}", has_doc, apply ), @@ -1680,12 +1680,18 @@ fn apply(s: &mut Session, p: &Value) -> Result { Some(Value::Array(cs)) => Some(cs), Some(_) => return Err(bad(C, "`groupColors` must be an array")), }; - // A null in groupColors removes the group's swatch at its place, and "keep" leaves the swatch - // at its place its color, without the Global Adjust. - let own: Vec> = match group { - Some(g) => { - s.doc()?.doc.swatch_groups.iter().find(|x| x.name == g).map(|g| g.swatches.iter().map(|w| w.paint.color()).collect()).unwrap_or_default() - } + // The places of groupColors are those of the group's color swatches: a gradient, pattern or + // None swatch keeps its place and paint. A null removes the color swatch at its place, and + // "keep" leaves it its color, without the Global Adjust. + let own: Vec = match group { + Some(g) => s + .doc()? + .doc + .swatch_groups + .iter() + .find(|x| x.name == g) + .map(|g| g.swatches.iter().filter_map(|w| w.paint.color()).collect()) + .unwrap_or_default(), None => vec![], }; let new: Vec> = match group_colors { @@ -1694,12 +1700,8 @@ fn apply(s: &mut Session, p: &Value) -> Result { .enumerate() .map(|(i, v)| match v { Value::Null => Ok(None), - // Past the group's swatches it adds nothing. - Value::String(k) if k == "keep" => match own.get(i) { - Some(Some(c)) => Ok(Some(*c)), - Some(None) => Err(bad(C, format!("the swatch at place {i} of groupColors is not a colour to keep"))), - None => Ok(None), - }, + // Past the group's color swatches it adds nothing. + Value::String(k) if k == "keep" => Ok(own.get(i).copied()), v => color_value(v) .map(|c| adjust.apply(c)) .map(|c| Some(in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c))))) @@ -1747,6 +1749,7 @@ fn apply(s: &mut Session, p: &Value) -> Result { .map(|g| { g.swatches .iter() + .filter(|w| w.paint.color().is_some()) .zip(&new) .filter(|(w, _)| w.global && !w.is_reserved()) .filter_map(|(w, c)| Some((w, (*c)?))) @@ -1766,7 +1769,7 @@ fn apply(s: &mut Session, p: &Value) -> Result { .collect(); map.converted.set(false); let changed = keeping_series_paint(d, &ids, |d| Ok(Recolor::with_links(scope, &f, &lf).run(d, &ids)))?; - let edit = group.map(|g| super::swatch::rewrite_group(d, g, &new, rename, C)).transpose()?; + let edit = group.map(|g| super::swatch::rewrite_group(d, g, &new, true, rename, C)).transpose()?; super::paint::check_colorized_kept(colorized_ok, d).map_err(|e| bad(C, e))?; // Rewriting the group's swatches can change the colors of art linked to them, left out or // not, and of the patterns it uses. Art that only loses its link keeps its colors and is diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs new file mode 100644 index 0000000000..cb548bd46e --- /dev/null +++ b/crates/engine/src/cmd/retype.rs @@ -0,0 +1,622 @@ +//! Type › Retype (#4934), phase 1: outlined text whose glyph shapes are glyphs of a font the app +//! has becomes live point text again, in that font and size, at the same baseline. +//! +//! Behaviour follows the public description of Illustrator's Retype +//! (, +//! ): +//! select outlined text and Retype finds the fonts that match it, from the fonts on the device among +//! others, for use as live text. Illustrator ranks candidate fonts in a panel; this phase is local +//! and exact instead, and sets the text itself, as #4934 asks. Each selected glyph shape (a path or compound +//! path, inside groups too) is compared with the glyphs of the candidate fonts +//! ([`vectorcraft_text::retype`]), the same up to uniform scale, rotation and translation. Matched +//! glyphs map back to characters through the font's cmap and are rebuilt as point text, one object +//! per line of glyphs, with the first glyph's fill and stroke. Shapes that match no font stay as +//! they are and are reported. Near matches (another version of the font, simplified outlines, +//! merged glyphs) and images are phase 2. + +use std::f64::consts::{PI, TAU}; +use std::sync::Arc; + +use kurbo::{BezPath, Point, Vec2}; +use serde_json::{Value, json}; +use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_text::FontDb; +use vectorcraft_text::retype::{GlyphMatch, RetypeIndex}; + +use super::edit::selected_roots; +use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_selected_path}; + +/// At most this many shapes are compared. +const MAX_PIECES: usize = 2048; +/// Groups deeper than this are not looked into. +const MAX_DEPTH: usize = 16; +/// Extra families named by `fonts`. +const MAX_FONT_PARAMS: usize = 32; + +pub fn specs() -> Vec { + vec![cmd!( + "type.retype", + "Retype", + ["Type"], + None, + "{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live point text: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); matched glyphs become point text in that font and size at the same baseline, one object per line, with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line splits where its type would not draw the outlines' glyphs in their places (tracking, manual spacing, font substitutions); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts, fonts: [{family, style, size}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches", + has_selected_path, + retype + )] +} + +#[path = "retype_fonts.rs"] +pub(super) mod fonts; + +/// A shape to match: a path or compound path, in document space. +struct Piece { + id: NodeId, + /// The group or layer holding it: glyphs of different groups, which may composite + /// differently, never share a line. + parent: Option, + /// Other art (not retyped) lies between it and the shape before it, so the type after that + /// art must stay painted after it: the line ends here. + after_barrier: bool, + path: BezPath, + appearance: Appearance, + /// The shape's own transparency, which the new type takes. + opacity: f32, + blend: vectorcraft_color::BlendMode, + /// The shape has what type cannot take (its own opacity mask, more than one fill or stroke, + /// effects, a brush, width profile or arrowheads): it stays an outline. + keeps_outline: bool, +} + +/// The shapes in `n` (held by `parent`), in paint order. `barrier` is set when art that is not a +/// shape lies before the next one; it starts set for a root that does not follow the last root. +/// `truncated` is set when shapes past [`MAX_PIECES`] or [`MAX_DEPTH`] were left out. +fn collect(n: &Node, parent: Option, depth: usize, barrier: &mut bool, truncated: &mut bool, out: &mut Vec) { + if out.len() >= MAX_PIECES || depth > MAX_DEPTH { + *barrier = true; + *truncated = true; + return; + } + // Hidden and locked art is left as it is: a hidden glyph must not come back as visible type. + if !n.visible || n.locked { + *barrier = true; + return; + } + let piece = |path: BezPath, after_barrier: bool| Piece { + id: n.id, + parent, + after_barrier, + path, + appearance: (*n.appearance).clone(), + opacity: n.opacity, + blend: n.blend, + keeps_outline: n.extras().mask.is_some() || !type_can_paint(&n.appearance), + }; + match &n.kind { + NodeKind::Group { children, clip: false } => { + for c in children { + collect(c, Some(n.id), depth + 1, barrier, truncated, out); + } + } + // Only closed shapes can be glyphs: an open path stroked along a glyph's outline is not one. + NodeKind::Path { path, clipping: false, guide: false, .. } if path.is_closed() => out.push(piece(path.to_bezpath(), std::mem::take(barrier))), + NodeKind::Compound { children, .. } => { + let mut path = BezPath::new(); + for c in children { + match &c.kind { + // A hidden or locked path keeps its whole compound as it is. + NodeKind::Path { path: p, .. } if p.is_closed() && c.visible && !c.locked => path.extend(p.to_bezpath()), + _ => { + *barrier = true; + return; + } + } + } + out.push(piece(path, std::mem::take(barrier))); + } + // Live type, images, clip groups and the rest stay, and the type after them stays after them. + _ => *barrier = true, + } +} + +/// Can type's character style paint `ap` as it is: a basic appearance (at most one fill and one +/// stroke, no effects, no item opacity or blend), with a plain stroke? +fn type_can_paint(ap: &Appearance) -> bool { + ap.is_basic() && ap.stroke().is_none_or(|s| s.start_arrow.is_none() && s.end_arrow.is_none() && s.profile.is_none() && s.brush.is_none()) +} + +/// The faces to match against: the families in `fonts`, the document's fonts, then every loaded face. +fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec> { + let mut families: Vec = fonts.iter().take(MAX_FONT_PARAMS).cloned().collect(); + d.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + for r in &t.runs { + if !families.contains(&r.style.font_family) && families.len() < vectorcraft_text::retype::MAX_FACES { + families.push(r.style.font_family.clone()); + } + } + } + }); + let cap = vectorcraft_text::retype::MAX_FACES; + let mut faces = vec![]; + 'families: for f in &families { + for style in db.styles(f) { + // No more faces are loaded than the index takes. + if faces.len() >= cap { + break 'families; + } + if let Some(face) = db.face(f, &style) + && !faces.iter().any(|k: &Arc| k.id() == face.id()) + { + faces.push(face); + } + } + } + for face in db.loaded_faces() { + if faces.len() >= cap { + break; + } + if !faces.iter().any(|k| k.id() == face.id()) { + faces.push(face); + } + } + faces +} + +/// One line of retyped glyphs. +struct Line { + pieces: Vec, + /// What each piece matched, as `pieces`. + matches: Vec, + /// Every glyph the first piece fits, while the line holds only it: the next glyph may tell + /// which one it is (see [`join`]). + first_cands: Vec, + text: String, + face: Arc, + scale: f64, + angle: f64, + origin: Point, + end: Point, + appearance: Appearance, + parent: Option, + opacity: f32, + blend: vectorcraft_color::BlendMode, +} + +impl Line { + fn dir(&self) -> Vec2 { + Vec2::new(self.angle.cos(), self.angle.sin()) + } + + /// Does glyph `m` of shape `pc` continue this line (same group, paint and transparency, same + /// font, size and turn, on its baseline, after its end)? + fn continues(&self, pc: &Piece, m: &GlyphMatch) -> bool { + let size = self.scale * self.face.units_per_em(); + let d = m.origin - self.origin; + let dir = self.dir(); + let across = d.cross(dir).abs(); + pc.parent == self.parent + && pc.appearance == self.appearance + && pc.opacity == self.opacity + && pc.blend == self.blend + && m.face.id() == self.face.id() + // One size and turn for the whole line: the type sets every glyph at the first one's. + && (m.scale - self.scale).abs() <= self.scale * 1e-4 + // Wrapped: type turned 180° has angles near +π and −π. + && ((m.angle - self.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5 + && across < size * 0.05 + && (m.origin - self.end).dot(dir) > -size * 0.25 + } + + fn push(&mut self, id: NodeId, m: &GlyphMatch) { + // A gap wider than half a space before the glyph is spaces the outlines left no shape for. + let dir = self.dir(); + let gap = (m.origin - self.end).dot(dir); + let space = space_advance(&self.face) * self.scale; + if space > 0.0 && gap > space * 0.5 { + let n = ((gap / space).round() as usize).clamp(1, 64); + self.text.extend(std::iter::repeat_n(' ', n)); + } + self.text.push(m.ch); + self.pieces.push(id); + self.matches.push(m.clone()); + self.end = m.origin + dir * (m.face.advance(m.gid) * m.scale); + } + + /// The line of this one's glyphs `from..to`, with its group, paint and transparency. + fn part(&self, from: usize, to: usize) -> Option { + let (ids, ms) = (self.pieces.get(from..to)?, self.matches.get(from..to)?); + let (first, m) = (ids.first()?, ms.first()?); + let dir = Vec2::new(m.angle.cos(), m.angle.sin()); + let mut l = Line { + pieces: vec![*first], + matches: vec![m.clone()], + first_cands: vec![], + text: m.ch.to_string(), + face: m.face.clone(), + scale: m.scale, + angle: m.angle, + origin: m.origin, + end: m.origin + dir * (m.face.advance(m.gid) * m.scale), + appearance: self.appearance.clone(), + parent: self.parent, + opacity: self.opacity, + blend: self.blend, + }; + for (id, m) in ids.iter().zip(ms).skip(1) { + l.push(*id, m); + } + Some(l) + } + + /// The point type that sets this line. + fn text_object(&self, system_layout: bool) -> TextObject { + let style = CharStyle { + font_family: self.face.family.clone(), + font_style: self.face.style.clone(), + // The version that matched, when two of the family and style are loaded. + font_version: (!self.face.version.is_empty()).then(|| self.face.version.clone()), + // Each outlined glyph was drawn on its own; a ligature would draw another shape. + features: vec!["-liga".into()], + size: self.scale * self.face.units_per_em(), + fill: self.appearance.fill_paint(), + stroke: self.appearance.stroke_paint(), + stroke_width: self.appearance.stroke_width(), + ..Default::default() + }; + let mut style = style; + if let Some(st) = self.appearance.stroke() { + style.stroke_cap = st.cap; + style.stroke_join = st.join; + style.stroke_miter_limit = st.miter_limit; + style.stroke_dash = st.dash.clone(); + style.stroke_align = st.align; + } + let mut t = TextObject::point(self.origin, &self.text, style); + if self.angle != 0.0 { + t.xf *= kurbo::Affine::rotate(self.angle); + } + t.para = super::create::new_type_para(); + t.system_layout = system_layout; + super::typecmd::refresh_bounds(&mut t); + t + } + + /// The first of this line's glyphs its type does not draw as the outlines did: another glyph + /// (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing, + /// more space than whole spaces make); `None` when the type draws every glyph in its place. + fn first_mismatch(&self, t: &TextObject) -> Option { + let lay = vectorcraft_text::layout(FontDb::global(), t); + let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()); + let tol = (self.scale * self.face.units_per_em() * 0.01).max(0.01); + for (k, m) in self.matches.iter().enumerate() { + let Some(g) = drawn.next() else { return Some(k) }; + let at = t.xf * (g.xf * Point::ORIGIN); + if g.font_id != m.face.id() || g.gid != m.gid || at.distance(m.origin) > tol { + return Some(k); + } + } + // Ink the outlines did not have: the last glyph is where it went wrong. + drawn.next().map(|_| self.matches.len().saturating_sub(1)) + } +} + +/// `lines` checked against their own layout: a line splits where its type stops drawing the +/// outlines, and a glyph its type cannot draw even on its own stays an outline (`unmatched`). +/// The glyphs laid out are bounded by a multiple of the number of glyphs. +fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) -> Vec { + // Glyphs laid out in all, at most: past it, the glyphs left unchecked stay outlines. + let mut budget = lines.iter().map(|l| l.pieces.len()).sum::().saturating_mul(16).saturating_add(256); + let mut todo: std::collections::VecDeque = lines.into(); + let mut out = vec![]; + while let Some(l) = todo.pop_front() { + let n = l.pieces.len(); + // The line's type is laid out over a window from its start that doubles while the type + // draws the window's glyphs as the outlines do, so finding where it stops costs about + // twice the glyphs before that point, not the whole rest of the line each time. + let mut w = 8usize; + loop { + let e = n.min(w); + let Some(part) = l.part(0, e) else { break }; + let Some(left) = budget.checked_sub(e) else { + // Unchecked glyphs stay outlines. + unmatched.extend(l.pieces.iter().copied()); + break; + }; + budget = left; + match part.first_mismatch(&part.text_object(system_layout)) { + // The whole line is drawn as it was: one object. + None if e == n => { + out.push(part); + break; + } + None => w = w.saturating_mul(2), + // The first glyph on its own may still be drawn as it was (a contextual form + // changed it in the line); else it stays an outline. Checked again either way. + Some(0) if n > 1 => { + todo.extend_front_parts(&l, [(0, 1), (1, n)]); + break; + } + Some(0) => { + unmatched.extend(l.pieces.first().copied()); + break; + } + // The glyphs before the mismatch, then the rest, each checked as a line of its + // own: the type before the mismatch may draw otherwise without what follows it (a + // font can place a glyph by the glyph after it). + Some(k) => { + todo.extend_front_parts(&l, [(0, k), (k, n)]); + break; + } + } + } + } + out +} + +/// Puts parts of a line at the front of the work list, in order. +trait FrontParts { + fn extend_front_parts(&mut self, l: &Line, ranges: [(usize, usize); N]); +} + +impl FrontParts for std::collections::VecDeque { + fn extend_front_parts(&mut self, l: &Line, ranges: [(usize, usize); N]) { + for (a, b) in ranges.into_iter().rev() { + if let Some(p) = l.part(a, b) { + self.push_front(p); + } + } + } +} + +fn space_advance(face: &vectorcraft_text::FontFace) -> f64 { + face.mapped_chars().iter().find(|(c, _)| *c == ' ').map(|(_, g)| face.advance(*g)).unwrap_or(0.0) +} + +/// Add shape `pc` to line `l` when one of its candidate glyphs `cands`, in one of its poses, +/// continues it (one shape can be several glyphs, and a glyph that looks the same turned fits in +/// more than one pose). A line of one shape may turn to another of that shape's candidates to take +/// the next one: an L or a turned L half round, an I upright or upside down, and the glyph after it +/// tells which. Whether it was added. +fn join(l: &mut Line, pc: &Piece, cands: &[GlyphMatch]) -> bool { + let fits = |l: &Line| cands.iter().flat_map(|c| c.poses()).find(|mp| l.continues(pc, mp)); + if let Some(mp) = fits(l) { + l.push(pc.id, &mp); + return true; + } + let (Some(id), [current]) = (l.pieces.first().copied(), l.matches.as_slice()) else { return false }; + let current = current.clone(); + let others: Vec = l + .first_cands + .iter() + .flat_map(|c| c.poses()) + .filter(|fp| !(fp.gid == current.gid && fp.face.id() == current.face.id() && fp.angle == current.angle)) + .collect(); + for fp in others { + let mut turned = reposed(l, id, &fp); + if let Some(mp) = fits(&turned) { + turned.push(pc.id, &mp); + *l = turned; + return true; + } + } + false +} + +/// Line `l`'s group, paint and transparency with glyph `m` (shape `id`) alone on it. +fn reposed(l: &Line, id: NodeId, m: &GlyphMatch) -> Line { + let dir = Vec2::new(m.angle.cos(), m.angle.sin()); + Line { + pieces: vec![id], + matches: vec![m.clone()], + first_cands: l.first_cands.clone(), + text: m.ch.to_string(), + face: m.face.clone(), + scale: m.scale, + angle: m.angle, + origin: m.origin, + end: m.origin + dir * (m.face.advance(m.gid) * m.scale), + appearance: l.appearance.clone(), + parent: l.parent, + opacity: l.opacity, + blend: l.blend, + } +} + +/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` (none: `None`). +fn new_line(pc: &Piece, cands: &[GlyphMatch]) -> Option { + let m = cands.first()?; + let dir = Vec2::new(m.angle.cos(), m.angle.sin()); + Some(Line { + pieces: vec![pc.id], + matches: vec![m.clone()], + first_cands: cands.to_vec(), + text: m.ch.to_string(), + face: m.face.clone(), + scale: m.scale, + angle: m.angle, + origin: m.origin, + end: m.origin + dir * (m.face.advance(m.gid) * m.scale), + appearance: pc.appearance.clone(), + parent: pc.parent, + opacity: pc.opacity, + blend: pc.blend, + }) +} + +fn retype(s: &mut Session, p: &Value) -> Result { + const C: &str = "type.retype"; + let fonts: Vec = match p.get("fonts") { + None | Some(Value::Null) => vec![], + Some(Value::Array(a)) => { + a.iter().map(|v| v.as_str().map(str::to_owned).ok_or_else(|| bad(C, "fonts must be a list of family names"))).collect::>()? + } + Some(_) => return Err(bad(C, "fonts must be a list of family names")), + }; + let roots = selected_roots(s)?; + let db = FontDb::global(); + let system_layout = s.doc()?.doc.setup.system_layout; + let (lines, unmatched, truncated) = { + let d = &s.doc()?.doc; + let mut pieces = vec![]; + let mut truncated = false; + let mut last: Option<(Option, usize)> = None; + // Carried across roots: a selected root that yields no shape (live type, an open path) still + // ends the line. + let mut barrier = true; + for r in &roots { + let Some(n) = d.node(*r) else { continue }; + let parent = d.parent_of(*r); + let idx = d.position(*r).map(|(_, i, _)| i); + // A root right after the last one, in the same parent, continues its lines; unselected + // art between two roots is a barrier. + if !matches!((last, idx), (Some((p, i)), Some(j)) if p == parent && i + 1 == j) { + barrier = true; + } + last = idx.map(|i| (parent, i)); + collect(n, parent, 0, &mut barrier, &mut truncated, &mut pieces); + } + if pieces.is_empty() { + return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into())); + } + // Only glyphs with a selected shape's key (segments per contour) can match one: the others are + // not sampled. + let wanted: std::collections::BTreeSet = + pieces.iter().filter(|pc| !pc.keeps_outline).filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect(); + // Nothing to match (every shape stays an outline): no font is read. + let index = if wanted.is_empty() { RetypeIndex::default() } else { RetypeIndex::build(db, candidate_faces(db, d, &fonts), &wanted) }; + let found: Vec> = pieces.iter().map(|pc| if pc.keeps_outline { vec![] } else { index.matches(&pc.path) }).collect(); + // The face most shapes match, so a glyph several fonts share is set in the same font as + // the glyphs around it. + let mut votes: Vec<(u32, usize)> = vec![]; + for ms in &found { + // Each shape votes once for each face it fits. + let mut faces: Vec = ms.iter().map(|m| m.face.id()).collect(); + faces.sort_unstable(); + faces.dedup(); + for f in faces { + match votes.iter_mut().find(|(v, _)| *v == f) { + Some(v) => v.1 += 1, + None => votes.push((f, 1)), + } + } + } + let rank = |face: u32| votes.iter().find(|(f, _)| *f == face).map_or(0, |v| v.1); + let mut lines: Vec = vec![]; + let mut unmatched = vec![]; + // An unmatched shape between glyphs ends the line: the type after it is painted after it. + let mut open = false; + for (pc, ms) in pieces.iter().zip(&found) { + if pc.after_barrier { + open = false; + } + // The shape's candidates in the face most shapes fit (the first such face, as the + // matches come upright and closest first). + let face = ms.iter().enumerate().max_by_key(|(i, m)| (rank(m.face.id()), std::cmp::Reverse(*i))).map(|(_, m)| m.face.id()); + let cands: Vec = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect(); + if cands.is_empty() { + unmatched.push(pc.id); + open = false; + continue; + } + let joined = match lines.last_mut() { + Some(l) if open => join(l, pc, &cands), + _ => false, + }; + if !joined { + lines.extend(new_line(pc, &cands)); + } + open = true; + } + // A lone one-contour glyph (a period, a hyphen, a bullet) is too plain to tell from drawn + // art (a dot, a bar): beside other shapes it stays an outline. Selected on its own, it is + // what was asked for. Lone means alone on its baseline as the outlines lie, before the + // layout check splits lines (tracking and manual kerning split them glyph by glyph). + let lone_pieces: std::collections::HashSet = + lines.iter().filter(|l| matches!(l.matches.as_slice(), [m] if m.contours == 1)).flat_map(|l| l.pieces.iter().copied()).collect(); + let mut lines = verified(lines, system_layout, &mut unmatched); + if pieces.len() > 1 { + lines.retain(|l| { + let lone = matches!(l.pieces.as_slice(), [id] if lone_pieces.contains(id)); + if lone { + unmatched.extend(l.pieces.iter().copied()); + } + !lone + }); + } + (lines, unmatched, truncated) + }; + if lines.is_empty() { + return Err(EngineError::Other(format!("Retype: no selected shape matches a glyph of an available font ({} checked)", unmatched.len()))); + } + let made = s.edit("Retype", |d, sel| { + let mut ids = vec![]; + let mut emptied = vec![]; + for l in &lines { + let Some(first) = l.pieces.first() else { continue }; + let (par, idx, _) = d.position(*first).ok_or(EngineError::NoNode(*first))?; + let t = l.text_object(system_layout); + let id = d.alloc_id(); + let mut node = Node::new(id, NodeKind::Text(Box::new(t))); + // The glyphs' own transparency (the group's, kept, still applies over it). + node.opacity = l.opacity; + node.blend = l.blend; + d.insert(par, idx, node)?; + for pc in &l.pieces { + if let Some((Some(parent), _, _)) = d.position(*pc) { + emptied.push(parent); + } + d.remove(*pc)?; + } + ids.push(id); + } + // A group left holding only the new type (Create Outlines' group) gives way to it, unless + // the group has transparency, effects, a mask or a name of its own, which then keep + // applying to the type inside it. A group left empty goes. + emptied.sort_unstable(); + emptied.dedup(); + for g in emptied { + let Some(n) = d.node(g) else { continue }; + let NodeKind::Group { children, clip: false } = &n.kind else { continue }; + let plain = n.opacity == 1.0 + && n.blend == vectorcraft_color::BlendMode::Normal + && *n.appearance == Appearance::default() + && n.name.is_none() + // Its mask, Attributes note and the rest of what few objects have stay with it. + && { + let mut ex = n.extras().clone(); + ex.type_outlines = false; + ex == vectorcraft_doc::NodeExtras::default() + } + // Isolation and knockout change how the group composites its type. + && !n.isolate + && n.knockout == vectorcraft_doc::Knockout::default() + && !n.knockout_shape; + let only_type = children.iter().all(|c| ids.contains(&c.id)); + if children.is_empty() { + d.remove(g)?; + } else if plain && only_type { + let kids: Vec> = children.clone(); + let (par, idx, _) = d.position(g).ok_or(EngineError::NoNode(g))?; + d.remove(g)?; + for (i, k) in kids.into_iter().enumerate() { + d.insert(par, idx + i, (*k).clone())?; + } + } + } + let mut keep: Vec = roots.iter().copied().filter(|r| d.node(*r).is_some()).collect(); + keep.extend(&ids); + sel.set(keep); + Ok(ids) + })?; + Ok(json!({ + "ids": made.iter().map(|i| i.0).collect::>(), + "texts": lines.iter().map(|l| l.text.clone()).collect::>(), + "fonts": lines.iter().map(|l| json!({"family": l.face.family, "style": l.face.style, "size": l.scale * l.face.units_per_em()})).collect::>(), + "unmatched": unmatched.iter().map(|i| i.0).collect::>(), + "truncated": truncated, + })) +} + +#[cfg(test)] +#[path = "retype_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/retype_fonts.rs b/crates/engine/src/cmd/retype_fonts.rs new file mode 100644 index 0000000000..dc9a413d5f --- /dev/null +++ b/crates/engine/src/cmd/retype_fonts.rs @@ -0,0 +1,141 @@ +//! Retype's matching fonts (`type.retypeFonts`): the fonts whose glyphs match the selected outlined +//! text, ranked, for the Retype panel's list +//! (, +//! ). +//! The panel lists ten fonts and five more on request. Each selected glyph shape is compared with +//! the glyphs of up to 96 loaded fonts, those of the document's live type first, by the same +//! matching as `type.retype` (exact matches only). Of two versions of one font, only the version its +//! family and style name gives is compared. The order is VectorCraft's own: a font ranks by how many +//! of the shapes it matches, then by how closely, on average, and then by name. The query changes +//! nothing. + +use std::collections::BTreeSet; +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_text::FontDb; +use vectorcraft_text::retype::{RetypeIndex, shape_key}; + +use super::super::edit::selected_roots; +use super::super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_selected_path}; +use super::{candidate_faces, collect}; + +pub(in crate::cmd) fn specs() -> Vec { + vec![cmd!( + query "type.retypeFonts", + "Find Matching Fonts", + [], + None, + "{count?: 1..96 (default 10)} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only); of two versions of a font loaded at once, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out)}; a count that is not a whole number from 1 to 96 is an error", + has_selected_path, + retype_fonts + )] +} + +/// The fonts listed when `count` is left out. +pub(super) const DEFAULT_COUNT: usize = 10; +/// The most fonts one query lists: every face the matching indexes. +pub(super) const MAX_COUNT: usize = vectorcraft_text::retype::MAX_FACES; + +/// One font that matched some of the shapes. +struct Ranked { + face: Arc, + /// How many shapes it matched. + matched: usize, + /// The sum of those matches' leftover distances. + residual: f64, +} + +impl Ranked { + fn mean(&self) -> f64 { + self.residual / self.matched.max(1) as f64 + } +} + +pub(super) fn retype_fonts(s: &mut Session, p: &Value) -> Result { + retype_fonts_in(s, p, FontDb::global()) +} + +/// [`retype_fonts`] with the fonts of `db`. +fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result { + const C: &str = "type.retypeFonts"; + let count = match p.get("count") { + None | Some(Value::Null) => DEFAULT_COUNT, + Some(v) => v + .as_u64() + .and_then(|n| usize::try_from(n).ok()) + .filter(|n| (1..=MAX_COUNT).contains(n)) + .ok_or_else(|| bad(C, "`count` must be a whole number from 1 to 96"))?, + }; + let roots = selected_roots(s)?; + let d = &s.doc()?.doc; + let mut pieces = vec![]; + let (mut barrier, mut truncated) = (true, false); + for r in &roots { + if let Some(n) = d.node(*r) { + collect(n, d.parent_of(*r), 0, &mut barrier, &mut truncated, &mut pieces); + } + } + if pieces.is_empty() { + return Err(EngineError::Other("Retype: select outlined text (paths or compound paths)".into())); + } + // Only glyphs with a selected shape's key (segments per contour) can match one. + let wanted: BTreeSet = pieces.iter().filter_map(|pc| shape_key(&pc.path)).collect(); + // A font is chosen by its family and style, which set the version the name gives: of two + // versions of one font, only that one is compared. The other versions do not take the places + // of fonts loaded after them. + let by_name = |f: &Arc| db.face(&f.family, &f.style).is_some_and(|g| g.id() == f.id()); + let mut faces: Vec<_> = candidate_faces(db, d, &[]).into_iter().filter(by_name).collect(); + for f in db.loaded_faces() { + if faces.len() >= vectorcraft_text::retype::MAX_FACES { + break; + } + if by_name(&f) && !faces.iter().any(|k| k.id() == f.id()) { + faces.push(f); + } + } + // No shape has a key: no font is read. + let index = if wanted.is_empty() { RetypeIndex::default() } else { RetypeIndex::build(db, faces, &wanted) }; + // A shape's paint does not change which glyph it is: shapes that would stay outlines count too. + let mut ranked: Vec = vec![]; + for pc in &pieces { + // A shape can fit several glyphs or poses of one font: it counts once for the font, at its + // closest fit. + let mut best: Vec<(Arc, f64)> = vec![]; + for m in index.all_matches(&pc.path) { + match best.iter_mut().find(|(f, _)| f.id() == m.face.id()) { + Some(b) => b.1 = b.1.min(m.residual), + None => best.push((m.face, m.residual)), + } + } + for (face, residual) in best { + match ranked.iter_mut().find(|r| r.face.id() == face.id()) { + Some(r) => { + r.matched += 1; + r.residual += residual; + } + None => ranked.push(Ranked { face, matched: 1, residual }), + } + } + } + ranked.sort_by(|a, b| { + b.matched + .cmp(&a.matched) + .then(a.mean().total_cmp(&b.mean())) + .then_with(|| a.face.family.to_lowercase().cmp(&b.face.family.to_lowercase())) + .then_with(|| a.face.style.to_lowercase().cmp(&b.face.style.to_lowercase())) + .then(a.face.id().cmp(&b.face.id())) + }); + let more = ranked.len() > count; + ranked.truncate(count); + Ok(json!({ + "fonts": ranked.iter().map(|r| json!({"family": r.face.family, "style": r.face.style, "matched": r.matched})).collect::>(), + "shapes": pieces.len(), + "more": more, + "truncated": truncated, + })) +} + +#[cfg(test)] +#[path = "retype_fonts_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/retype_fonts_tests.rs b/crates/engine/src/cmd/retype_fonts_tests.rs new file mode 100644 index 0000000000..d7e675f503 --- /dev/null +++ b/crates/engine/src/cmd/retype_fonts_tests.rs @@ -0,0 +1,159 @@ +use std::sync::OnceLock; + +use serde_json::{Value, json}; +use vectorcraft_text::FontDb; + +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + s +} + +/// The bundled fonts alone: other tests add copies of them to the global database, and a copy +/// ties with its original, so the ranking is read against a database of its own. +fn bundled() -> &'static FontDb { + static DB: OnceLock = OnceLock::new(); + DB.get_or_init(|| FontDb::with_font_dirs(vec![])) +} + +/// `type.retypeFonts` with `params`, comparing the fonts of `db`. +fn query(s: &mut Session, params: Value, db: &FontDb) -> Value { + super::retype_fonts_in(s, ¶ms, db).unwrap() +} + +/// Point text, outlined: the id of the outlines' group. +fn outlined(s: &mut Session, p: Value) -> u64 { + let id = s.execute("text.create", &p).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap() +} + +fn names(r: &Value) -> Vec<(String, String, u64)> { + r["fonts"] + .as_array() + .unwrap() + .iter() + .map(|f| (f["family"].as_str().unwrap().to_string(), f["style"].as_str().unwrap().to_string(), f["matched"].as_u64().unwrap())) + .collect() +} + +#[test] +fn matching_fonts_rank_by_how_many_shapes_each_matches() { + let mut s = session(); + // Seven shapes in Source Sans 3 Bold, three in Source Serif 4. + let a = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Ranking", "size": 30, "font": "Source Sans 3", "style": "Bold"})); + let b = outlined(&mut s, json!({"x": 40, "y": 200, "text": "Wxy", "size": 30, "font": "Source Serif 4", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let r = query(&mut s, json!({}), bundled()); + assert_eq!(r["shapes"], json!(10), "{r}"); + let fonts = names(&r); + assert_eq!(fonts.first(), Some(&("Source Sans 3".to_string(), "Bold".to_string(), 7)), "{r}"); + let serif = fonts.iter().position(|f| f.0 == "Source Serif 4" && f.1 == "Regular").expect("the serif is listed"); + assert_eq!(fonts[serif].2, 3, "{r}"); + // Each font once, and no font matches more shapes than one listed before it. + for (i, f) in fonts.iter().enumerate() { + assert!(!fonts[..i].iter().any(|g| g.0 == f.0 && g.1 == f.1), "{f:?} is listed twice: {r}"); + assert!(fonts[..i].iter().all(|g| g.2 >= f.2), "{f:?} ranks after a font that matches fewer shapes: {r}"); + } + assert_eq!(r["truncated"], json!(false)); + // The command: a query, so the document stays as it was, and there is no undo step for it. + let r = s.execute("type.retypeFonts", &json!({})).unwrap(); + assert_eq!(r["shapes"], json!(10), "{r}"); + assert!(s.doc().unwrap().doc == before, "nothing changes"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc != before, "undo takes back the last outlining, not the query"); +} + +#[test] +fn count_lists_the_first_fonts_and_more_says_others_match() { + let mut s = session(); + let a = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Aa", "size": 30, "font": "Source Sans 3", "style": "Regular"})); + let b = outlined(&mut s, json!({"x": 40, "y": 200, "text": "B", "size": 30, "font": "Source Serif 4", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let all = query(&mut s, json!({"count": 96}), bundled()); + assert!(names(&all).len() >= 2, "{all}"); + assert_eq!(all["more"], json!(false), "{all}"); + let one = query(&mut s, json!({"count": 1}), bundled()); + assert_eq!(names(&one), vec![("Source Sans 3".to_string(), "Regular".to_string(), 2)], "{one}"); + assert_eq!(one["more"], json!(true), "{one}"); + assert_eq!(query(&mut s, json!({"count": null}), bundled()), query(&mut s, json!({}), bundled())); +} + +#[test] +fn a_count_that_is_not_a_whole_number_from_1_to_96_is_an_error() { + let mut s = session(); + let a = outlined(&mut s, json!({"x": 40, "y": 100, "text": "A", "size": 30})); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + for bad in [json!(0), json!(97), json!(-1), json!(2.5), json!("10"), json!(true)] { + let e = s.execute("type.retypeFonts", &json!({"count": bad})).unwrap_err().to_string(); + assert!(e.contains("`count` must be a whole number from 1 to 96"), "{bad}: {e}"); + } +} + +#[test] +fn shapes_that_are_no_glyph_list_no_font() { + let mut s = session(); + let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [rect]})).unwrap(); + let r = query(&mut s, json!({}), bundled()); + assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false})); + // Live type alone holds no shape to compare. + let t = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "live"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [t]})).unwrap(); + assert!(s.execute("type.retypeFonts", &json!({})).is_err()); +} + +#[test] +fn shapes_past_the_limits_are_reported_as_left_out() { + let mut s = session(); + let top = outlined(&mut s, json!({"x": 40, "y": 100, "text": "A", "size": 40})); + // B, nested deeper than Retype looks. + let mut deep = outlined(&mut s, json!({"x": 40, "y": 200, "text": "B", "size": 40})); + for _ in 0..20 { + s.execute("select.set", &json!({"ids": [deep]})).unwrap(); + deep = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap(); + } + s.execute("select.set", &json!({"ids": [top, deep]})).unwrap(); + let r = query(&mut s, json!({}), bundled()); + assert_eq!((r["shapes"].clone(), r["truncated"].clone()), (json!(1), json!(true)), "{r}"); +} + +/// Two versions of one font: choosing the font by name sets the version the name gives, so only +/// that version is compared, and a font whose other version alone matches is not listed. +#[test] +fn of_two_versions_only_the_one_the_name_gives_is_listed() { + use vectorcraft_text::test_fonts::named_copy; + const FAMILY: &str = "Versiontest Sans"; + // A database of its own, so that no other test sees these fonts. + let db = FontDb::with_font_dirs(vec![]); + // The first version loaded (Source Sans 3's glyphs) is the one the name gives. + db.add_font(named_copy(false, (FAMILY, "Regular", "Version 1.000", "VersiontestSans-Regular")).unwrap()); + db.add_font(named_copy(true, (FAMILY, "Regular", "Version 2.000", "VersiontestSans-Regular")).unwrap()); + assert_eq!(db.face(FAMILY, "Regular").unwrap().version, "Version 1.000"); + let mut s = session(); + let inter = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Kg", "size": 40, "font": "Inter", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [inter]})).unwrap(); + let r = query(&mut s, json!({"count": 96}), &db); + let fonts = names(&r); + assert!(fonts.iter().any(|f| f.0 == "Inter"), "{r}"); + assert!(!fonts.iter().any(|f| f.0 == FAMILY), "version 2 matches, but choosing the font sets version 1: {r}"); + let source = outlined(&mut s, json!({"x": 40, "y": 200, "text": "Kg", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [source]})).unwrap(); + let r = query(&mut s, json!({"count": 96}), &db); + assert_eq!(names(&r).iter().filter(|f| f.0 == FAMILY).count(), 1, "version 1 matches and is listed once: {r}"); +} + +#[test] +fn shapes_that_stay_outlines_still_name_their_font() { + // A glyph with paint type cannot take (two fills) is not retyped, but it is still that font's glyph. + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "M", "size": 40, "font": "Source Serif 4", "style": "Regular"})); + let glyph = s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(g)).unwrap().children().unwrap()[0].id.0; + s.execute("select.set", &json!({"ids": [glyph]})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + let r = query(&mut s, json!({}), bundled()); + assert_eq!(names(&r).first().map(|f| (f.0.as_str(), f.1.as_str())), Some(("Source Serif 4", "Regular")), "{r}"); +} diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs new file mode 100644 index 0000000000..d691ab34fa --- /dev/null +++ b/crates/engine/src/cmd/retype_tests.rs @@ -0,0 +1,539 @@ +use serde_json::json; +use vectorcraft_doc::{NodeId, NodeKind, TextObject}; + +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + s +} + +/// Point text, outlined: the id of the outlines' group. +fn outlined(s: &mut Session, p: serde_json::Value) -> u64 { + let id = s.execute("text.create", &p).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap() +} + +fn text_of(s: &Session, id: u64) -> TextObject { + let NodeKind::Text(t) = &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind else { panic!("text object") }; + (**t).clone() +} + +fn near(a: f64, b: f64, tol: f64) -> bool { + (a - b).abs() <= tol +} + +#[test] +fn outlined_point_text_retypes_to_the_same_text_font_size_and_place() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Retype me, 42!", "size": 36, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["Retype me, 42!"]), "{r}"); + assert_eq!(r["unmatched"], json!([])); + let id = r["ids"][0].as_u64().unwrap(); + let t = text_of(&s, id); + assert_eq!(t.plain_text(), "Retype me, 42!"); + let st = t.first_style(); + assert_eq!((st.font_family.as_str(), st.font_style.as_str()), ("Source Sans 3", "Regular")); + assert!(near(st.size, 36.0, 0.01), "size {}", st.size); + let o = t.xf.translation(); + assert!(near(o.x, 40.0, 0.01) && near(o.y, 100.0, 0.01), "baseline start {o:?}"); + // The outlines are gone, in one undo step that brings them back. + let d = &s.doc().unwrap().doc; + assert!(d.node(NodeId(g)).is_none(), "the emptied group goes"); + s.execute("edit.undo", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.node(NodeId(g)).is_some() && d.node(NodeId(id)).is_none()); +} + +#[test] +fn turned_bold_and_serif_type_keeps_its_font_and_angle() { + let mut s = session(); + let a = outlined(&mut s, json!({"x": 100, "y": 200, "text": "Bold", "size": 24, "font": "Source Sans 3", "style": "Bold", "rotation": 30})); + let b = outlined(&mut s, json!({"x": 300, "y": 80, "text": "Serif", "size": 18, "font": "Source Serif 4", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["Bold", "Serif"]), "{r}"); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + let bold = text_of(&s, ids[0]); + assert_eq!(bold.first_style().font_style, "Bold"); + assert!(near(bold.first_style().size, 24.0, 0.01)); + // text.create turns as kurbo does: compare the turn the new type has with the old one's. + let turned = kurbo::Affine::translate((100.0, 200.0)) * vectorcraft_geom::rotate_deg(30.0); + for (x, y) in bold.xf.as_coeffs().iter().zip(turned.as_coeffs()) { + assert!(near(*x, y, 1e-3), "{:?} vs {:?}", bold.xf, turned); + } + let serif = text_of(&s, ids[1]); + assert_eq!(serif.first_style().font_family, "Source Serif 4"); + assert!(near(serif.first_style().size, 18.0, 0.01)); +} + +#[test] +fn a_drawn_shape_is_reported_and_left_alone() { + let mut s = session(); + let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [rect]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + assert!(e.contains("no selected shape matches"), "{e}"); + assert!(s.doc().unwrap().doc == before, "nothing changes"); + // With outlines that would match, a bad `fonts` is refused for itself, and nothing changes. + let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "AB", "size": 40})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + for bad in [json!("Source Sans 3"), json!([1]), json!({"family": "x"})] { + let e = s.execute("type.retype", &json!({"fonts": bad})).unwrap_err().to_string(); + assert!(e.contains("fonts must be a list of family names"), "{e}"); + } + assert!(s.doc().unwrap().doc == before); +} + +#[test] +fn mixed_selection_retypes_the_glyphs_and_keeps_the_rest() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Mix", "size": 30})); + let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 200, "width": 80, "height": 40})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g, rect]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["Mix"])); + assert_eq!(r["unmatched"], json!([rect])); + let d = &s.doc().unwrap().doc; + assert!(matches!(d.node(NodeId(rect)).unwrap().kind, NodeKind::Path { .. }), "the rectangle stays"); +} + +#[test] +fn two_words_keep_their_space() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 20, "y": 60, "text": "two words", "size": 20})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["two words"])); +} + +#[test] +fn craft_fonts_glyphs_retype_too() { + let Some(f) = vectorcraft_text::CRAFT_FONTS.iter().find(|f| f.is_japanese()) else { + eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)"); + return; + }; + let mut s = session(); + let g = outlined(&mut s, json!({"x": 20, "y": 60, "text": "漢字です", "size": 20, "font": f.family, "style": f.style})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({"fonts": [f.family]})).unwrap(); + assert_eq!(r["texts"], json!(["漢字です"]), "{r}"); + assert_eq!(r["fonts"][0]["family"], json!(f.family)); +} + +fn children_of(s: &Session, g: u64) -> Vec { + s.doc().unwrap().doc.node(NodeId(g)).unwrap().children().unwrap().iter().map(|c| c.id.0).collect() +} + +#[test] +fn a_shape_between_glyphs_ends_the_line_so_paint_order_holds() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + let rect = s.execute("shape.rectangle", &json!({"x": 30, "y": 60, "width": 80, "height": 50})).unwrap()["id"].as_u64().unwrap(); + // The rectangle goes between A and B, inside the outlines' group. + s.edit("test", |d, _| { + let n = d.node(NodeId(rect)).unwrap().clone(); + d.remove(NodeId(rect))?; + d.insert(Some(NodeId(g)), 1, n)?; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["A", "B"]), "{r}"); + assert_eq!(r["unmatched"], json!([rect])); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(children_of(&s, g), vec![ids[0], rect, ids[1]], "A under the rectangle, B over it"); +} + +#[test] +fn glyphs_of_different_groups_and_transparency_stay_apart() { + let mut s = session(); + let a = outlined(&mut s, json!({"x": 40, "y": 100, "text": "ab", "size": 20})); + let b = outlined(&mut s, json!({"x": 120, "y": 100, "text": "ed", "size": 20})); + let first_d = children_of(&s, b)[1]; + s.edit("test", |d, _| { + d.node_mut(NodeId(b)).unwrap().opacity = 0.5; + d.node_mut(NodeId(first_d)).unwrap().opacity = 0.25; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["ab", "e", "d"]), "same baseline, other group; d has its own opacity: {r}"); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + let d = &s.doc().unwrap().doc; + assert!(d.node(NodeId(a)).is_none(), "a plain group gives way to its type"); + assert_eq!(d.node(NodeId(b)).unwrap().opacity, 0.5, "the half-transparent group stays"); + assert_eq!(children_of(&s, b), vec![ids[1], ids[2]]); + assert_eq!(s.doc().unwrap().doc.node(NodeId(ids[2])).unwrap().opacity, 0.25, "the glyph's own opacity carries over"); +} + +#[test] +fn live_type_between_glyphs_ends_the_line_too() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + let live = s.execute("text.create", &json!({"x": 30, "y": 90, "text": "x", "size": 60})).unwrap()["id"].as_u64().unwrap(); + s.edit("test", |d, _| { + let n = d.node(NodeId(live)).unwrap().clone(); + d.remove(NodeId(live))?; + d.insert(Some(NodeId(g)), 1, n)?; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["A", "B"]), "{r}"); + let ids: Vec = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + assert_eq!(children_of(&s, g), vec![ids[0], live, ids[1]], "B stays over the live type"); + let t = text_of(&s, ids[0]); + assert!(t.first_style().features.iter().any(|f| f == "-liga"), "glyphs drawn one by one: no ligatures"); +} + +#[test] +fn an_open_path_along_a_glyph_is_not_a_glyph() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "I", "size": 40})); + s.edit("test", |d, _| { + let glyph = d.node(NodeId(g)).unwrap().children().unwrap()[0].id; + for sp in &mut d.node_mut(glyph).unwrap().path_data_mut().unwrap().subpaths { + sp.closed = false; + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + assert!(s.execute("type.retype", &json!({})).is_err(), "nothing matches"); +} + +#[test] +fn live_type_selected_between_loose_glyphs_still_ends_the_line() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + let live = s.execute("text.create", &json!({"x": 30, "y": 90, "text": "x", "size": 60})).unwrap()["id"].as_u64().unwrap(); + let (a, b) = (children_of(&s, g)[0], children_of(&s, g)[1]); + // A, the live type and B as siblings in the layer, as Ungroup leaves them. + s.edit("test", |d, _| { + let (par, idx, _) = d.position(NodeId(g)).unwrap(); + let live_n = d.node(NodeId(live)).unwrap().clone(); + let (an, bn) = (d.node(NodeId(a)).unwrap().clone(), d.node(NodeId(b)).unwrap().clone()); + d.remove(NodeId(live))?; + d.remove(NodeId(g))?; + d.insert(par, idx, an)?; + d.insert(par, idx + 1, live_n)?; + d.insert(par, idx + 2, bn)?; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [a, live, b]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["A", "B"]), "the selected live type between them ends the line: {r}"); +} + +#[test] +fn glyphs_selected_inside_groups_join_only_their_siblings() { + let mut s = session(); + let g1 = outlined(&mut s, json!({"x": 40, "y": 100, "text": "ab", "size": 20})); + let g2 = outlined(&mut s, json!({"x": 70, "y": 100, "text": "ed", "size": 20})); + let (a, b, c) = (children_of(&s, g1)[0], children_of(&s, g1)[1], children_of(&s, g2)[0]); + s.execute("select.set", &json!({"ids": [a, b, c]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["ab", "e"]), "a and b are siblings; e is in another group: {r}"); + let d = &s.doc().unwrap().doc; + assert!(d.node(NodeId(g2)).is_some(), "d's group stays with c's type and d in it"); +} + +#[test] +fn tracked_type_splits_where_its_spacing_cannot_be_set_again() { + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "abe", "size": 30})).unwrap()["id"].as_u64().unwrap(); + // Less than half a space: no whole number of spaces makes up the gap (0.4 em would be two + // spaces in this font, and the outlines cannot tell those apart from tracking). + s.execute("text.setRangeStyle", &json!({"id": id, "start": 1, "end": 3, "tracking": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let texts: Vec = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect(); + assert_eq!(texts.concat(), "abe", "{r}"); + assert!(texts.len() > 1, "the tracked glyphs are set where the outlines are, not where untracked type puts them: {r}"); + assert_eq!(r["unmatched"], json!([])); +} + +#[test] +fn a_masked_glyph_stays_an_outline() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + let a = children_of(&s, g)[0]; + s.edit("test", |d, _| { + let art = vectorcraft_doc::Node::path(d.alloc_id(), vectorcraft_geom::PathData::default(), Default::default()); + d.node_mut(NodeId(a)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true))); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["B"]), "{r}"); + assert_eq!(r["unmatched"], json!([a])); + assert!(s.doc().unwrap().doc.node(NodeId(a)).unwrap().extras().mask.is_some(), "A keeps its mask"); +} + +#[test] +fn shapes_past_the_limits_are_reported_as_left_out() { + let mut s = session(); + let top = outlined(&mut s, json!({"x": 40, "y": 100, "text": "A", "size": 40})); + let deep = outlined(&mut s, json!({"x": 40, "y": 200, "text": "B", "size": 40})); + // B, deeper than Retype looks. + s.edit("test", |d, _| { + let (par, idx, _) = d.position(NodeId(deep)).unwrap(); + let mut n = d.node(NodeId(deep)).unwrap().clone(); + d.remove(NodeId(deep))?; + for _ in 0..20 { + n = vectorcraft_doc::Node::group(d.alloc_id(), vec![std::sync::Arc::new(n)]); + } + let wrapper = n.id.0; + d.insert(par, idx, n)?; + Ok(wrapper) + }) + .map(|w| s.execute("select.set", &json!({"ids": [top, w]})).unwrap()) + .unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["A"])); + assert_eq!(r["truncated"], json!(true), "{r}"); +} + +#[test] +fn a_glyph_painted_beyond_what_type_takes_stays_an_outline() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + let a = children_of(&s, g)[0]; + s.edit("test", |d, _| { + let n = d.node_mut(NodeId(a)).unwrap(); + let mut ap = (*n.appearance).clone(); + let fill = ap.items.iter().find(|i| i.is_fill()).unwrap().clone(); + ap.items.push(fill); + n.appearance = ap.into(); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["B"]), "two fills: A stays an outline: {r}"); + assert_eq!(r["unmatched"], json!([a])); +} + +#[test] +fn a_hidden_or_locked_glyph_stays_an_outline() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "ABD", "size": 40})); + let k = children_of(&s, g); + s.edit("test", |d, _| { + d.node_mut(NodeId(k[0])).unwrap().visible = false; + d.node_mut(NodeId(k[2])).unwrap().locked = true; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["B"]), "{r}"); + let d = &s.doc().unwrap().doc; + assert!(!d.node(NodeId(k[0])).unwrap().visible, "A stays a hidden outline"); + assert!(d.node(NodeId(k[2])).unwrap().locked, "D stays a locked outline"); +} + +#[test] +fn an_isolated_or_knockout_group_keeps_its_type_inside() { + for case in ["isolate", "knockout", "knockout_shape"] { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + s.edit("test", |d, _| { + let n = d.node_mut(NodeId(g)).unwrap(); + match case { + "isolate" => n.isolate = true, + "knockout" => n.knockout = vectorcraft_doc::Knockout::On, + _ => n.knockout_shape = true, + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let id = r["ids"][0].as_u64().unwrap(); + assert_eq!(children_of(&s, g), vec![id], "{case}: the group stays, holding the type"); + } +} + +#[test] +fn type_turned_half_round_stays_one_object() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 300, "y": 200, "text": "Upside", "size": 30, "rotation": 180})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["Upside"]), "{r}"); +} + +#[test] +fn a_drawn_dot_or_bar_beside_type_stays_art() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + let dot = s.execute("shape.ellipse", &json!({"x": 300, "y": 60, "width": 8, "height": 8})).unwrap()["id"].as_u64().unwrap(); + // A bar that is exactly a hyphen of the font, somewhere else: the worst case. + let bar = outlined(&mut s, json!({"x": 200, "y": 300, "text": "-", "size": 50})); + s.execute("select.set", &json!({"ids": [g, dot, bar]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["AB"]), "{r}"); + let un = r["unmatched"].as_array().unwrap(); + assert!(un.contains(&json!(dot)) && un.len() == 2, "the dot and the bar stay art: {r}"); + // Selected on its own, the hyphen is what was asked for. + s.execute("select.set", &json!({"ids": [bar]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["-"]), "{r}"); +} + +/// How long Retype takes with a large CJK face to match against (run with `--ignored +/// --nocapture`; skips when no such face is installed). Not a pass/fail budget: it prints. +#[test] +#[ignore = "timing: needs an installed CJK font"] +fn timing_with_a_large_cjk_face() { + let db = vectorcraft_text::FontDb::global(); + let Some(family) = ["Microsoft YaHei", "Yu Gothic", "MS Gothic", "Noto Sans CJK JP", "Hiragino Sans"].into_iter().find(|f| db.has_family(f)) + else { + eprintln!("skipped: no large CJK font installed"); + return; + }; + let face = db.resolve(family, "Regular").map(|(f, _)| f).unwrap(); + let mut s = session(); + let g = outlined(&mut s, json!({"x": 20, "y": 80, "text": "漢字のテスト ABC", "size": 24, "font": family, "style": face.style})); + for run in ["cold", "warm"] { + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let t0 = std::time::Instant::now(); + let r = s.execute("type.retype", &json!({"fonts": [family]})).unwrap(); + let ms = t0.elapsed().as_secs_f64() * 1000.0; + eprintln!("{run}: Retype with {family} ({} encoded glyphs) loaded: {ms:.0} ms → {}", face.mapped_chars().len(), r["texts"]); + s.execute("edit.undo", &json!({})).unwrap(); + } +} + +#[test] +fn a_compound_with_a_locked_or_hidden_part_stays_whole() { + let mut s = session(); + // "B" outlines as a compound path of three contours. + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + let b = children_of(&s, g)[1]; + let part = children_of(&s, b)[1]; + s.edit("test", |d, _| { + d.node_mut(NodeId(part)).unwrap().locked = true; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["A"]), "{r}"); + let d = &s.doc().unwrap().doc; + assert!(d.node(NodeId(part)).unwrap().locked, "B's locked part, and B, stay as they are"); +} + +#[test] +fn a_group_with_an_attributes_note_keeps_its_type_inside() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB", "size": 40})); + s.execute("attributes.set", &json!({"ids": [g], "note": "logo, keep"})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let id = r["ids"][0].as_u64().unwrap(); + assert_eq!(children_of(&s, g), vec![id], "the group and its note stay, holding the type"); +} + +#[test] +fn nothing_retypable_reads_no_font() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "A", "size": 40})); + let a = children_of(&s, g)[0]; + s.edit("test", |d, _| { + let art = vectorcraft_doc::Node::path(d.alloc_id(), vectorcraft_geom::PathData::default(), Default::default()); + d.node_mut(NodeId(a)).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(art, true))); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + assert!(e.contains("(1 checked)"), "the masked shape is reported, and no font was indexed: {e}"); +} + +#[test] +fn tracked_one_contour_letters_still_become_type() { + for text in ["LIT", "HELLO", "LIST"] { + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 30})).unwrap()["id"].as_u64().unwrap(); + let n = text.len() as u64; + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": n, "tracking": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let texts: Vec = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect(); + assert_eq!(texts.concat(), text, "split by the tracking, every letter still becomes type: {r}"); + assert!(texts.len() > 1, "the tracking splits the line: {r}"); + assert_eq!(r["unmatched"], json!([]), "{r}"); + } +} + +/// How long Retype takes on a few hundred CJK outlines at once (run with `--ignored --nocapture`; +/// skips when no large CJK font is installed). Not a pass/fail budget: it prints. +#[test] +#[ignore = "timing: needs an installed CJK font"] +fn timing_with_hundreds_of_cjk_outlines() { + let db = vectorcraft_text::FontDb::global(); + let Some(family) = ["Microsoft YaHei", "Yu Gothic", "MS Gothic", "Noto Sans CJK JP", "Hiragino Sans"].into_iter().find(|f| db.has_family(f)) + else { + eprintln!("skipped: no large CJK font installed"); + return; + }; + let face = db.resolve(family, "Regular").map(|(f, _)| f).unwrap(); + // 300 common ideographs, ten lines of thirty. + let chars: Vec = (0x4E00u32..).filter_map(char::from_u32).filter(|c| face.covers(*c)).take(300).collect(); + let mut s = session(); + let mut groups = vec![]; + for (i, line) in chars.chunks(30).enumerate() { + let text: String = line.iter().collect(); + groups.push(outlined(&mut s, json!({"x": 20, "y": 40 + 30 * i, "text": text, "size": 20, "font": family, "style": face.style}))); + } + for run in ["cold", "warm"] { + s.execute("select.set", &json!({"ids": groups})).unwrap(); + let t0 = std::time::Instant::now(); + let r = s.execute("type.retype", &json!({"fonts": [family]})).unwrap(); + let ms = t0.elapsed().as_secs_f64() * 1000.0; + let typed: usize = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().chars().count()).sum(); + eprintln!( + "{run}: Retype of {} {family} outlines: {ms:.0} ms → {typed} characters typed, {} unmatched", + chars.len(), + r["unmatched"].as_array().unwrap().len() + ); + s.execute("edit.undo", &json!({})).unwrap(); + } +} + +#[test] +fn a_long_tracked_line_is_checked_in_time() { + // Tracking splits the line at every glyph: the layout check must not lay out the rest of the + // line again after each split. + let text = "abe".repeat(150); + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 4})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": text.len(), "tracking": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let t0 = std::time::Instant::now(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let texts: Vec = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect(); + assert_eq!(texts.concat(), text); + assert_eq!(r["unmatched"], json!([])); + eprintln!("450 tracked glyphs: {:?}, {} objects", t0.elapsed(), texts.len()); +} diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index d1f147ffbe..01c8f913d1 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -8,9 +8,10 @@ use vectorcraft_doc::{ Unit, WidthProfile, }; use vectorcraft_geom::PathData; +use vectorcraft_tools::builder::is_live_paint; use super::appearance::{ItemTarget, edit_items, item_target}; -use super::paint::painted; +use super::paint::{live_paint_parts, live_paint_parts_skipped, painted}; use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, ok, str_param}; use crate::DocState; use crate::inspect::{ALIGNS, CAPS, JOINS, StrokeMixed, node_stroke, scale_layer}; @@ -22,7 +23,7 @@ pub fn specs() -> Vec { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", has_doc, stroke_set ), @@ -31,7 +32,7 @@ pub fn specs() -> Vec { "Stroke Weight Up", [], Some("Cmd+Alt+."), - "{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke are left alone. With nothing selected (and no ids), the weight of the next object drawn. On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {objects}", + "{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke, and a Live Paint group's faces, are left alone. With nothing selected (and no ids), the weight of the next object drawn, and so while the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none). On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {objects}", has_doc, |s, p| stroke_step(s, p, true) ), @@ -49,7 +50,7 @@ pub fn specs() -> Vec { "Stroke Options", [], None, - "{arrowScale?: [start %, end %], swapArrows?: bool, flipProfile?: \"along\"|\"across\", brush?: name|null, item?: stroke item index|null, aligned?: bool (as stroke.set), ids?|id?, target?: \"object\"|\"contents\"} Stroke panel extras (with nothing selected, all but brush set up the next object drawn)", + "{arrowScale?: [start %, end %], swapArrows?: bool, flipProfile?: \"along\"|\"across\", brush?: name|null, item?: stroke item index|null, aligned?: bool (as stroke.set), ids?|id?, target?: \"object\"|\"contents\"} Stroke panel extras (with nothing selected, all but brush set up the next object drawn, and so while the Live Paint Bucket is the active tool and no ids, id, item or brush are given, a null ids or id counting as none; without item, a Live Paint group's edges take them and its faces are left alone)", has_doc, stroke_advanced ), @@ -210,20 +211,25 @@ fn no_targets(ids: &[vectorcraft_doc::NodeId], p: &Value) -> bool { /// The objects `stroke.set` edits with no `item`: a selected group or layer with a stroke row of /// its own edits that row, as the Stroke panel does with the group targeted (#6739); the other -/// targets reach their painted leaves, as before. +/// targets reach their painted leaves, as before (a Live Paint group's edges, not its faces). fn own_stroke_or_leaves(s: &Session, p: &Value) -> Result> { let picked = super::targets(s, p)?; let d = &s.doc()?.doc; + // A Live Paint group's stroke is its edges' strokes, also when it has a stroke row of its own. let own = |id: &vectorcraft_doc::NodeId| { d.node(*id).is_some_and(|n| { - matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.is_compound_shape() && n.appearance.stroke().is_some() + matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) + && !n.is_compound_shape() + && n.appearance.stroke().is_some() + && !is_live_paint(n) }) }; let (mut out, rest): (Vec<_>, Vec<_>) = picked.into_iter().partition(own); + let faces = live_paint_parts_skipped(d, &rest, false); // A leaf already listed is skipped; a set keeps this linear in the number of leaves. let mut seen: std::collections::HashSet = out.iter().copied().collect(); for id in super::leaf_targets(s, &rest)? { - if seen.insert(id) { + if !faces.contains(&id) && seen.insert(id) { out.push(id); } } @@ -233,13 +239,26 @@ fn own_stroke_or_leaves(s: &Session, p: &Value) -> Result Result { const C: &str = "stroke.set"; let change = StrokeChange::parse(p, C)?; + // The stroke the Live Paint Bucket paints with changes; the selection keeps its own, and its + // active Appearance row is not a target. + let bucket_p = super::paint::bucket_color_params(s, p, C)?; + let bucket = bucket_p.is_some(); + let p = bucket_p.as_ref().unwrap_or(p); let item = item_target(s, p, C)?.of_kind(s, false); - let mut ids = if item == ItemTarget::Top { own_stroke_or_leaves(s, p)? } else { item.targets(s, p)? }; - let new_art = no_targets(&ids, p); - let given = !ids.is_empty(); + let mut ids = if bucket { + vec![] + } else if item == ItemTarget::Top { + own_stroke_or_leaves(s, p)? + } else { + item.targets(s, p)? + }; + // A Live Paint group without edges was still selected or given: the options do not go to new art. + let live_paint = !bucket && item == ItemTarget::Top && !live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, false).is_empty(); + let new_art = bucket || (no_targets(&ids, p) && !live_paint); + let given = !ids.is_empty() || live_paint; // The art of a graph design in a series keeps the design's stroke. ids = super::appearance::drop_design_art_rows(s, ids, item, false, C)?; - // With only design art, the weight for new art stays as it is too. + // With only design art, or only Live Paint groups without edges, the weight for new art stays as it is too. let only_design_art = given && ids.is_empty(); if item == ItemTarget::Top { // Images and symbol instances take no stroke from the panel. @@ -371,9 +390,14 @@ pub(crate) fn step_weight(w: f64, unit: Unit, up: bool) -> f64 { fn stroke_step(s: &mut Session, p: &Value, up: bool) -> Result { let c = if up { "stroke.weightUp" } else { "stroke.weightDown" }; let unit = s.stroke_unit(); + // The weight the Live Paint Bucket paints with changes; the selection keeps its own, and its + // active Appearance row is not a target. + let bucket_p = super::paint::bucket_color_params(s, p, c)?; + let bucket = bucket_p.is_some(); + let p = bucket_p.as_ref().unwrap_or(p); let item = item_target(s, p, c)?.of_kind(s, false); - let ids = item.targets(s, p)?; - if no_targets(&ids, p) { + let (ids, skipped) = if bucket { (vec![], false) } else { item.targets_and_skipped(s, p, false)? }; + if bucket || (no_targets(&ids, p) && !skipped) { let w = step_weight(s.paint.stroke_width, unit, up); s.paint.stroke_width = w; if let Some(st) = s.new_art_stroke_mut() { @@ -412,13 +436,18 @@ impl Session { /// The stroke the Stroke panel, the Control bar and the Properties panel show, picked as the /// Stroke proxy picks its paint: the Appearance panel's active item when it is a stroke, else - /// the first selected object's (a group's first painted object's) top stroke, type's first - /// run's character stroke; with an object of a dynamic symbol instance selected + /// the first selected object's (a group's first painted object's, a Live Paint group's first + /// edge's, or the next selected object's when a Live Paint group has no edge) top stroke, type's + /// first run's character stroke; with an object of a dynamic symbol instance selected /// ([`DocState::selected_symbol_part`]), that object's as the instance draws it; with nothing - /// selected, the next object drawn's ([`Session::new_art_stroke`]). None without a document or - /// the selection's stroke. + /// selected, the next object drawn's ([`Session::new_art_stroke`]), and so while the Live Paint + /// Bucket is the active tool (the stroke it paints with). None without a document or the + /// selection's stroke. pub fn shown_stroke(&self) -> Option { let st = self.active()?; + if self.tool_id() == super::paint::LIVE_PAINT_BUCKET { + return Some(self.new_art_stroke()); + } if let Some(part) = st.selected_symbol_part() { return node_stroke(&part); } @@ -427,9 +456,20 @@ impl Session { if let Some(i) = first.appearance.item_of_kind(self.appearance_item(), false) { return first.appearance.stroke_at(Some(i)).cloned(); } - let mut nodes = vec![]; - painted(first, true, &mut nodes); - node_stroke(nodes.first()?) + // A Live Paint group without edges shows the next selected object's stroke; any other object + // without a painted object shows none. + for id in &st.selection.objects { + let Some(n) = st.doc.node(*id) else { continue }; + let mut nodes = vec![]; + painted(n, true, true, &mut nodes); + if let Some(n) = nodes.first() { + return node_stroke(n); + } + if !is_live_paint(n) { + return None; + } + } + None } /// Do all the strokes that `stroke.set` edits without `ids` or `item` draw with a brush @@ -488,12 +528,13 @@ impl DocState { let part = self.selected_symbol_part(); let mut nodes = vec![]; if let Some(part) = &part { - painted(part, true, &mut nodes); + painted(part, true, true, &mut nodes); } else { - for id in &self.selection.objects { - if let Some(n) = self.doc.node(*id) { - painted(n, true, &mut nodes); - } + let selected: Vec<&Node> = self.selection.objects.iter().filter_map(|id| self.doc.node(*id)).collect(); + // The faces and edges of the selected Live Paint groups: selected as well, they count with their group's. + let covered: std::collections::HashSet = selected.iter().flat_map(|n| live_paint_parts(n)).collect(); + for n in selected.into_iter().filter(|n| !covered.contains(&n.id)) { + painted(n, true, true, &mut nodes); } } let mut strokes = vec![]; @@ -568,9 +609,14 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result { if scale.is_none() && flip.is_none() && !swap && brush.is_none() { return Err(bad(C, "nothing to change")); } + // As stroke.set: the stroke the Live Paint Bucket paints with changes; the selection keeps its own. + // A brush still goes to the selection. + let bucket_p = if brush.is_none() { super::paint::bucket_color_params(s, p, C)? } else { None }; + let bucket = bucket_p.is_some(); + let p = bucket_p.as_ref().unwrap_or(p); let item = item_target(s, p, C)?.of_kind(s, false); - let ids = item.targets(s, p)?; - let new_art = no_targets(&ids, p); + let (ids, skipped) = if bucket { (vec![], false) } else { item.targets_and_skipped(s, p, false)? }; + let new_art = bucket || (no_targets(&ids, p) && !skipped); // The art of a graph design in a series keeps the design's stroke. let ids = super::appearance::drop_design_art_rows(s, ids, item, false, C)?; let arrows_and_profile = |st: &mut StrokeLayer| { diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 2b746b7634..76003551cd 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -9,7 +9,9 @@ use vectorcraft_doc::swatches::{LinkFn, PaintFn, color_name, map_node_paints, ma use vectorcraft_doc::{Document, NodeId}; use super::paint::paint_from; -use super::{CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, index, ok, str_param, switch_or}; +use super::{ + CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, index, ok, str_param, switch_or, text_param, +}; use crate::EngineError; pub fn specs() -> Vec { @@ -106,6 +108,15 @@ pub fn specs() -> Vec { has_doc, swatch_ungroup ), + cmd!( + "swatch.renameGroup", + "Color Group Options", + ["Window", "Swatches"], + None, + "{group: color group, name: its new name (trimmed)} rename a color group, as one undo step; its swatches, their colors and the art linked to them stay as they are. Swatches and color groups share one set of names, so a name another color group or a swatch has is an error, as is an empty name; the group's own name records no undo step. A drag still in progress becomes an undo step of its own first → {name}", + has_doc, + swatch_rename_group + ), cmd!( "swatch.sortByKind", "Sort by Kind", @@ -1200,6 +1211,35 @@ fn swatch_ungroup(s: &mut Session, p: &Value) -> Result { Ok(json!({ "swatches": moved })) } +fn swatch_rename_group(s: &mut Session, p: &Value) -> Result { + const C: &str = "swatch.renameGroup"; + let group = text_param(p, "group", C)?.ok_or_else(|| bad(C, "missing `group`"))?.to_string(); + let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing `name`"))?.trim().to_string(); + if name.is_empty() { + return Err(bad(C, "`name` is empty")); + } + let d = &s.doc()?.doc; + if !d.swatch_groups.iter().any(|g| g.name == group) { + return Err(bad(C, format!("no colour group `{group}`"))); + } + if name == group { + return Ok(json!({ "name": name })); + } + if d.swatch_name_taken(&name) { + return Err(bad(C, format!("a swatch or color group named `{name}` already exists"))); + } + // A drag still in progress is a step of its own, so canceling or undoing it leaves the rename. + if !s.previewing && s.batch_stash.is_none() && s.in_interaction() { + super::settle_interaction(s)?; + } + s.edit("Color Group Options", |d, _| { + let g = d.swatch_groups.iter_mut().find(|g| g.name == group).ok_or_else(|| bad(C, format!("no colour group `{group}`")))?; + g.name.clone_from(&name); + Ok(()) + })?; + Ok(json!({ "name": name })) +} + fn swatch_sort_by_kind(s: &mut Session, _: &Value) -> Result { let rank = |w: &Swatch| match &w.paint { Paint::None => 0, @@ -1279,40 +1319,63 @@ impl GroupEdit { /// Rewrite colour group `group` with `colors`: its swatches take them in order (keeping their /// names, kinds and global or spot flags), a `None` removes the swatch at its place, extra colors -/// are added as new swatches and swatches past the end are removed. Paints linked to its global +/// are added as new swatches and swatches past the end are removed. With `colors_only`, a swatch +/// that is not a color (a gradient, pattern or None swatch) keeps its place and paint and takes no +/// entry of `colors`, which go to the group's color swatches in order. Paints linked to its global /// swatches follow (a removed swatch's are unlinked); `rename` renames the group. A built-in swatch /// (None, Registration) it would change or remove is refused. -pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Option], rename: Option<&str>, cmd: &str) -> Result { +pub(super) fn rewrite_group( + d: &mut Document, + group: &str, + colors: &[Option], + colors_only: bool, + rename: Option<&str>, + cmd: &str, +) -> Result { let gi = d.swatch_groups.iter().position(|g| g.name == group).ok_or_else(|| bad(cmd, format!("no colour group `{group}`")))?; let name = match rename.map(str::trim).filter(|n| !n.is_empty() && *n != group) { Some(n) => d.free_swatch_name(n), None => group.to_string(), }; let old = &d.swatch_groups[gi].swatches; + // The place in `colors` of each swatch's new color; none for a swatch kept as it is. + let mut taken = 0; + let places: Vec> = old + .iter() + .map(|w| { + (!colors_only || w.paint.color().is_some()).then(|| { + taken += 1; + taken - 1 + }) + }) + .collect(); + let new_color = |place: Option| place.and_then(|i| colors.get(i).copied().flatten()); if let Some(w) = old .iter() - .enumerate() - .find(|(i, w)| w.is_reserved() && colors.get(*i).copied().flatten().is_none_or(|c| w.paint.color() != Some(c))) - .map(|x| x.1) + .zip(&places) + .find(|(w, place)| place.is_some() && w.is_reserved() && new_color(**place).is_none_or(|c| w.paint.color() != Some(c))) + .map(|x| x.0) { return Err(bad(cmd, format!("`{}` can't be edited or removed", w.name))); } let colorized_ok = super::paint::check_colorized(d).is_ok(); let mut relinks = vec![]; let old = std::mem::take(&mut d.swatch_groups[gi].swatches); - let old_len = old.len(); - // The swatches that stay, each with its new color. - let mut kept: Vec<(Swatch, Color)> = vec![]; - for (i, w) in old.into_iter().enumerate() { - match colors.get(i).copied().flatten() { - Some(c) => kept.push((w, c)), - None if w.global => relinks.push(Relink { from: w.name.clone(), to: w.name, color: None, keep: false }), - None => {} + // The swatches that stay, each with its new color (none for one kept as it is). + let mut kept: Vec<(Swatch, Option)> = vec![]; + for (w, place) in old.into_iter().zip(places) { + match (place, new_color(place)) { + (None, _) => kept.push((w, None)), + (_, Some(c)) => kept.push((w, Some(c))), + (_, None) if w.global => relinks.push(Relink { from: w.name.clone(), to: w.name, color: None, keep: false }), + (_, None) => {} } } let mut swatches = Vec::with_capacity(kept.len()); for (mut w, c) in kept { - if w.paint.color() != Some(c) { + if let Some(c) = c + && w.paint.color() != Some(c) + { // A tint swatch becomes a colour of its own. w.paint = Paint::solid(c); if w.global { @@ -1325,7 +1388,7 @@ pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Option Result { { return Ok(json!({"name": group, "swatches": g.swatches.iter().map(|w| w.name.clone()).collect::>(), "relinked": 0})); } - let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, rename, C))?; + let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, false, rename, C))?; e.defaults(s)?; Ok(json!({"name": e.name, "swatches": e.swatches, "relinked": e.relinked})) } diff --git a/crates/engine/src/cmd/symbollib.rs b/crates/engine/src/cmd/symbollib.rs index 3e4774a370..4eb909605e 100644 --- a/crates/engine/src/cmd/symbollib.rs +++ b/crates/engine/src/cmd/symbollib.rs @@ -170,6 +170,7 @@ pub const BUILTIN: &[BuiltinSymbolLibrary] = &[ BuiltinSymbolLibrary { id: "inventory-icons", name: "Inventory Icons", make: inventory_icons }, BuiltinSymbolLibrary { id: "skill-icons", name: "Skill Icons", make: skill_icons }, BuiltinSymbolLibrary { id: "weather-icons", name: "Weather Icons", make: weather_icons }, + BuiltinSymbolLibrary { id: "media-controls", name: "Media Controls", make: media_controls }, ]; /// Built-in library `id`, made once. @@ -502,6 +503,130 @@ fn weather_icons() -> SymbolLibrary { SymbolLibrary { name: "Weather Icons".into(), doc } } +/// Media Controls: play, pause, stop, skip next, shuffle and repeat for audio/video UI art (original, no 9-slice). +fn media_controls() -> SymbolLibrary { + // 1. Play: Right-pointing equilateral triangle. + let play = shapes::polygon(Point::ZERO, 18.0, 3, 90.0); + + // 2. Pause: Two parallel vertical rounded bars. + let mut pause_subpaths = Vec::new(); + pause_subpaths.extend(shapes::rounded_rectangle(Rect::new(-11.0, -15.0, -3.0, 15.0), 3.0).subpaths); + pause_subpaths.extend(shapes::rounded_rectangle(Rect::new(3.0, -15.0, 11.0, 15.0), 3.0).subpaths); + let pause = PathData::new(pause_subpaths); + + // 3. Stop: Rounded square. + let stop = shapes::rounded_rectangle(Rect::new(-14.0, -14.0, 14.0, 14.0), 4.0); + + // 4. Skip Next: Right-pointing triangle with adjacent vertical bar. + let mut skip_subpaths = Vec::new(); + let tri_pts = [Point::new(-14.0, -14.0), Point::new(6.0, 0.0), Point::new(-14.0, 14.0)]; + skip_subpaths.push(SubPath::polyline(&tri_pts, true)); + skip_subpaths.extend(shapes::rounded_rectangle(Rect::new(8.0, -14.0, 13.0, 14.0), 2.0).subpaths); + let skip_next = PathData::new(skip_subpaths); + + // Helper for ribbon arrows with optional arrowhead + let make_arrow = |pts: &[Point], half_w: f64, head: Option<(f64, f64)>| -> SubPath { + let n = pts.len(); + let mut left_pts = Vec::new(); + let mut right_pts = Vec::new(); + + let mut seg_normals = Vec::with_capacity(n - 1); + let mut seg_dirs = Vec::with_capacity(n - 1); + for i in 0..(n - 1) { + let d = pts[i + 1] - pts[i]; + let len = (d.x * d.x + d.y * d.y).sqrt().max(1e-6); + let dir = Point::new(d.x / len, d.y / len); + let normal = Point::new(-dir.y, dir.x); + seg_dirs.push(dir); + seg_normals.push(normal); + } + + for i in 0..n { + let normal = if i == 0 { + seg_normals[0] + } else if i == n - 1 { + seg_normals[n - 2] + } else { + let n1 = seg_normals[i - 1]; + let n2 = seg_normals[i]; + let avg = Point::new((n1.x + n2.x) * 0.5, (n1.y + n2.y) * 0.5); + let len = (avg.x * avg.x + avg.y * avg.y).sqrt().max(1e-6); + Point::new(avg.x / len, avg.y / len) + }; + left_pts.push(Point::new(pts[i].x + normal.x * half_w, pts[i].y + normal.y * half_w)); + right_pts.push(Point::new(pts[i].x - normal.x * half_w, pts[i].y - normal.y * half_w)); + } + + let mut poly = left_pts; + if let Some((head_w, head_len)) = head { + let end_pt = pts[n - 1]; + let end_dir = seg_dirs[n - 2]; + let end_norm = seg_normals[n - 2]; + poly.push(Point::new(end_pt.x + end_norm.x * head_w, end_pt.y + end_norm.y * head_w)); + poly.push(Point::new(end_pt.x + end_dir.x * head_len, end_pt.y + end_dir.y * head_len)); + poly.push(Point::new(end_pt.x - end_norm.x * head_w, end_pt.y - end_norm.y * head_w)); + } + right_pts.reverse(); + poly.extend(right_pts); + SubPath::polyline(&poly, true) + }; + + // 5. Shuffle: Two crossing/intertwined arrows. + let a1 = [Point::new(-14.0, -9.0), Point::new(-5.0, -9.0), Point::new(5.0, 9.0), Point::new(8.0, 9.0)]; + let a2a = [Point::new(-14.0, 9.0), Point::new(-5.0, 9.0), Point::new(-1.8, 3.24)]; + let a2b = [Point::new(1.8, -3.24), Point::new(5.0, -9.0), Point::new(8.0, -9.0)]; + let shuffle = PathData::new(vec![make_arrow(&a1, 1.4, Some((4.0, 6.0))), make_arrow(&a2a, 1.4, None), make_arrow(&a2b, 1.4, Some((4.0, 6.0)))]); + + // 6. Repeat: Looping circular arrows. + let r_mid = 11.5; + let r_in = 9.8; + let r_out = 13.2; + let head_w = 4.0; + let tip_len = 5.0; + let a_start = -150.0_f64.to_radians(); + let a_end = -15.0_f64.to_radians(); + let steps = 14; + + let mut top_pts = Vec::new(); + for i in 0..=steps { + let a = a_start + (a_end - a_start) * (i as f64) / (steps as f64); + top_pts.push(Point::new(r_out * a.cos(), r_out * a.sin())); + } + top_pts.push(Point::new((r_mid + head_w) * a_end.cos(), (r_mid + head_w) * a_end.sin())); + let t_dir = Point::new(-a_end.sin(), a_end.cos()); + top_pts.push(Point::new(r_mid * a_end.cos() + tip_len * t_dir.x, r_mid * a_end.sin() + tip_len * t_dir.y)); + top_pts.push(Point::new((r_mid - head_w) * a_end.cos(), (r_mid - head_w) * a_end.sin())); + for i in (0..=steps).rev() { + let a = a_start + (a_end - a_start) * (i as f64) / (steps as f64); + top_pts.push(Point::new(r_in * a.cos(), r_in * a.sin())); + } + + let bottom_pts: Vec = top_pts.iter().map(|p| Point::new(-p.x, -p.y)).collect(); + + let repeat = PathData::new(vec![SubPath::polyline(&top_pts, true), SubPath::polyline(&bottom_pts, true)]); + + let icons = [ + ("Play", play, "#2ecc71"), + ("Pause", pause, "#f39c12"), + ("Stop", stop, "#e74c3c"), + ("Skip Next", skip_next, "#3498db"), + ("Shuffle", shuffle, "#9b59b6"), + ("Repeat", repeat, "#1abc9c"), + ]; + let mut doc = Document::new(100.0, 100.0); + for (name, path, hex) in icons { + let fill = Color::from_hex(hex).unwrap_or(Color::BLACK); + let edge = fill.lerp(&Color::BLACK, 0.35); + let id = doc.alloc_id(); + let art = Node::path(id, path, Appearance::basic(Paint::solid(fill), Paint::solid(edge), 1.25)); + let Ok((art, size, _)) = normalize(art) else { continue }; + doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + set_natural_size(&mut doc, name, Some(size)); + } + doc.title = "Media Controls".into(); + SymbolLibrary { name: "Media Controls".into(), doc } +} + /// An instance of symbol `name` (what the resource gathering follows). fn instance(name: &str) -> Node { Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::IDENTITY }) diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 11bd1b4259..cde1456589 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -39,13 +39,37 @@ impl Kind { /// Attributes of style `name` (the Normal style is built in: empty unless redefined). fn attrs(self, d: &Document, name: &str) -> Option> { match self.defs(d).iter().find(|s| s.name == name) { - Some(s) => Some(s.attrs.clone()), + Some(s) => { + let mut attrs = s.attrs.clone(); + if self == Kind::Para { + kinsoku_pair(&mut attrs); + } + Some(attrs) + } None if name == self.normal() => Some(Map::new()), None => None, } } } +/// The two keys of Kinsoku Set: a built-in set (`kinsoku`) and a custom set (`kinsoku_set`), which +/// goes with Hard. +const KINSOKU: [&str; 2] = ["kinsoku", "kinsoku_set"]; + +/// Paragraph style attributes `attrs` with Kinsoku Set as one attribute: one that gives only +/// `kinsoku` gets no custom set, and one that gives only `kinsoku_set` gets Hard beside it. +fn kinsoku_pair(attrs: &mut Map) { + match (attrs.contains_key(KINSOKU[0]), attrs.contains_key(KINSOKU[1])) { + (true, false) => { + attrs.insert(KINSOKU[1].into(), Value::Null); + } + (false, true) => { + attrs.insert(KINSOKU[0].into(), json!(vectorcraft_doc::Kinsoku::Hard)); + } + _ => {} + } +} + /// One command spec (the `cmd!` macro wants literals; these ids are built with `concat!`). const fn spec(id: &'static str, label: &'static str, menu: &'static [&'static str], params: &'static str, run: Run, journal: bool) -> CommandSpec { CommandSpec { id, label, menu, shortcut: None, params, enabled: has_doc, run, journal, schema: None } @@ -253,6 +277,7 @@ pub fn para_attrs(v: &ParaStyle) -> Map { ("leading_model", json!(v.leading_model)), ("burasagari", json!(v.burasagari)), ("kinsoku", json!(v.kinsoku)), + ("kinsoku_set", json!(v.kinsoku_set)), ("kinsoku_type", json!(v.kinsoku_type)), ("bunri_kinshi", json!(v.bunri_kinshi)), ("kurikaeshi_moji_shori", json!(v.kurikaeshi_moji_shori)), @@ -325,6 +350,8 @@ fn restyle( // Starts from every key `cur` writes, so values no style sets (a glyph choice) are kept. let Some(mut m) = to_map(cur) else { return cur.clone() }; m.extend(attrs(cur)); + let pair = |m: &Map| KINSOKU.map(|k| m.get(k).cloned()); + let own = pair(&m); for (k, v) in new { if old.get(k).is_none_or(|o| m.get(k) == Some(o)) { m.insert(k.clone(), v.clone()); @@ -338,6 +365,25 @@ fn restyle( m.insert(k.clone(), base_value.clone()); } } + // Kinsoku Set's two keys change together: a paragraph whose Kinsoku Set is not the old + // style's keeps its own. + let has = |m: &Map| KINSOKU.iter().any(|k| m.contains_key(*k)); + if has(old) || has(new) { + let follows = !has(old) || pair(old) == own; + let to = if !follows { + own + } else if has(new) { + pair(new) + } else { + pair(base) + }; + for (k, v) in KINSOKU.into_iter().zip(to) { + match v { + Some(v) => m.insert(k.to_string(), v), + None => m.remove(k), + }; + } + } serde_json::from_value(Value::Object(m)).unwrap_or_else(|_| cur.clone()) } @@ -359,16 +405,27 @@ fn font_change(before: &CharStyle, mut st: CharStyle, attrs: &Map /// Change text in layers, symbols, graph designs, pattern tiles, saved pattern tiles restored by /// Cancel, and brush art, including opacity masks in those trees. pub(crate) fn each_text_mut(d: &mut Document, f: &mut impl FnMut(&mut vectorcraft_doc::TextObject) -> Result<()>) -> Result<()> { + each_node_with_text_mut(d, &mut |n| match &mut n.kind { + NodeKind::Text(t) => f(t), + _ => Ok(()), + }) +} + +/// Change the nodes [`each_text_mut`] reaches: each type object and each node holding one, and each +/// graph keeping paragraph attributes for its labels, with or without labels drawn. +pub(crate) fn each_node_with_text_mut(d: &mut Document, f: &mut impl FnMut(&mut Node) -> Result<()>) -> Result<()> { fn has_text(n: &Node) -> bool { matches!(n.kind, NodeKind::Text(_)) + || n.extras().graph.as_deref().is_some_and(|g| { + let l = &g.label_styles; + l.values_para.is_some() || l.categories_para.is_some() || l.legend_para.is_some() + }) || n.extras().mask.as_ref().is_some_and(|mask| has_text(&mask.art)) || n.children().is_some_and(|children| children.iter().any(|child| has_text(child))) } - fn visit(n: &mut Node, f: &mut impl FnMut(&mut vectorcraft_doc::TextObject) -> Result<()>) -> Result<()> { - if let NodeKind::Text(t) = &mut n.kind { - f(t)?; - } + fn visit(n: &mut Node, f: &mut impl FnMut(&mut Node) -> Result<()>) -> Result<()> { + f(n)?; if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_mut()) && has_text(&mask.art) { @@ -654,10 +711,43 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma } para_ranges(&st, m, kept, &c)?; sort_tabs(&mut st, m, kept); + // A custom Kinsoku set goes with Hard and has a name a custom set can have: one + // given beside None or Soft, or with a blank or built-in name, fails the call + // instead of being dropped. + if m.get("kinsoku_set").is_some_and(|v| !v.is_null()) && KINSOKU.iter().any(|k| kept.and_then(|kept| kept.get(*k)) != m.get(*k)) { + if st.kinsoku != vectorcraft_doc::Kinsoku::Hard { + return Err(bad(&c, "`kinsoku_set` goes with `kinsoku` Hard: give `kinsoku` as `hard` or leave it out")); + } + if st.kinsoku_set.is_none() { + return Err(bad(&c, "`kinsoku_set` needs the name of one of the document's Kinsoku sets")); + } + } + // A custom Kinsoku set is one of the document's, by name (any case), as + // `text.setFormat` chooses it; one the style already holds stays. + if let Some(set) = &st.kinsoku_set + && kept.and_then(|k| k.get("kinsoku_set")) != m.get("kinsoku_set") + { + let name = set.name.clone(); + let found = vectorcraft_doc::KinsokuSet::named(&d.kinsoku_sets, &name).cloned().map(std::sync::Arc::new); + st.kinsoku_set = + Some(found.ok_or_else(|| bad(&c, format!("`kinsoku_set`: the document has no Kinsoku set named `{name}`")))?); + } para_attrs(&st) } }; - Ok(Some(m.keys().filter_map(|k| full.get(k).map(|v| (k.clone(), v.clone()))).collect())) + let mut out: Map = m.keys().filter_map(|k| full.get(k).map(|v| (k.clone(), v.clone()))).collect(); + // A paragraph style giving one key of Kinsoku Set keeps both, so applying it replaces a + // paragraph's custom set or built-in set. + if kind == Kind::Para { + for k in KINSOKU { + if KINSOKU.iter().any(|g| m.contains_key(*g)) + && let Some(v) = full.get(k) + { + out.insert(k.into(), v.clone()); + } + } + } + Ok(Some(out)) } Some(_) => Err(bad(&kind.cmd(verb), "attrs must be an object")), } diff --git a/crates/engine/src/cmd/toast.rs b/crates/engine/src/cmd/toast.rs new file mode 100644 index 0000000000..e2eb41bd21 --- /dev/null +++ b/crates/engine/src/cmd/toast.rs @@ -0,0 +1,283 @@ +//! `app.toast`: a short message shown over the window that does not stop work and goes away by +//! itself (a toast). Scripts (`vc.run`), actions (a recorded step), MCP clients and plug-ins raise +//! one with the command, and the app's code can raise one with [`Session::toast`]. The engine +//! queues the messages and the desktop app takes them each frame ([`Session::take_toasts`]) and +//! shows them. A failed script run puts the documents back but keeps the messages it raised. + +use std::collections::VecDeque; + +use serde_json::{Value, json}; + +use super::{CommandSpec, Result, always, bad, cmd}; +use crate::Session; + +const ID: &str = "app.toast"; + +/// The most characters a message has. +pub const MAX_CHARS: usize = 500; + +/// How long a message shows when `seconds` is omitted, and the shortest and longest time it may +/// show. +pub const DEFAULT_SECONDS: f64 = 4.0; +pub const MIN_SECONDS: f64 = 0.5; +pub const MAX_SECONDS: f64 = 60.0; + +/// The most messages waiting for the app to take them: past it the oldest one goes. A session +/// without a window (the headless MCP server, `vectorcraft-cli run`) never takes them. +pub const MAX_QUEUED: usize = 32; + +/// What kind of news a message is, which sets its color. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Level { + #[default] + Info, + Success, + Warning, + Error, +} + +impl Level { + pub const ALL: [Level; 4] = [Level::Info, Level::Success, Level::Warning, Level::Error]; + + /// Its `level` value. + pub fn param(self) -> &'static str { + match self { + Level::Info => "info", + Level::Success => "success", + Level::Warning => "warning", + Level::Error => "error", + } + } + + /// The level whose `level` value is `param`. + pub fn from_param(param: &str) -> Option { + Level::ALL.into_iter().find(|l| l.param() == param) + } +} + +/// A message to show. +#[derive(Clone, Debug, PartialEq)] +pub struct Toast { + pub message: String, + pub level: Level, + /// How long it shows, in seconds. + pub seconds: f64, +} + +impl Toast { + /// A message of `level` shown for [`DEFAULT_SECONDS`]. + pub fn new(message: impl Into, level: Level) -> Toast { + Toast { message: message.into(), level, seconds: DEFAULT_SECONDS } + } +} + +/// The messages waiting for the app to show them. +#[derive(Clone, Debug, Default)] +pub struct Queue(VecDeque); + +impl Session { + /// Queue `toast` for the app to show. With [`MAX_QUEUED`] waiting, the oldest one goes. Its + /// time is held to [`MIN_SECONDS`] to [`MAX_SECONDS`], and a time that is not a number is + /// [`DEFAULT_SECONDS`]. + pub fn toast(&mut self, mut toast: Toast) { + toast.seconds = if toast.seconds.is_nan() { DEFAULT_SECONDS } else { toast.seconds.clamp(MIN_SECONDS, MAX_SECONDS) }; + while self.toasts.0.len() >= MAX_QUEUED { + self.toasts.0.pop_front(); + } + self.toasts.0.push_back(toast); + } + + /// Take the messages queued since the last call, oldest first. + pub fn take_toasts(&mut self) -> Vec { + self.toasts.0.drain(..).collect() + } +} + +pub fn specs() -> Vec { + vec![cmd!( + "app.toast", + "Show Message", + [], + None, + "{message: string (1 to 500 characters, not only whitespace), level?: \"info\" | \"success\" | \"warning\" | \"error\" (default \"info\"), seconds?: number 0.5 to 60 (default 4)} show `message` over the window without stopping work: it goes away after `seconds` or when clicked; messages stack at the window's bottom right, the newest lowest, at most 5 at once; edits no document; an action records it as a step → {message, level, seconds}", + always, + run + )] +} + +fn run(s: &mut Session, p: &Value) -> Result { + let toast = parse(p)?; + let r = json!({"message": &toast.message, "level": toast.level.param(), "seconds": toast.seconds}); + s.toast(toast); + Ok(r) +} + +/// The message `p` asks for; an invalid value of any key is an error. +fn parse(p: &Value) -> Result { + let message = match p.get("message") { + Some(Value::String(m)) => m, + Some(_) => return Err(bad(ID, "`message` must be a string")), + None => return Err(bad(ID, "`message` is required")), + }; + if message.trim().is_empty() { + return Err(bad(ID, "`message` must have a character other than whitespace")); + } + let chars = message.chars().count(); + if chars > MAX_CHARS { + return Err(bad(ID, format!("`message` has {chars} characters; at most {MAX_CHARS} are allowed"))); + } + let level = match p.get("level") { + None => Level::default(), + Some(v) => v.as_str().and_then(Level::from_param).ok_or_else(|| { + let all: Vec<&str> = Level::ALL.iter().map(|l| l.param()).collect(); + bad(ID, format!("`level` must be one of {}", all.join(", "))) + })?, + }; + let seconds = match p.get("seconds") { + None => DEFAULT_SECONDS, + Some(v) => v + .as_f64() + .filter(|s| (MIN_SECONDS..=MAX_SECONDS).contains(s)) + .ok_or_else(|| bad(ID, format!("`seconds` must be a number from {MIN_SECONDS} to {MAX_SECONDS}")))?, + }; + Ok(Toast { message: message.clone(), level, seconds }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_message_is_queued_with_its_defaults() { + let mut s = Session::new(); + let r = s.execute(ID, &json!({"message": "Saved 3 files"})).unwrap(); + assert_eq!(r, json!({"message": "Saved 3 files", "level": "info", "seconds": 4.0})); + assert_eq!(s.take_toasts(), vec![Toast::new("Saved 3 files", Level::Info)]); + // Taken once. + assert_eq!(s.take_toasts(), vec![]); + } + + #[test] + fn level_and_seconds_are_kept() { + let mut s = Session::new(); + for level in Level::ALL { + s.execute(ID, &json!({"message": "m", "level": level.param(), "seconds": 0.5})).unwrap(); + } + s.execute(ID, &json!({"message": "long", "seconds": 60})).unwrap(); + let got: Vec<(Level, f64)> = s.take_toasts().iter().map(|t| (t.level, t.seconds)).collect(); + assert_eq!(got, vec![(Level::Info, 0.5), (Level::Success, 0.5), (Level::Warning, 0.5), (Level::Error, 0.5), (Level::Info, 60.0)]); + } + + #[test] + fn invalid_values_are_errors_and_queue_nothing() { + let mut s = Session::new(); + let long = "x".repeat(MAX_CHARS + 1); + for p in [ + json!({}), + json!({"message": 3}), + json!({"message": ""}), + json!({"message": " \n\t"}), + json!({"message": long}), + json!({"message": "m", "level": "loud"}), + json!({"message": "m", "level": 1}), + json!({"message": "m", "seconds": 0.4}), + json!({"message": "m", "seconds": 61}), + json!({"message": "m", "seconds": "4"}), + json!({"message": "m", "seconds": null}), + ] { + let e = s.execute(ID, &p).unwrap_err().to_string(); + assert!(e.contains(ID), "{p}: {e}"); + } + assert_eq!(s.take_toasts(), vec![]); + // The longest message is allowed, counted in characters, not bytes. + let most = "é".repeat(MAX_CHARS); + s.execute(ID, &json!({"message": most})).unwrap(); + assert_eq!(s.take_toasts().len(), 1); + } + + #[test] + fn a_message_queued_by_the_app_shows_for_0_5_to_60_seconds() { + let mut s = Session::new(); + for seconds in [f64::INFINITY, 1e9, f64::NEG_INFINITY, 0.0, f64::NAN, 10.0] { + s.toast(Toast { seconds, ..Toast::new("m", Level::Info) }); + } + let got: Vec = s.take_toasts().iter().map(|t| t.seconds).collect(); + assert_eq!(got, vec![MAX_SECONDS, MAX_SECONDS, MIN_SECONDS, MIN_SECONDS, DEFAULT_SECONDS, 10.0]); + } + + #[test] + fn the_oldest_waiting_message_goes_past_the_limit() { + let mut s = Session::new(); + for i in 0..MAX_QUEUED + 2 { + s.toast(Toast::new(format!("{i}"), Level::Info)); + } + let left: Vec = s.take_toasts().into_iter().map(|t| t.message).collect(); + assert_eq!(left.len(), MAX_QUEUED); + assert_eq!(left.first().map(String::as_str), Some("2")); + assert_eq!(left.last().map(String::as_str), Some("33")); + } + + #[test] + fn a_message_is_journaled_without_an_undo_step_or_a_document() { + let mut s = Session::new(); + // No document open. + s.execute(ID, &json!({"message": "no document"})).unwrap(); + assert_eq!(s.journal.last().unwrap(), &(ID.to_string(), json!({"message": "no document"}))); + s.execute("file.new", &json!({})).unwrap(); + let undo = s.active().unwrap().history.undo.len(); + let revision = s.active().unwrap().revision; + s.execute(ID, &json!({"message": "m", "level": "success"})).unwrap(); + assert_eq!(s.journal.last().unwrap(), &(ID.to_string(), json!({"message": "m", "level": "success"}))); + assert_eq!(s.active().unwrap().history.undo.len(), undo); + assert_eq!(s.active().unwrap().revision, revision); + } + + #[test] + fn a_script_raises_a_message_with_vc_run() { + let mut s = Session::new(); + let r = s + .execute( + "script.run", + &json!({"source": "vc.run('app.toast', {message: 'Done: ' + (1 + 1), level: 'success'});", "name": "t.js", "answers": []}), + ) + .unwrap(); + assert!(r.get("error").is_none_or(Value::is_null), "{r}"); + assert_eq!(s.take_toasts(), vec![Toast::new("Done: 2", Level::Success)]); + } + + #[test] + fn a_failed_script_run_puts_the_documents_back_and_keeps_its_messages() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let art = format!("{:?}", s.active().unwrap().doc.layers); + let e = s + .execute( + "script.run", + &json!({ + "source": "vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10}); vc.run('app.toast', {message: 'Failed: no artboard'}); throw new Error('stop');", + "name": "t.js", + "answers": [], + }), + ) + .unwrap_err() + .to_string(); + assert!(e.contains("stop"), "{e}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), art, "the rectangle is put back"); + assert_eq!(s.take_toasts(), vec![Toast::new("Failed: no artboard", Level::Info)]); + } + + #[test] + fn a_command_batch_raises_its_messages_in_order() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute( + "command.batch", + &json!({"commands": [ + {"command": "app.toast", "params": {"message": "one"}}, + {"command": "app.toast", "params": {"message": "two", "level": "warning"}}, + ]}), + ) + .unwrap(); + assert_eq!(s.take_toasts(), vec![Toast::new("one", Level::Info), Toast::new("two", Level::Warning)]); + } +} diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index 359b369a89..e9c316157f 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -10,8 +10,8 @@ use super::object::choice; use super::threads::ThreadIndex; use super::typecmd::{area_text, block_gaps, needed_room, refresh_bounds}; use super::{ - CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, named_ids, - number_or, switch_or, targets, text_param, + CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, index_opt, + named_ids, number_or, object_param, switch_or, targets, text_param, }; pub fn specs() -> Vec { @@ -120,7 +120,7 @@ pub fn specs() -> Vec { "Find and Replace…", ["Edit"], None, - "{find, replace?: \"\", matchCase?: false, wholeWord?: false, ids?} replace in every text object (or ids) → {count}. Matches never span style runs.", + "{find, replace?: \"\", matchCase?: false, wholeWord?: false, hiddenLayers?: false, lockedLayers?: false, ids?} replace every match in the type the search reaches (or in ids, whatever their layers), as one undo step → {count (every match), replaced (the matches that did not already read as `replace`)}. The search reaches visible, unlocked type on visible, unlocked layers, off locked artboards; hiddenLayers adds the type of hidden layers and sublayers and lockedLayers that of locked ones, while a hidden or locked object or group keeps its type out. Matches never span style runs. When nothing matches, or every match already reads as `replace`, nothing changes and no undo step is recorded.", has_doc, find_replace ), @@ -129,16 +129,25 @@ pub fn specs() -> Vec { "Find Next", ["Edit"], None, - "{find, matchCase?, wholeWord?} select the next text object (after the selected one, wrapping) containing `find` → {id|null}", + "{find, matchCase?: false, wholeWord?: false, backwards?: false, hiddenLayers?: false, lockedLayers?: false, from?: {id, start, end} (a match this command returned, or the range edit.replaceMatch returned)} find the next match of `find` in the type edit.findReplace reaches and select its type object → {id, start, end (the match's bytes in the object's plain text), index (its place among all the matches, from 1), count, selected} or {id: null, count: 0}. The search visits type objects from the top of the stacking order down and each object's matches in reading order; backwards visits the objects from the bottom up and each object's matches from the last. It goes on after `from` and, past the last match, starts again at the first. Without `from` it goes on after the first selected type object, and with no type selected, or with a null `from`, it starts at the first match. A match on a hidden or locked layer is returned with selected false and the selection stays as it is. Nothing is recorded for undo.", has_doc, find_next ), + cmd!( + "edit.replaceMatch", + "Replace", + [], + None, + "{find, replace?: \"\", matchCase?: false, wholeWord?: false, id, start, end} replace one match of `find`, the bytes start..end of type object id as edit.findNext returns them, with `replace`, as one undo step → {id, start, end (the replacement's bytes; pass them to edit.findNext as `from` to go on), replaced}. Bytes that are no match of `find` are refused. When the match already reads as `replace`, nothing changes, no undo step is recorded and replaced is false.", + has_doc, + replace_one + ), cmd!( "edit.pasteWithoutFormatting", "Paste without Formatting", ["Edit"], Some("Cmd+Alt+V"), - "{center?, dx?, dy?, swatchConflict?} paste as edit.paste; pasted text takes the default character style (one run) and leaves its character and paragraph styles behind, as do the labels of pasted graphs, which take a new graph's label character style and paragraph attributes (keeping their alignment); a pasted graph no longer keeps its labels' character and paragraph formats, so a later redraw sets them the same way → {ids, added, merged, renamed}", + "{center?, dx?, dy?, swatchConflict?, profileMismatch?} paste as edit.paste; pasted text takes the default character style (one run) and leaves its character and paragraph styles behind, as do the labels of pasted graphs, which take a new graph's label character style and paragraph attributes (keeping their alignment); a pasted graph no longer keeps its labels' character and paragraph formats, so a later redraw sets them the same way → {ids, added, merged, renamed}", has_clipboard, paste_plain ), @@ -1657,14 +1666,9 @@ fn is_word(c: char) -> bool { c.is_alphanumeric() || c == '_' } -/// Byte ranges of `needle` in `hay`. -pub(crate) fn find_all(hay: &str, needle: &str, match_case: bool, whole_word: bool) -> Vec<(usize, usize)> { - find_all_between(hay, needle, match_case, whole_word, None, None) -} - -/// [`find_all`] in run `i` of `runs`: a whole word looks past the run's ends at the characters -/// next to it, so a change of style inside a word is not a word boundary (#5901). Matches stay -/// inside the run. +/// Byte ranges of `needle` in run `i` of `runs`: a whole word looks past the run's ends at the +/// characters next to it, so a change of style inside a word is not a word boundary (#5901). +/// Matches stay inside the run. fn find_in_run(runs: &[TextRun], i: usize, needle: &str, match_case: bool, whole_word: bool) -> Vec<(usize, usize)> { let Some(run) = runs.get(i) else { return vec![] }; let before = runs.get(..i).and_then(|r| r.iter().rev().find_map(|r| r.text.chars().next_back())); @@ -1672,8 +1676,8 @@ fn find_in_run(runs: &[TextRun], i: usize, needle: &str, match_case: bool, whole find_all_between(&run.text, needle, match_case, whole_word, before, after) } -/// [`find_all`], with `before` and `after` the characters on either side of `hay` (none at the -/// text's ends), which a whole word must not touch either. +/// Byte ranges of `needle` in `hay`, with `before` and `after` the characters on either side of +/// `hay` (none at the text's ends), which a whole word must not touch either. fn find_all_between(hay: &str, needle: &str, match_case: bool, whole_word: bool, before: Option, after: Option) -> Vec<(usize, usize)> { let nc: Vec = needle.chars().collect(); if nc.is_empty() { @@ -1705,102 +1709,234 @@ fn find_all_between(hay: &str, needle: &str, match_case: bool, whole_word: bool, /// The visible, unlocked type objects of visible, unlocked layers, off locked artboards, in paint /// order: the text Find and Replace and Check Spelling go through. pub(crate) fn all_texts(d: &Document) -> Vec { - fn visit(n: &Node, locks: &LockedArtboards<'_>, v: &mut Vec) { - if !n.visible || n.locked { + searched_texts(d, false, false) +} + +/// [`all_texts`], with the type of hidden layers (`hidden_layers`) and of locked layers +/// (`locked_layers`) as well, as Check Hidden Layers and Check Locked Layers of Find and Replace +/// ask. The switches are about layers and sublayers: a hidden or locked object or group keeps its +/// type out, and so does a locked artboard. +fn searched_texts(d: &Document, hidden_layers: bool, locked_layers: bool) -> Vec { + fn visit(n: &Node, locks: &LockedArtboards<'_>, layers: (bool, bool), v: &mut Vec) { + let layer = matches!(n.kind, NodeKind::Layer { .. }); + if (!n.visible && !(layer && layers.0)) || (n.locked && !(layer && layers.1)) { return; } if matches!(n.kind, NodeKind::Text(_)) && !locks.holds_id(n.id) { v.push(n.id); } for c in n.children().into_iter().flatten() { - visit(c, locks, v); + visit(c, locks, layers, v); } } let mut v = vec![]; let locks = d.locked_artboards(); for l in &d.layers { - visit(l, &locks, &mut v); + visit(l, &locks, (hidden_layers, locked_layers), &mut v); } v } +/// What Find and Replace looks for: the text, Match Case and Find Whole Word. +struct Query { + find: String, + match_case: bool, + whole_word: bool, +} + +impl Query { + /// The `find`, `matchCase` and `wholeWord` params of command `c`. An empty or missing `find` + /// is an error. + fn of(p: &Value, c: &str) -> Result { + let find = text_param(p, "find", c)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(c, "missing `find`"))?.to_string(); + Ok(Self { find, match_case: switch_or(p, "matchCase", false, c)?, whole_word: switch_or(p, "wholeWord", false, c)? }) + } + + /// The matches in `t`, in reading order, each as (run, start, end) with `start..end` the bytes + /// of the match in the object's plain text. A match stays inside one style run, and an inline + /// graphic is art, not characters to find. + fn matches(&self, t: &TextObject) -> Vec<(usize, usize, usize)> { + let mut hits = vec![]; + let mut base = 0; + for (ri, r) in t.runs.iter().enumerate() { + if r.inline.is_none() { + hits.extend( + find_in_run(&t.runs, ri, &self.find, self.match_case, self.whole_word).into_iter().map(|(a, b)| (ri, base + a, base + b)), + ); + } + base += r.text.len(); + } + hits + } +} + +/// Replace bytes `start..end` of the plain text of `t`, which lie inside run `run`, with `rep`. +/// The paragraph styles and the ruby follow the edit, as `text.editRange` moves them. The caller +/// refreshes the bounds. +fn replace_match(t: &mut TextObject, run: usize, start: usize, end: usize, rep: &str) { + let base: usize = t.runs.iter().take(run).map(|r| r.text.len()).sum(); + let (Some(a), Some(b)) = (start.checked_sub(base), end.checked_sub(base)) else { return }; + if !t.runs.get(run).is_some_and(|r| a <= b && r.text.is_char_boundary(a) && r.text.is_char_boundary(b)) { + return; + } + t.splice_paras(start, end, rep); + if let Some(r) = t.runs.get_mut(run) { + r.text.replace_range(a..b, rep); + } + t.ruby_after_replace(start, end, rep.len()); +} + fn find_replace(s: &mut Session, p: &Value) -> Result { const C: &str = "edit.findReplace"; - let find = text_param(p, "find", C)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "missing `find`"))?.to_string(); + let q = Query::of(p, C)?; let rep = text_param(p, "replace", C)?.unwrap_or("").to_string(); - let (mc, ww) = (switch_or(p, "matchCase", false, C)?, switch_or(p, "wholeWord", false, C)?); + let (hidden, locked) = (switch_or(p, "hiddenLayers", false, C)?, switch_or(p, "lockedLayers", false, C)?); let ids = match p.get("ids").filter(|v| !v.is_null()) { Some(_) => text_ids(&s.doc()?.doc, &checked_ids_param(s, p, "ids", C)?), - None => all_texts(&s.doc()?.doc), + None => searched_texts(&s.doc()?.doc, hidden, locked), }; let st = s.doc()?; - let total: usize = ids + // Every match, and the matches that do not already read as the replacement. + let (total, replaced) = ids .iter() .filter_map(|id| match &st.doc.node(*id)?.kind { - NodeKind::Text(t) => Some((0..t.runs.len()).map(|i| find_in_run(&t.runs, i, &find, mc, ww).len()).sum::()), + NodeKind::Text(t) => { + let plain = t.plain_text(); + let hits = q.matches(t); + Some((hits.len(), hits.iter().filter(|(_, a, b)| plain.get(*a..*b) != Some(rep.as_str())).count())) + } _ => None, }) - .sum(); - if total == 0 { - return Ok(json!({ "count": 0 })); + .fold((0, 0), |(n, r), (hn, hr)| (n + hn, r + hr)); + if replaced == 0 { + return Ok(json!({ "count": total, "replaced": 0 })); } super::overprint::edit_counted(s, "Replace", |d| { let mut changed = 0; for id in &ids { let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; - // Matches as (run, start, end) with offsets inside the run. Inline graphics are art, not - // characters to rewrite. - let mut hits = vec![]; - let mut base = 0; - for (ri, r) in t.runs.iter().enumerate() { - if r.inline.is_none() { - for (a, b) in find_in_run(&t.runs, ri, &find, mc, ww) { - if r.text.get(a..b) != Some(rep.as_str()) { - hits.push((ri, base + a, base + b, a, b)); - } - } - } - base += r.text.len(); - } + let plain = t.plain_text(); + let hits: Vec<_> = q.matches(t).into_iter().filter(|(_, a, b)| plain.get(*a..*b) != Some(rep.as_str())).collect(); if hits.is_empty() { continue; } - // Last match first, so the offsets of earlier ones stay valid. The paragraph styles follow - // each edit, as `text.editRange` does. - for (ri, ta, tb, a, b) in hits.into_iter().rev() { - t.splice_paras(ta, tb, &rep); - if let Some(r) = t.runs.get_mut(ri) { - r.text.replace_range(a..b, &rep); - } + // Last match first, so the offsets of earlier ones stay valid. + for (ri, a, b) in hits.into_iter().rev() { + replace_match(t, ri, a, b, &rep); } changed += 1; refresh_bounds(t); } Ok(changed) })?; - Ok(json!({ "count": total })) + Ok(json!({ "count": total, "replaced": replaced })) +} + +/// A match of Find and Replace: bytes `start..end` of the plain text of type object `id`. +#[derive(Clone, Copy)] +struct Match { + id: NodeId, + start: usize, + end: usize, +} + +impl Match { + /// The `id`, `start` and `end` that `p` gives for a match, under command `c`: an object id and + /// two byte offsets, put in order as `text.editRange` orders its own. + fn of(p: &Value, c: &str) -> Result { + let whole = |key: &str| index_opt(p, key, c)?.ok_or_else(|| bad(c, format!("missing `{key}`"))); + let id = object_param(p, "id", c)?.ok_or_else(|| bad(c, "missing `id`"))?; + let (start, end) = (whole("start")?, whole("end")?); + Ok(Self { id, start: start.min(end), end: start.max(end) }) + } } fn find_next(s: &mut Session, p: &Value) -> Result { const C: &str = "edit.findNext"; - let find = text_param(p, "find", C)?.filter(|f| !f.is_empty()).ok_or_else(|| bad(C, "missing `find`"))?.to_string(); - let (mc, ww) = (switch_or(p, "matchCase", false, C)?, switch_or(p, "wholeWord", false, C)?); + let q = Query::of(p, C)?; + let backwards = switch_or(p, "backwards", false, C)?; + let (hidden, locked) = (switch_or(p, "hiddenLayers", false, C)?, switch_or(p, "lockedLayers", false, C)?); + // A `from` that is no object gives no `id`, and is refused as one without it. A null `from` + // starts at the first match, whatever is selected. + let from = match p.get("from") { + None => None, + Some(Value::Null) => Some(None), + Some(v) => Some(Some(Match::of(v, C)?)), + }; let st = s.doc()?; - let all = all_texts(&st.doc); - let cur = st.selection.objects.first().and_then(|id| all.iter().position(|x| x == id)); - let n = all.len(); - let start = cur.map(|c| c + 1).unwrap_or(0); - let hit = (0..n).map(|k| all[(start + k) % n.max(1)]).find(|id| match st.doc.node(*id).map(|n| &n.kind) { - Some(NodeKind::Text(t)) => !find_all(&t.plain_text(), &find, mc, ww).is_empty(), - _ => false, - }); - match hit { - Some(id) => { - s.select(|_, sel| sel.set([id]))?; - Ok(json!({ "id": id.0 })) - } - None => Ok(json!({ "id": null })), + // The objects in the order the search visits them: from the top of the stacking order down, + // or with Search Backwards from the bottom up. + let mut order = searched_texts(&st.doc, hidden, locked); + if !backwards { + order.reverse(); } + // Every match in that order as (object's place, match): inside an object in reading order, or + // with Search Backwards from its end. + let mut all: Vec<(usize, Match)> = vec![]; + for (place, id) in order.iter().enumerate() { + let Some(NodeKind::Text(t)) = st.doc.node(*id).map(|n| &n.kind) else { continue }; + let mut hits = q.matches(t); + if backwards { + hits.reverse(); + } + all.extend(hits.into_iter().map(|(_, start, end)| (place, Match { id: *id, start, end }))); + } + if all.is_empty() { + return Ok(json!({ "id": null, "count": 0 })); + } + // The search goes on from `from`, or from the whole of the first selected type object it + // visits, so that the same call again reaches the next object. From anywhere else it starts + // at the first match. + let from = from.unwrap_or_else(|| { + st.selection.objects.iter().filter(|id| order.contains(id)).find_map(|id| match &st.doc.node(*id)?.kind { + NodeKind::Text(t) => Some(Match { id: *id, start: 0, end: t.runs.iter().map(|r| r.text.len()).sum() }), + _ => None, + }) + }); + let after = |(place, m): &(usize, Match), at: usize, f: &Match| { + *place > at || (*place == at && if backwards { m.end <= f.start } else { m.start >= f.end }) + }; + let k = from + .and_then(|f| order.iter().position(|id| *id == f.id).map(|at| (at, f))) + .and_then(|(at, f)| all.iter().position(|hit| after(hit, at, &f))) + .unwrap_or(0); + let Some((_, m)) = all.get(k).copied() else { return Ok(json!({ "id": null, "count": 0 })) }; + let count = all.len(); + // Type that a selection tool can't reach (on a hidden or locked layer) is found without being + // selected. + let selected = all_texts(&st.doc).contains(&m.id); + if selected && st.selection.objects != [m.id] { + s.select(|_, sel| sel.set([m.id]))?; + } + let index = if backwards { count - k } else { k + 1 }; + Ok(json!({ "id": m.id.0, "start": m.start, "end": m.end, "index": index, "count": count, "selected": selected })) +} + +fn replace_one(s: &mut Session, p: &Value) -> Result { + const C: &str = "edit.replaceMatch"; + let q = Query::of(p, C)?; + let rep = text_param(p, "replace", C)?.unwrap_or("").to_string(); + let m = Match::of(p, C)?; + let st = s.doc()?; + let t = match st.doc.node(m.id).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => t, + Some(_) => return Err(bad(C, format!("node {} is not text", m.id.0))), + None => return Err(EngineError::NoNode(m.id)), + }; + let Some((run, ..)) = q.matches(t).into_iter().find(|(_, a, b)| (*a, *b) == (m.start, m.end)) else { + return Err(bad(C, format!("no match of `find` at bytes {}..{} of object {}", m.start, m.end, m.id.0))); + }; + let end = m.start + rep.len(); + if t.plain_text().get(m.start..m.end) == Some(rep.as_str()) { + return Ok(json!({ "id": m.id.0, "start": m.start, "end": end, "replaced": false })); + } + s.edit("Replace", |d, _| { + let Some(NodeKind::Text(t)) = d.node_mut(m.id).map(|n| &mut n.kind) else { return Err(EngineError::NoNode(m.id)) }; + replace_match(t, run, m.start, m.end, &rep); + refresh_bounds(t); + Ok(()) + })?; + Ok(json!({ "id": m.id.0, "start": m.start, "end": end, "replaced": true })) } // ---------- Paste without Formatting ---------- diff --git a/crates/engine/src/cmd/variablecmds/library.rs b/crates/engine/src/cmd/variablecmds/library.rs index 8886c597da..f68551aefe 100644 --- a/crates/engine/src/cmd/variablecmds/library.rs +++ b/crates/engine/src/cmd/variablecmds/library.rs @@ -250,7 +250,6 @@ fn parse_library(xml: &str, cmd: &str, text_only: bool) -> Result { craft_xml::Error::TooDeep(_) => bad(cmd, format!("the variable library nests elements more than {MAX_LIBRARY_NESTING} deep")), _ => bad(cmd, format!("the variable library is not well-formed XML: {e}")), })?; - crate::cmd::xmlattrs::validate(xml.as_bytes(), opts.limits).map_err(|e| bad(cmd, format!("the variable library is not well-formed XML: {e}")))?; let Some(root) = std::iter::once(&doc).chain(doc.descendants()).find(|n| n.is(craft_xml::Local("variableSets"))) else { return Err(bad(cmd, "the file holds no `variableSets` element")); }; diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index 897cd87c55..498982a7f9 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Save for Web", [], None, - "{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries; a new reduction without colorTable clears it and deleted)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/.), output?: images (default)|html (an HTML page placing the image or slices, .html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself", + "{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries, its transparent colors taking one slot together; a new reduction without colorTable clears it and deleted), shifted?: {\"#source\": \"#rrggbb\"…} (each source color is written as the color given, wherever it is in the image; kept when reducing as a locked color is, before the locked ones, while one palette slot is left for the reduction; at most 256; a source the table does not hold shifts nothing; a color shifted to itself is removed; a shifted color is not web-shifted, and a transparent one stays transparent; GIF lossy moves no pixel into or out of a shifted color)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/.), output?: images (default)|html (an HTML page placing the image or slices, .html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself", has_doc, export ), @@ -41,7 +41,7 @@ pub fn specs() -> Vec { "Save for Web Preview", [], None, - "{…the settings of document.exportForWeb (preset?, format?…), slice?: n (1-based, from slice.list; default the whole image), kbps?: 56.6 (connection speed for the download time), image?: false (also the optimised file as dataBase64)} what Save writes for the whole image (or one slice) → {format, width, height, bytes (exactly the file's size), seconds (to download at kbps), kbps, colors?: [{color: \"#rrggbb\", source: \"#rrggbb\" (the colour the reduction made, as colorTable lists it), transparent, locked, webShifted, webSafe}] (gif/png8: the colour table in file order), mappedToTransparent?: [\"#rrggbb\"…], slices: images an export writes, warnings (as document.exportForWeb's), dataBase64?}", + "{…the settings of document.exportForWeb (preset?, format?…), slice?: n (1-based, from slice.list; default the whole image), kbps?: 56.6 (connection speed for the download time), image?: false (also the optimised file as dataBase64)} what Save writes for the whole image (or one slice) → {format, width, height, bytes (exactly the file's size), seconds (to download at kbps), kbps, colors?: [{color: \"#rrggbb\", source: \"#rrggbb\" (the colour the reduction made, as colorTable lists it), transparent, locked, webShifted, shifted (by colorTable.shifted; also locked), webSafe}] (gif/png8: the colour table in file order), mappedToTransparent?: [\"#rrggbb\"…], slices: images an export writes, warnings (as document.exportForWeb's), dataBase64?}", has_doc, preview ), @@ -331,8 +331,14 @@ pub struct ColorTable { /// A fixed palette (a Custom table) used instead of the reduction's own: the colors of the /// table when the first color was deleted. Empty: the reduction makes the palette. pub custom_palette: Vec, + /// Colors shifted by hand: each source color (`#rrggbb`) and the color it is written as. A + /// shifted color is locked, and a source the table does not hold shifts nothing. + pub shifted: std::collections::BTreeMap, } +/// A color shifted by hand: (source, color written). +type Shift = ([u8; 3], [u8; 3]); + /// The most colours a colour table list holds. const MAX_TABLE: usize = 256; @@ -352,6 +358,21 @@ impl ColorTable { list.iter().map(|h| Self::rgb(h).ok_or_else(|| format!("colorTable.{what}: `{h}` is not a colour such as \"#ff8800\""))).collect() } + /// The colors shifted by hand as (source, color written). An error names a value that is not a + /// color such as `#ff8800`, two keys that name one color, or more than 256 entries. + fn shifts(&self) -> std::result::Result, String> { + // One entry past the limit is enough for `colors` to refuse a longer map. + let (keys, values): (Vec, Vec) = self.shifted.iter().take(MAX_TABLE + 1).map(|(k, v)| (k.clone(), v.clone())).unzip(); + let sources = Self::colors(&keys, "shifted")?; + let to = Self::colors(&values, "shifted")?; + for (i, (s, k)) in sources.iter().zip(&keys).enumerate() { + if sources[..i].contains(s) { + return Err(format!("colorTable.shifted: `{k}` names a color another key names")); + } + } + Ok(sources.into_iter().zip(to).collect()) + } + /// `h` as RGB; `None` when it is not a color such as `#ff8800`. fn rgb(h: &str) -> Option<[u8; 3]> { vectorcraft_color::Color::from_hex(h).filter(|_| !super::hex_with_alpha(h)).map(|c| { @@ -487,13 +508,18 @@ impl WebSettings { { ColorTable::colors(list, what)?; } - // A deleted color is no longer locked, transparent or web-shifted. + // A deleted color is no longer locked, transparent, web-shifted or shifted. let deleted = ColorTable::colors(&table.deleted, "deleted")?; if !deleted.is_empty() { for list in [&mut table.locked, &mut table.transparent, &mut table.web_shift] { list.retain(|h| ColorTable::rgb(h).is_none_or(|c| !deleted.contains(&c))); } } + // Shifts are kept as `#rrggbb` in lowercase; a color shifted to itself is not shifted, and + // a color shifted by hand is not web-shifted. + let shifts: Vec = table.shifts()?.into_iter().filter(|(s, to)| s != to && !deleted.contains(s)).collect(); + table.web_shift.retain(|h| ColorTable::rgb(h).is_none_or(|c| !shifts.iter().any(|(s, _)| *s == c))); + table.shifted = shifts.into_iter().map(|(s, to)| (hex(s), hex(to))).collect(); Ok(self) } @@ -640,6 +666,8 @@ pub struct TableColor { pub transparent: bool, pub locked: bool, pub web_shifted: bool, + /// Shifted by hand (`colorTable.shifted`): written as `color` instead of `source`. + pub shifted: bool, } /// An optimised image file. @@ -759,6 +787,11 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 let locked = ColorTable::colors(&table.locked, "locked")?; let to_clear = ColorTable::colors(&table.transparent, "transparent")?; let shift = ColorTable::colors(&table.web_shift, "webShift")?; + let by_hand = table.shifts()?; + let shifted_to = |src: &[u8; 3]| by_hand.iter().find(|(s, _)| s == src).map(|(_, to)| *to); + // A color shifted by hand is kept when the colors are reduced, as a locked one is, and takes + // one of the slots kept for them before the locked colors do. + let kept: Vec<[u8; 3]> = by_hand.iter().map(|(s, _)| *s).chain(locked.iter().copied()).collect(); let o = PaletteOptions { colors: s.colors, reduction: s.reduction, @@ -767,7 +800,7 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 transparency: s.transparency, matte, }; - let mut ix = reduced(rgba, w, h, s, &o, &locked)?; + let mut ix = reduced(rgba, w, h, s, &o, &kept)?; // Map to transparent works on the colours the reduction made. let before = ix.palette.clone(); let clear = ix.transparent.map(usize::from); @@ -781,11 +814,11 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 *slot = *c; } } - // Web snap, then the colours shifted by hand (locked colours stay as they are). + // Web shift and web snap (locked colors and colors shifted by hand stay as they are). let clear = ix.transparent.map(usize::from); for (i, c) in ix.palette.iter_mut().enumerate() { let src = sources.get(i).copied().unwrap_or(*c); - if Some(i) == clear || locked.contains(&src) { + if Some(i) == clear || shifted_to(&src).is_some() || locked.contains(&src) { continue; } if shift.contains(&src) { @@ -794,8 +827,19 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 *c = snapped; } } + // Lossy compares the pixels with the colors written for them, and moves no pixel into or out of + // a color shifted by hand. if s.format == WebFormat::Gif { - web::lossy(&mut ix, rgba, s.lossy); + let fixed: Vec = sources.iter().enumerate().filter(|(_, c)| shifted_to(c).is_some()).filter_map(|(i, _)| u8::try_from(i).ok()).collect(); + web::lossy(&mut ix, rgba, s.lossy, &fixed); + } + // The colors shifted by hand. + for (i, c) in ix.palette.iter_mut().enumerate() { + if Some(i) != clear + && let Some(to) = sources.get(i).and_then(shifted_to) + { + *c = to; + } } let order = web::sort(&mut ix, table.sort); let sources: Vec<[u8; 3]> = order.iter().map(|&i| sources.get(i).copied().unwrap_or_default()).collect(); @@ -804,12 +848,17 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 .iter() .zip(&sources) .enumerate() - .map(|(i, (c, src))| TableColor { - color: *c, - source: *src, - transparent: ix.transparent == u8::try_from(i).ok(), - locked: locked.contains(src), - web_shifted: shift.contains(src), + .map(|(i, (c, src))| { + let transparent = ix.transparent == u8::try_from(i).ok(); + let shifted = !transparent && shifted_to(src).is_some(); + TableColor { + color: *c, + source: *src, + transparent, + locked: locked.contains(src) || shifted, + web_shifted: shift.contains(src) && !shifted, + shifted, + } }) .collect(); Ok(PaletteImage { ix, colors, mapped }) @@ -818,7 +867,8 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 /// The pixels reduced to the palette `s` gives: the reduction's own (`locked` kept), or the /// color table's fixed one, without the deleted colors. The pixels of a deleted color take the /// nearest color left, with `o`'s dither. A deletion has to leave a color that is not mapped to -/// transparent. +/// transparent. A fixed palette keeps its colors mapped to transparent, which take one slot of +/// `colors` together, and its first opaque colors that fit in the rest. fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, locked: &[[u8; 3]]) -> std::result::Result { let table = &s.color_table; let deleted = ColorTable::colors(&table.deleted, "deleted")?; @@ -847,11 +897,70 @@ fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, loc left.push(c); } } - left.truncate(usize::from(s.colors.clamp(2, 256)) - usize::from(has_clear)); if left.is_empty() || (removed && !opaque_left(&left)) { return Err(KEEP_ONE.into()); } - Ok(quantize::quantize_to(rgba, w, h, o, &left)) + // The colors mapped to transparent all become the one transparent entry, so together they take + // one slot, and the opaque colors fill the rest in palette order. When no pixel takes one of + // them and no pixel is transparent, that slot goes to the next opaque color instead. + let kept = fixed_palette(&left, &to_clear, s.colors, has_clear, true); + let mut ix = quantize::quantize_to(rgba, w, h, o, &kept); + clear_dropped(&mut ix, rgba, o, &kept, &left, &to_clear); + if !has_clear && !ix.palette.iter().any(|c| to_clear.contains(c)) && left.iter().any(|c| to_clear.contains(c)) { + return Ok(quantize::quantize_to(rgba, w, h, o, &fixed_palette(&left, &to_clear, s.colors, has_clear, false))); + } + Ok(ix) +} + +/// The entries of the fixed palette `left` that fit in `colors`. With `clear`, the colors in +/// `to_clear` are kept and take one slot together; without it they are left out. The list holds +/// at most 256 entries, less one when `has_clear` (the transparent pixels' entry). +fn fixed_palette(left: &[[u8; 3]], to_clear: &[[u8; 3]], colors: u16, has_clear: bool, clear: bool) -> Vec<[u8; 3]> { + let any_clear = clear && left.iter().any(|c| to_clear.contains(c)); + let total = 256 - usize::from(has_clear); + let mut room = (usize::from(colors.clamp(2, 256)) - usize::from(has_clear || any_clear)).min(total - usize::from(any_clear)); + let opaque = left.iter().filter(|c| !to_clear.contains(c)).count().min(room); + let mut clear_room = if clear { total - opaque } else { 0 }; + left.iter() + .copied() + .filter(|c| { + let slots = if to_clear.contains(c) { &mut clear_room } else { &mut room }; + let keep = *slots > 0; + *slots = slots.saturating_sub(1); + keep + }) + .collect() +} + +/// Makes transparent the pixels of `ix` whose nearest color is a color of `left` mapped to +/// transparent (`to_clear`) that does not fit in the fixed palette `kept`. Such a pixel takes the +/// transparent entry, or an entry mapped to transparent, which Map to Transparent clears later. +fn clear_dropped(ix: &mut Indexed, rgba: &[u8], o: &PaletteOptions, kept: &[[u8; 3]], left: &[[u8; 3]], to_clear: &[[u8; 3]]) { + let dropped: Vec<[u8; 3]> = left.iter().filter(|c| to_clear.contains(c) && !kept.contains(c)).copied().collect(); + if dropped.is_empty() { + return; + } + let all: Vec<[u8; 3]> = kept.iter().chain(&dropped).copied().collect(); + let near = quantize::nearest_entries(rgba, o, &all); + if !near.iter().any(|n| n.is_some_and(|n| n >= kept.len())) { + return; + } + let entry = match ix.transparent.or_else(|| ix.palette.iter().position(|c| to_clear.contains(c)).and_then(|i| u8::try_from(i).ok())) { + Some(i) => i, + None => { + // A kept color mapped to transparent that no pixel took; at most 255 entries are used then. + let (Some(c), Ok(i)) = (kept.iter().find(|c| to_clear.contains(c)), u8::try_from(ix.palette.len())) else { + return; + }; + ix.palette.push(*c); + i + } + }; + for (v, n) in ix.indices.iter_mut().zip(&near) { + if n.is_some_and(|n| n >= kept.len()) { + *v = entry; + } + } } /// An optimised image as straight RGBA → `(pixels, width, height)` (the dialog's preview). @@ -1116,7 +1225,7 @@ fn preview(s: &mut Session, p: &Value) -> Result { .map(|c| { json!({ "color": hex(c.color), "source": hex(c.source), "transparent": c.transparent, "locked": c.locked, - "webShifted": c.web_shifted, "webSafe": quantize::web_safe(c.color) == c.color, + "webShifted": c.web_shifted, "shifted": c.shifted, "webSafe": quantize::web_safe(c.color) == c.color, }) }) .collect(); diff --git a/crates/engine/src/cmd/xform.rs b/crates/engine/src/cmd/xform.rs index 0fc5340e2f..c592e552a4 100644 --- a/crates/engine/src/cmd/xform.rs +++ b/crates/engine/src/cmd/xform.rs @@ -30,7 +30,7 @@ pub fn specs() -> Vec { "Sample Color", [], None, - "{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it", + "{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default, and so does a sample without ids while the Live Paint Bucket is the active tool, `stop` included); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it", has_doc, sample_color ), diff --git a/crates/engine/src/cmd/xmlattrs.rs b/crates/engine/src/cmd/xmlattrs.rs deleted file mode 100644 index 6dd2578fae..0000000000 --- a/crates/engine/src/cmd/xmlattrs.rs +++ /dev/null @@ -1,55 +0,0 @@ -//! Attribute uniqueness checks missing from the pinned shared XML reader's strict mode. -//! -//! Temporary consumer guard: parsing remains in craft-xml. Move this invariant into the -//! shared strict reader and remove this second event pass when that dependency is updated. - -/// Check names before canonical/local-name rewriting can collapse distinct attributes. -/// The event reader and namespace scope use the same caller-supplied resource caps. -pub(super) fn validate(xml: &[u8], limits: craft_xml::Limits) -> Result<(), String> { - use std::collections::BTreeSet; - - let opts = craft_xml::Options { limits, doctype: craft_xml::Doctype::Reject, ..Default::default() }.strict(); - let mut events = opts.events(xml); - let mut bindings: Vec<(String, String)> = Vec::new(); - let mut scopes = Vec::new(); - while let Some(event) = events.next().map_err(|e| e.to_string())? { - match event { - craft_xml::Event::Start { attrs, .. } => { - scopes.push(bindings.len()); - let mut raw = BTreeSet::new(); - for (key, value) in &attrs { - if !raw.insert(key.as_str()) { - return Err(format!("duplicate attribute `{key}`")); - } - if let Some(prefix) = key.strip_prefix("xmlns:") { - if bindings.len() >= limits.max_attrs { - return Err("too many in-scope namespace declarations".into()); - } - bindings.push((prefix.to_string(), value.clone())); - } - } - let mut expanded = BTreeSet::new(); - for (key, _) in &attrs { - if key == "xmlns" || key.starts_with("xmlns:") { - continue; - } - // Default namespaces do not apply to attributes. Preserve undeclared - // prefixes for standalone SVG library fragments, as the importer did. - let name = match key.split_once(':') { - Some(("xml", local)) => ("http://www.w3.org/XML/1998/namespace", local), - Some((prefix, local)) => { - bindings.iter().rev().find(|(p, _)| p == prefix).map_or(("", key.as_str()), |(_, uri)| (uri.as_str(), local)) - } - None => ("", key.as_str()), - }; - if !expanded.insert(name) { - return Err(format!("duplicate expanded attribute `{key}`")); - } - } - } - craft_xml::Event::End { .. } => bindings.truncate(scopes.pop().unwrap_or(0)), - _ => {} - } - } - Ok(()) -} diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index ee594bae25..82e090a3ef 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -24,6 +24,11 @@ pub const ON_ACTIVE_ARTBOARD: [&str; 8] = [ /// `indices` instead. pub const FIT_ACTIVE_ARTBOARD: [&str; 2] = ["artboard.fitToArt", "artboard.fitToSelection"]; +/// The commands that the Rectangle, Rounded Rectangle, Ellipse, Polygon, Star and Line Segment +/// tools and their dialogs, and the Shaper tool for a shape it recognizes, run to draw a shape +/// ([`crate::Session::take_shape_drawn`]). +pub const DRAWS_SHAPE: [&str; 5] = ["shape.rectangle", "shape.ellipse", "shape.polygon", "shape.star", "shape.line"]; + /// `(command, param)` pairs the journal records only so a replay reproduces the original run /// (dates from the clock: `cmd::clock_date`; the artboards the app passes to the /// [`ON_ACTIVE_ARTBOARD`] and [`FIT_ACTIVE_ARTBOARD`] commands and to a batch; the artboards the diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index b824bebce2..c5ecee374e 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -48,7 +48,7 @@ pub struct AutomationRoots { write: Vec, } -#[derive(Debug)] +#[derive(Clone, Debug)] struct Root { /// The folder made absolute, links followed: what paths are compared with. resolved: PathBuf, @@ -128,6 +128,25 @@ impl AutomationRoots { } } + /// The roots that grant only what both `self` and `other` grant: for each kind, every root of + /// one that lies inside a root of the other. A kind left with none grants no access of its kind. + pub fn intersect(&self, other: &Self) -> Arc { + let both = |a: &[Root], b: &[Root]| { + let mut out: Vec = Vec::new(); + for r in a + .iter() + .filter(|r| b.iter().any(|o| inside(&r.resolved, &o.resolved))) + .chain(b.iter().filter(|o| a.iter().any(|r| inside(&o.resolved, &r.resolved)))) + { + if !out.iter().any(|o| o.resolved == r.resolved) { + out.push(r.clone()); + } + } + out + }; + Arc::new(Self { read: both(&self.read, &other.read), write: both(&self.write, &other.write) }) + } + /// The roots for people: `read A, B; write C` (`none` for a kind without any). pub fn describe(&self) -> String { let list = |roots: &[Root]| { @@ -223,6 +242,36 @@ impl ScopeHandle { let Self(scope, gate, exempt) = self; with_gate(gate, || with_gate_reads_exempt(exempt, || with_scope(scope, f))) } + + /// The roots in force in this scope, if any (as [`current`] gives them on its thread). + fn roots(&self) -> Option> { + match &self.0 { + Some(Scope::Confined(r)) => Some(r.clone()), + Some(Scope::Unconfined) => None, + None => PROCESS.get().cloned(), + } + } + + /// The captured scope narrowed to what the calling thread may reach as well: the roots of both + /// are in force ([`AutomationRoots::intersect`]), and without roots in either, none are. The + /// script gates of both are in force too, and reads are exempt from them only where both are. + pub fn within_current(self) -> Self { + let here = Self::capture(); + let gate = match (self.1.clone(), here.1.clone()) { + (None, None) => None, + (Some(g), None) | (None, Some(g)) => Some(g), + (Some(a), Some(b)) if Arc::ptr_eq(&a, &b) => Some(a), + (Some(a), Some(b)) => Some(Arc::new(a.followed_by(b))), + }; + let exempt = self.2 && here.2; + let scope = match (self.roots(), here.roots()) { + (None, None) => self.0, + (Some(r), None) | (None, Some(r)) => Some(Scope::Confined(r)), + (Some(a), Some(b)) if Arc::ptr_eq(&a, &b) => Some(Scope::Confined(a)), + (Some(a), Some(b)) => Some(Scope::Confined(a.intersect(&b))), + }; + Self(scope, gate, exempt) + } } /// What a command a running script runs (`vc.run`) may read and write: the places the script's @@ -235,10 +284,26 @@ pub(crate) struct ScriptGate { pub(crate) write: ScriptScope, /// The paths of the open documents' files, as the documents hold them. pub(crate) documents: Vec, + /// Another gate a path must pass as well ([`ScopeHandle::within_current`]). + pub(crate) also: Option>, } impl ScriptGate { + /// This gate with `next` at the end of its chain of `also` gates, so a path must pass every + /// gate already in the chain as well as `next`. + fn followed_by(&self, next: Arc) -> ScriptGate { + let also = match &self.also { + None => next, + Some(also) if Arc::ptr_eq(also, &next) => next, + Some(also) => Arc::new(also.followed_by(next)), + }; + ScriptGate { also: Some(also), ..self.clone() } + } + fn check(&self, path: &str, access: Access) -> Result<(), String> { + if let Some(also) = &self.also { + also.check(path, access)?; + } let real = if ScriptScope::refused_by_name(Path::new(path)) { None } else { resolve(path).ok() }; let allowed = real.is_some_and(|real| { let scoped = match access { @@ -824,6 +889,74 @@ mod tests { p.to_string_lossy().into_owned() } + /// The roots both grant: the deeper of two nested roots, nothing for roots apart, and a kind + /// only one grants is not granted. + #[test] + fn intersected_roots_grant_what_both_grant() { + let (base, roots) = folders("intersect"); + let narrow = AutomationRoots::new(&[&base.join("in/sub"), &base.join("in2")], &[]).unwrap().unwrap(); + let both = roots.intersect(&narrow); + assert_eq!(both.check(&s(base.join("in/sub/x.svg")), Access::Read), Ok(())); + assert!(both.check(&s(base.join("in/a.svg")), Access::Read).is_err(), "only the narrow root grants it"); + assert!(both.check(&s(base.join("in2")), Access::Read).is_err(), "only the narrow roots grant it"); + assert!(both.check(&s(base.join("out/x.svg")), Access::Write).is_err(), "only the first grants writes"); + assert_eq!(both.describe(), narrow.intersect(&roots).describe(), "either order"); + let unconfined = ScopeHandle(Some(Scope::Unconfined), None, false); + let within = |saved: ScopeHandle, here: Option<&Arc>| { + confine(here, || saved.within_current()).run(|| current().map(|r| r.describe())) + }; + assert_eq!(within(unconfined.clone(), Some(&narrow)), Some(narrow.describe()), "a confined caller keeps its roots"); + assert_eq!(within(ScopeHandle(Some(Scope::Confined(roots.clone())), None, false), None), Some(roots.describe()), "the saved roots stay"); + assert_eq!(within(ScopeHandle(Some(Scope::Confined(roots.clone())), None, false), Some(&narrow)), Some(both.describe())); + assert!(unconfined.run(|| current().is_none())); + let _ = std::fs::remove_dir_all(base); + } + + /// A scope narrowed to the calling thread keeps the script gate of both: a script command that + /// carries on work saved without a gate reads only what its gate allows, and with a gate saved + /// too, only what both allow; reads are exempt only where both scopes exempt them. + #[test] + fn a_narrowed_scope_keeps_the_script_gates_of_both() { + let (base, _) = folders("narrowed-gate"); + let gate = + |dir: &str| ScriptGate { read: ScriptScope::of_folder(&base.join(dir)), write: ScriptScope::default(), documents: vec![], also: None }; + let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg"))); + let reads = |saved: ScopeHandle, gate_here: Option| { + let narrowed = match gate_here { + Some(g) => with_script_gate(g, || saved.within_current()), + None => saved.within_current(), + }; + narrowed.run(|| (check_read(&inside).is_ok(), check_read(&other).is_ok())) + }; + let plain = ScopeHandle(None, None, false); + assert_eq!(reads(plain.clone(), Some(gate("in"))), (true, false), "the confirming command's gate"); + assert_eq!(reads(ScopeHandle(None, Some(Arc::new(gate("in"))), false), None), (true, false), "the saved gate"); + assert_eq!(reads(ScopeHandle(None, Some(Arc::new(gate("in"))), false), Some(gate("outside"))), (false, false), "both gates"); + assert_eq!(reads(ScopeHandle(None, None, true), Some(gate("in"))), (true, false), "exempt only where both are"); + assert_eq!(reads(plain, None), (true, true)); + let _ = std::fs::remove_dir_all(base); + } + + /// A scope narrowed again and again keeps every gate it was narrowed by: a gate an earlier + /// narrowing joined to the chain still refuses what it refused before. + #[test] + fn a_scope_narrowed_several_times_keeps_every_gate() { + let (base, _) = folders("narrowed-thrice"); + let gate = |dir: &Path| ScriptGate { read: ScriptScope::of_folder(dir), write: ScriptScope::default(), documents: vec![], also: None }; + let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg"))); + let narrow = |saved: ScopeHandle, g: ScriptGate| with_script_gate(g, || saved.within_current()); + let reads = |h: &ScopeHandle| h.clone().run(|| (check_read(&inside).is_ok(), check_read(&other).is_ok())); + let first = narrow(ScopeHandle(None, None, false), gate(&base)); + assert_eq!(reads(&first), (true, true)); + let second = narrow(first, gate(&base.join("in"))); + assert_eq!(reads(&second), (true, false), "the second gate refuses the outside file"); + let third = narrow(second, gate(&base)); + assert_eq!(reads(&third), (true, false), "the second gate is kept after a third narrowing"); + let fourth = narrow(third, gate(&base)); + assert_eq!(reads(&fourth), (true, false), "and after a fourth"); + let _ = std::fs::remove_dir_all(base); + } + #[test] fn network_paths_are_told_by_name() { for p in [r"\\server\share\x.svg", "//server/share/x.svg", r"\\?\UNC\server\share\x.svg", r"\\?\unc\server\share"] { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index de780f406c..8cc6b4084e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -29,6 +29,7 @@ use vectorcraft_tools::{PaintDefaults, Tool}; pub use cmd::clipboard::{Clipboard, SourceLayer}; pub use cmd::create::constrain_click; pub use cmd::distortcmds::{perspective_click, width_point_pair}; +pub use cmd::flare::flare_settings; pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject}; pub use cmd::params::{check_keys, check_params}; pub use cmd::pathops::auto_simplify_level; @@ -109,6 +110,9 @@ pub struct Session { /// Set while saved steps play ([`Session::replay`]): [`Session::execute`] then takes keys the /// command's params description doesn't name instead of refusing them. replaying: bool, + /// Set when a command that draws a shape was journaled outside saved steps + /// ([`Session::take_shape_drawn`]). + shape_drawn: bool, /// Set when the active tool panicked (see [`guard`]); reported by the next tool event. tool_panic: Option, /// How many times switching or closing documents, or replacing the active one, has started the @@ -198,7 +202,8 @@ pub struct Session { /// `plugin.install` takes `grant` and `allowHeavy` from any request /// ([`Session::allow_plugin_grants_from_requests`]). plugin_grants_from_requests: bool, - /// URLs recently given in the Attributes panel (`attributes.set {url}`), newest first; not saved. + /// URLs recently given in the Attributes panel (`attributes.set {url}`), newest first, at most + /// [`cmd::RECENT_URLS`]; not saved. pub recent_urls: Vec, /// The saved tracing presets' revision and latest changes ([`Session::trace_presets_revision`]). pub(crate) trace_preset_changes: cmd::TracePresetChanges, @@ -360,6 +365,8 @@ pub struct Session { /// Set while [`Session::tool_typed_text`] passes keyboard input to the active tool /// ([`vectorcraft_tools::ToolContext::typed_from_keyboard`]). keyboard_text: bool, + /// The messages `app.toast` and [`Session::toast`] queued for the app to show; not saved. + pub(crate) toasts: cmd::toast::Queue, } impl Default for Session { @@ -407,7 +414,7 @@ mod session; pub(crate) use command_sets::SELECTS_GIVEN_IDS; #[cfg(test)] use command_sets::given_ids; -pub use command_sets::{FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_tool_edit}; +pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_tool_edit}; pub use doc_state::{DocState, OpenRows, RecalledSelection}; pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY}; #[cfg(test)] @@ -415,7 +422,7 @@ use history::history_budget_for; pub use history::{History, HistoryEntry, NamedStep, default_history_budget}; pub(crate) use interaction::PreviewCopies; pub use interaction::{Interaction, LastTransform, UndoGroup, UndoScope}; -pub use prefs::{DrawMode, PluginBudget, Prefs}; +pub use prefs::{DrawMode, KEY_HOLD_DELAY, KEY_HOLD_DELAY_RANGE, PluginBudget, Prefs}; pub use sanity::TOO_DEEP; pub(crate) use sanity::{deselect_hidden, is_guide_path}; #[cfg(test)] diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 6d044eace3..0bf8203463 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -57,6 +57,9 @@ pub struct Prefs { pub interpolate_control_points: bool, pub use_precise_cursors: bool, pub show_tool_tips: bool, + /// General › Show Tool Cards: with tool tips on, a tool button's tool tip is a card with what the + /// tool does and its keys, for tools that have a description. + pub show_tool_cards: bool, /// Other Script… warns before it runs a chosen script. pub show_external_script_warning: bool, pub anti_aliased_artwork: bool, @@ -97,6 +100,13 @@ pub struct Prefs { /// A single-key tool shortcut held down chooses its tool until the key is let go, and then the /// tool active before comes back; a quick press chooses the tool for good. pub hold_tool_keys: bool, + /// Hold shortcuts act (Edit › Keyboard Shortcuts › Hold Shortcuts, off by default): a key with a + /// hold shortcut runs it when held for [`Self::key_hold_delay`], and its own shortcut when let go + /// sooner. Off, every key runs on its press and the dialog shows no Hold column. + pub hold_shortcuts: bool, + /// Seconds a key with a hold shortcut must stay down before the hold shortcut runs (Hold + /// Shortcut Delay, 0.2 to 1.0). VectorCraft's own default, 0.35. + pub key_hold_delay: f64, /// With View › Show Bounding Box on, the bounding box stays visible while a drag moves the /// selection, and the shape tools that show it draw it around the shape being drawn. Off (the /// default), it hides during a move and while a shape is drawn, except that a Selection tool @@ -393,6 +403,11 @@ pub struct Prefs { /// selected, the panel and the Properties panel's Transform section measure and transform it /// from its symbol's registration point instead of the reference point. pub use_registration_point_for_symbol: bool, + /// The Transform panel menu's Show on Shape Creation: drawing a shape with the Rectangle, + /// Rounded Rectangle, Ellipse, Polygon, Star or Line Segment tool (a drag or OK in the tool's + /// dialog, also on the active perspective plane), a shape the Shaper tool recognizes, or running + /// one of [`crate::DRAWS_SHAPE`], shows the Transform panel. + pub show_on_shape_creation: bool, /// The tools' persistent options by store (a tool id, or a store a family shares: `liquify` /// holds the Liquify tools' Global Brush Dimensions), see [`vectorcraft_tools::settings`]: /// kept across tool switches and saved with the preferences. Not a Preferences dialog field: @@ -420,6 +435,21 @@ pub struct Prefs { pub import_matches: Vec, } +/// The default Hold Shortcut Delay, in seconds (VectorCraft's own value). +pub const KEY_HOLD_DELAY: f64 = 0.35; +/// The range of the Hold Shortcut Delay, in seconds. +pub const KEY_HOLD_DELAY_RANGE: (f64, f64) = (0.2, 1.0); + +impl Prefs { + /// The Hold Shortcut Delay in seconds, inside its range. A restored settings file is not + /// checked against the range, so a value outside it is brought inside, and one that is not a + /// number gives the default. + pub fn key_hold_delay(&self) -> f64 { + let (min, max) = KEY_HOLD_DELAY_RANGE; + if self.key_hold_delay.is_finite() { self.key_hold_delay.clamp(min, max) } else { KEY_HOLD_DELAY } + } +} + impl Default for Prefs { fn default() -> Self { let s = |v: &str| v.to_string(); @@ -431,6 +461,7 @@ impl Default for Prefs { interpolate_control_points: false, use_precise_cursors: false, show_tool_tips: true, + show_tool_cards: false, show_external_script_warning: true, anti_aliased_artwork: true, select_same_tint_percent: false, @@ -451,6 +482,8 @@ impl Default for Prefs { scrub_numeric_fields: true, trackpad_rotate_view: true, hold_tool_keys: true, + hold_shortcuts: false, + key_hold_delay: KEY_HOLD_DELAY, bounding_box_while_moving_and_drawing: false, paste_offset: 10.0, selection_tolerance: 3.0, @@ -597,6 +630,7 @@ impl Default for Prefs { single_corner_radius: true, transform_panel_patterns: "default".to_string(), use_registration_point_for_symbol: false, + show_on_shape_creation: false, tool_settings: Default::default(), perspective_presets: vec![], blend_options: None, diff --git a/crates/engine/src/sanity.rs b/crates/engine/src/sanity.rs index 4737246c9d..33738597b6 100644 --- a/crates/engine/src/sanity.rs +++ b/crates/engine/src/sanity.rs @@ -49,7 +49,8 @@ pub(crate) fn doc_sane(d: &Document, sel: &Selection) -> bool { && objects_in_range(d, &sel.objects) } -fn rect_in_range(r: vectorcraft_geom::Rect) -> bool { +/// Is every edge of `r` finite and within [`MAX_COORD`] of the origin? +pub(crate) fn rect_in_range(r: vectorcraft_geom::Rect) -> bool { [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD) } diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 6eecfeabf8..c0694bbd81 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -457,7 +457,7 @@ impl Disk { /// The gate for a command the script runs: the places it reads and writes now, and the files of /// the open documents, `documents`. pub(crate) fn gate(&self, documents: Vec) -> crate::file_access::ScriptGate { - crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents } + crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, also: None } } /// The files written since this was last asked, to name in the report. diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0dd9a46b6b..d811da6e2e 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1559,12 +1559,14 @@ fn kind_id(kind: &RunErrorKind) -> &'static str { } } -/// `message`, with what to do about a failure that comes from a script written for another program. -fn explained(kind: &RunErrorKind, message: &str) -> String { +/// `e`'s message, with what to do about a failure that comes from a script written for another +/// program. A message the script supplied itself ([`RunError::authored`]) is given as it is. +fn explained(e: &RunError) -> String { const HOST_OBJECTS: &[&str] = &["app", "Window", "BridgeTalk", "activeDocument", "documents"]; + let message = &e.message; let names_host_object = message.strip_prefix("ReferenceError: ").is_some_and(|m| HOST_OBJECTS.iter().any(|o| m.split_whitespace().next() == Some(o))); - if *kind == RunErrorKind::Thrown && names_host_object { + if e.kind == RunErrorKind::Thrown && !e.authored && names_host_object { format!("{message} (scripts here use the `vc` object; objects other applications give their scripts are not available)") } else { message.to_string() @@ -1582,7 +1584,7 @@ fn preprocessor_error(f: include::Failure) -> (RunError, Option>) { include::FailKind::Limit => (RunErrorKind::Limit(LimitKind::Host), f.message), }; let file = (f.index > 0).then_some(f.file); - (RunError { kind, message, line: f.line, column: f.column }, file) + (RunError { kind, message, line: f.line, column: f.column, authored: false }, file) } /// `e`, the error `realm` raised in the run of `host`, at the line and column of the file it is in, @@ -1591,20 +1593,20 @@ fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option { let (e, index, file) = map(&host.script_map.borrow()); @@ -1777,6 +1779,15 @@ impl Session { self.script_report.as_ref().filter(|r| r["ok"] == false).map(failure_text) } + /// [`Self::script_failure_text`] split around the message when that message is text the script + /// supplied itself (`messageOrigin` `script`): the text before it, the message and the text after + /// it. `None` when the last run did not fail, or failed with one of the app's own errors. + pub fn script_authored_failure(&self) -> Option<(String, &str, String)> { + let r = self.script_report.as_ref().filter(|r| r["ok"] == false && r["messageOrigin"] == "script")?; + let (before, after) = failure_frame(r); + Some((before, r["message"].as_str().unwrap_or_default(), after)) + } + /// Has the running script used up its growth allowance, so a person must answer? A run asked /// to stop no longer waits: the next [`Session::script_pump`] ends it. pub fn script_waiting(&self) -> bool { @@ -1873,7 +1884,7 @@ impl Session { }; drop(key); let kind = LimitKind::Interrupted; - let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0 }; + let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0, authored: false }; let _ = self.script_failed(job, &e); true } @@ -2120,14 +2131,14 @@ impl Session { // A stop while a dialog waits ends the run there; the interpreter cannot go on from the call. if job.realm.waits() { let kind = LimitKind::Interrupted; - let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0 }; + let e = RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0, authored: false }; return Some(self.script_failed(job, &e)); } job.host.calls_this_slice.set(0); let outcome = run_slice(self, &mut job); match outcome { Err(panic) => { - let e = RunError { kind: RunErrorKind::Internal, message: panic, line: 0, column: 0 }; + let e = RunError { kind: RunErrorKind::Internal, message: panic, line: 0, column: 0, authored: false }; Some(self.script_failed(job, &e)) } Ok(Err(e)) => Some(self.script_failed(job, &e)), @@ -2144,7 +2155,7 @@ impl Session { } else { format!("`answers` has {n} answers the script did not use") }; - Some(self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0 })) + Some(self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0, authored: false })) } Ok(Ok(Progress::Done(_))) => { let r = self.script_commit(job); @@ -2179,7 +2190,7 @@ impl Session { let unwritten = job.host.flush_files(); if !unwritten.is_empty() { let message = format!("{UNWRITTEN_FILES}: {}", unwritten.join(", ")); - let e = RunError { kind: RunErrorKind::Thrown, message, line: 0, column: 0 }; + let e = RunError { kind: RunErrorKind::Thrown, message, line: 0, column: 0, authored: false }; return self.script_failed(job, &e); } // The working copy goes into the session; `job.world` holds the state before the run. @@ -2197,7 +2208,7 @@ impl Session { if changed && (!crate::sanity::doc_sane(&st.doc, &st.selection) || st.doc.too_deep(None)) { job.world.docs = start; job.world.swap(self); - let e = RunError { kind: RunErrorKind::Internal, message: INVALID_RESULT.to_string(), line: 0, column: 0 }; + let e = RunError { kind: RunErrorKind::Internal, message: INVALID_RESULT.to_string(), line: 0, column: 0, authored: false }; return self.script_failed(job, &e); } } @@ -2302,7 +2313,8 @@ fn failure_report(name: &str, e: &RunError, file: Option<&str>, host: &Host, fue let mut report = json!({ "ok": false, "kind": kind_id(&e.kind), - "message": explained(&e.kind, &e.message), + "message": explained(e), + "messageOrigin": if e.authored { "script" } else { "built-in" }, "name": name, "line": e.line, "column": e.column, @@ -2395,6 +2407,12 @@ fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console:: /// The text of a failed run's error. fn failure_text(report: &Value) -> String { + let (before, after) = failure_frame(report); + format!("{before}{}{after}", report["message"].as_str().unwrap_or_default()) +} + +/// The text of a failed run's error before its message and after it. +fn failure_frame(report: &Value) -> (String, String) { let s = |k: &str| report[k].as_str().unwrap_or_default(); let (line, column) = (report["line"].as_u64().unwrap_or(0), report["column"].as_u64().unwrap_or(0)); let at = match report["file"].as_str() { @@ -2409,7 +2427,7 @@ fn failure_text(report: &Value) -> String { } else { String::new() }; - format!("{}{at}: {} ({}){kept}", s("name"), s("message"), s("kind")) + (format!("{}{at}: ", s("name")), format!(" ({}){kept}", s("kind"))) } /// A run's slice: the working copy in, the real session lent to the host functions, one measured diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index d6af60fee1..e48a8f6f38 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -1,4 +1,4 @@ -use super::command_sets::{JOURNALED_READS, SELECTS_GIVEN_IDS, TAKES_GUIDE_IDS, given_ids, strip_replay_only, waits_for_tool_edit}; +use super::command_sets::{DRAWS_SHAPE, JOURNALED_READS, SELECTS_GIVEN_IDS, TAKES_GUIDE_IDS, given_ids, strip_replay_only, waits_for_tool_edit}; use super::doc_state::DocState; use super::error::{EngineError, Result}; use super::history::NamedStep; diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 23dbe66e71..6ad8ed586e 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -68,6 +68,7 @@ impl Session { preview_memo: Default::default(), depth: 0, replaying: false, + shape_drawn: false, tool_panic: None, tool_resets: 0, tool_set_since_reset: false, @@ -149,6 +150,7 @@ impl Session { global_edit_options: Default::default(), select_similar: crate::cmd::SIMILAR[0].0, keyboard_text: false, + toasts: Default::default(), script_key: None, script_engines: crate::script::EnginesKey::new(), script_stop: vectorcraft_js::Interrupt::new(), @@ -204,8 +206,7 @@ impl Session { let _ = self.finish_tool_edit_later(); // The switch goes on whatever the lent tool's last actions did, as for the deactivation. let _ = self.give_back_tool(view); - let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx)); - let _ = self.apply_actions(acts); + let _ = self.deactivate_tool(view); // A batch leaves its interaction open in the document it leaves, to keep or roll back with // the rest of the batch; anything else in progress (a drag) is cancelled. if self.batch_stash.is_none() { diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index ce0c2998fe..ea697a0525 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -321,6 +321,9 @@ impl Session { if self.script_running() { return Err(EngineError::Busy); } + // While the Live Paint Bucket is active, paint previews change only the bucket's colors, so + // each preview starts from the colors the interaction began with. + let bucket = self.tool_id() == cmd::LIVE_PAINT_BUCKET; let (paint, restore_paint) = { let menu = self.menu.clone(); let st = self.doc_mut()?; @@ -334,8 +337,10 @@ impl Session { st.doc = it.doc.clone(); // A batch, or a preview that changed the new-art paints (a pattern rename), started from // the paints the interaction began with. - let restore_paint = - cmd == "command.batch" || it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch") || it.color_mode_paints.is_some(); + let restore_paint = bucket + || cmd == "command.batch" + || it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch") + || it.color_mode_paints.is_some(); let paint = it.paint.clone(); it.preview_paint = None; it.color_mode_paints = None; @@ -458,6 +463,7 @@ impl Session { st.last_perspective = perspective_again; } let (doc, journal, grouped) = (self.active().map(|d| d.uid), self.journal.len(), self.undo_group_docs()); + self.note_shape_drawn(&preview.0, &preview.1); self.journal.push(preview); self.journal_in_undo_groups(doc, &grouped, journal); if self.depth == 0 { @@ -477,10 +483,13 @@ impl Session { self.clear_deferred_overlay_cache(); self.decoded_images.empty(); self.pending_paint = None; + // While the Live Paint Bucket is active, a previewed color is the bucket's color, which the + // cancel puts back as well. + let bucket = self.tool_id() == cmd::LIVE_PAINT_BUCKET; if let Some(paint) = self .active() .and_then(|st| st.interaction.as_ref()) - .filter(|it| it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch") || it.color_mode_paints.is_some()) + .filter(|it| bucket || it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch") || it.color_mode_paints.is_some()) .map(|it| it.paint.clone()) { self.paint = paint; diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 3bc5c72378..046c480079 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -1,6 +1,6 @@ use super::{ - CommandSpec, EngineError, JOURNALED_READS, NodeId, Result, SELECTS_GIVEN_IDS, Selection, Session, TAKES_GUIDE_IDS, Value, cmd, find_command, - given_ids, guard, strip_replay_only, waits_for_tool_edit, + CommandSpec, DRAWS_SHAPE, EngineError, JOURNALED_READS, NodeId, Result, SELECTS_GIVEN_IDS, Selection, Session, TAKES_GUIDE_IDS, Value, cmd, + find_command, given_ids, guard, strip_replay_only, waits_for_tool_edit, }; /// A command's result `r` with the warnings of the previews that settling an interaction applied @@ -242,6 +242,7 @@ impl Session { let journaled = spec.journal || (self.depth == 0 && std::mem::take(&mut self.journal_query)); if journaled && self.depth == 0 && self.active().is_none_or(|d| d.interaction.is_none()) { let p = self.noted(params); + self.note_shape_drawn(id, &p); self.journal.push((id.to_string(), p)); } if self.depth == 0 { @@ -313,6 +314,32 @@ impl Session { self.replaying } + /// Note that journal entry `id` with `params` drew a shape ([`DRAWS_SHAPE`], also on the active + /// perspective plane as `perspective.draw` naming one, and as a step of `command.batch`), unless + /// saved steps are playing or a script runs. + pub(crate) fn note_shape_drawn(&mut self, id: &str, params: &Value) { + let shape = |id: &str| DRAWS_SHAPE.contains(&id); + let draws = |id: &str, params: Option<&Value>| { + shape(id) || (id == "perspective.draw" && params.and_then(|p| p.get("command")).and_then(Value::as_str).is_some_and(shape)) + }; + let in_batch = || { + params.get("commands").and_then(Value::as_array).is_some_and(|steps| { + steps.iter().any(|step| step.get("command").and_then(Value::as_str).is_some_and(|c| draws(c, step.get("params")))) + }) + }; + if !self.replaying && !self.script_in_run && (draws(id, Some(params)) || (id == "command.batch" && in_batch())) { + self.shape_drawn = true; + } + } + + /// Whether a shape was drawn since the last call: a drag of a shape tool that was committed, OK + /// in its dialog, or a [`DRAWS_SHAPE`] command (alone or as a batch step). Saved steps that play + /// ([`Session::replay`]) and a script's commands do not count. A frontend that shows the + /// Transform panel after a new shape asks this. + pub fn take_shape_drawn(&mut self) -> bool { + std::mem::take(&mut self.shape_drawn) + } + /// The journal from entry `start` on, as an action records it: without the params that only /// pin a replay to the original run ([`REPLAY_ONLY`]), so playing the action later acts now. pub fn journal_for_action(&self, start: usize) -> Vec<(String, Value)> { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 1f118b31a3..815a33eeae 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -44,6 +44,7 @@ mod constrain_new; mod constrain_tools; mod containers; mod css; +mod curvature_circle; mod cut; mod dashalign; mod dcs; @@ -154,6 +155,7 @@ mod printps; mod printtiling; mod proxyitems; mod puppetwarp; +mod quickpen; mod rasterfilters; mod rastersettings; mod recolor; @@ -199,6 +201,7 @@ mod swatchlib; mod symbol_nine_slice; mod symbolbounds; mod symboledit; +mod symbolism_options; mod symbollib; mod tangent_line; mod targeting; @@ -859,12 +862,13 @@ fn align_and_distribute_reject_bad_params_without_changing_state() { let h = "`horizontal` must be one of left, center, right"; let v = "`vertical` must be one of top, center, bottom"; let to = "`to` must be one of selection, artboard, key"; + let align_to = "`to` must be one of selection, artboard, key, auto"; for (cmd, p, msg) in [ ("object.align", json!({"horizontal": "middle"}), h), ("object.align", json!({"vertical": "centre"}), v), ("object.align", json!({"horizontal": true}), h), - ("object.align", json!({"horizontal": "left", "to": "page"}), to), - ("object.align", json!({"horizontal": "left", "to": 0}), to), + ("object.align", json!({"horizontal": "left", "to": "page"}), align_to), + ("object.align", json!({"horizontal": "left", "to": 0}), align_to), ("object.align", json!({"horizontal": "left", "bounds": false}), "`bounds` must be one of preview, geometric"), ("object.align", json!({"horizontal": "left", "vertical": "middle"}), v), ("object.distribute", json!({"horizontal": "middle"}), h), @@ -3393,6 +3397,149 @@ fn flare_rotation_turns_only_the_rays() { } } +/// A flare keeps its settings: `shape.editFlare` draws it again with the settings changed, in its +/// place and transformed as it has been since, as one undo step (none when nothing changes). A +/// flare with a changed part, a locked one and an expanded one are not edited. +#[test] +fn edit_flare_draws_a_transformed_flare_again_in_its_place_in_one_undo_step() { + let mut s = session(); + let p = json!({"cx": 200, "cy": 200, "diameter": 60, "rays": 9, "rings": 4, "x2": 400, "y2": 200, "seed": 3}); + let id = NodeId(s.execute("shape.flare", &p).unwrap()["id"].as_u64().unwrap()); + // Reflected twice, sheared and back, turned a quarter and moved: it stays a flare. + for (c, p) in [ + ("object.reflect", json!({"axis": "vertical"})), + ("object.reflect", json!({"axis": "horizontal"})), + ("object.shear", json!({"angle": 30})), + ("object.shear", json!({"angle": -30})), + ("object.rotate", json!({"angle": 90})), + ("object.move", json!({"dx": 50, "dy": 10})), + ] { + s.execute(c, &p).unwrap(); + } + let spec = |s: &Session| flare_settings(&s.doc().unwrap().doc, id).expect("still a flare"); + let part = |s: &Session, name: &str| { + let g = s.doc().unwrap().doc.node(id).unwrap(); + g.children().unwrap().iter().filter(|c| c.name.as_deref() == Some(name)).map(|c| c.geometric_bounds().unwrap()).collect::>() + }; + let (c, e) = (spec(&s).center().unwrap(), spec(&s).end().unwrap()); + // The quarter turn made the rings run vertically, 200 points from the center. + assert!((c.distance(e) - 200.0).abs() < 1e-6 && (c.x - e.x).abs() < 1e-6, "{c:?} {e:?}"); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("shape.editFlare", &json!({"diameter": 100, "rings": 6, "rays": 0})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + assert_eq!(s.doc().unwrap().selection.objects, vec![id]); + let centre = part(&s, "Center")[0]; + assert!(centre.center().distance(c) < 1e-6 && (centre.width() - 100.0).abs() < 1e-6, "{centre:?}"); + assert_eq!((part(&s, "Ring").len(), part(&s, "Rays").len()), (6, 0)); + assert!(spec(&s).end().unwrap().distance(e) < 1e-6, "the end point stays"); + // Each ring lies on the line from the center to the end point. + assert!(part(&s, "Ring").iter().all(|r| (r.center().x - c.x).abs() < 1e-6), "{:?}", part(&s, "Ring")); + // The center handle, where it is drawn now: the end point stays where it is. + s.execute("shape.editFlare", &json!({"ids": [id.0], "cx": c.x + 20.0, "cy": c.y})).unwrap(); + assert!(spec(&s).center().unwrap().distance(Point::new(c.x + 20.0, c.y)) < 1e-6); + assert!(spec(&s).end().unwrap().distance(e) < 1e-6); + assert!(part(&s, "Center")[0].center().distance(Point::new(c.x + 20.0, c.y)) < 1e-6); + // The end handle, then the path length and direction. + s.execute("shape.editFlare", &json!({"x2": c.x + 20.0, "y2": c.y + 80.0})).unwrap(); + assert!(spec(&s).end().unwrap().distance(Point::new(c.x + 20.0, c.y + 80.0)) < 1e-6); + // The path length and direction are where the flare is drawn now, though it was turned. + s.execute("shape.editFlare", &json!({"direction": 0, "pathLength": 50})).unwrap(); + assert!(spec(&s).end().unwrap().distance(Point::new(c.x + 70.0, c.y)) < 1e-6, "{:?}", spec(&s).end()); + s.execute("edit.undo", &json!({})).unwrap(); + // Nothing changes: no undo step. + let undo = s.doc().unwrap().history.undo.len(); + s.execute("shape.editFlare", &json!({"diameter": 100})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + // Bad values are refused. + for bad in [json!({"rings": 2.5}), json!({"diameter": "big"}), json!({"cx": 10}), json!({"diameter": 1e20})] { + assert!(s.execute("shape.editFlare", &bad).is_err(), "{bad}"); + } + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(spec(&s).end().unwrap().distance(e) < 1e-6, "undo puts the end point back"); + // A changed part: no longer a flare. + s.edit("Opacity", |d, _| { + let ring = d.node(id).unwrap().children().unwrap().iter().find(|c| c.name.as_deref() == Some("Center")).unwrap().id; + d.node_mut(ring).unwrap().opacity = 0.25; + Ok(()) + }) + .unwrap(); + assert_eq!(s.execute("shape.editFlare", &json!({"rings": 3})).unwrap_err().to_string(), "select a flare"); + s.execute("edit.undo", &json!({})).unwrap(); + // A locked flare. + s.execute("object.lock", &json!({})).unwrap(); + assert!(s.execute("shape.editFlare", &json!({"ids": [id.0], "rings": 3})).is_err()); + s.execute("object.unlockAll", &json!({})).unwrap(); + // Object › Expand: a plain group that is no longer a flare. + s.execute("object.expand", &json!({"object": true, "fill": false, "stroke": false})).unwrap(); + assert!(s.doc().unwrap().doc.node(id).unwrap().extras().flare.is_none()); + assert!(s.execute("shape.editFlare", &json!({"rings": 3})).is_err()); +} + +/// `shape.flare` reads whole-number counts written as floats, and refuses fractions. +#[test] +fn flare_counts_are_whole_numbers() { + let mut s = session(); + let id = NodeId(s.execute("shape.flare", &json!({"cx": 100, "cy": 100, "rays": 4.0, "rings": 2})).unwrap()["id"].as_u64().unwrap()); + let g = s.doc().unwrap().doc.node(id).unwrap(); + let rays = g.children().unwrap().iter().find(|c| c.name.as_deref() == Some("Rays")).unwrap(); + assert_eq!(rays.path_data().unwrap().subpaths.len(), 4); + assert!(s.execute("shape.flare", &json!({"cx": 100, "cy": 100, "rays": 2.5})).is_err()); +} + +/// `shape.editFlare` on a flare scaled far down: a `pathLength`, an end point or a center that, +/// taken back to where the flare was drawn, is not a finite number is an error, and the flare keeps +/// its settings. +#[test] +fn edit_flare_end_points_that_are_not_finite_are_errors() { + let mut s = session(); + let id = NodeId(s.execute("shape.flare", &json!({"cx": 100, "cy": 100, "rings": 2})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.scale", &json!({"sx": 1e-4, "sy": 1e-4})).unwrap(); + let before = flare_settings(&s.doc().unwrap().doc, id).expect("a flare"); + for (p, key) in [ + (json!({"pathLength": 1e305}), "x2"), + (json!({"x2": 1e305, "y2": 0}), "x2"), + (json!({"x2": 0, "y2": -1e305}), "y2"), + (json!({"cx": 1e305, "cy": 0}), "cx"), + ] { + let err = s.execute("shape.editFlare", &p).unwrap_err().to_string(); + assert!(err.ends_with(&format!("{key} must be a finite coordinate")), "{p}: {err}"); + assert_eq!(flare_settings(&s.doc().unwrap().doc, id).expect("still a flare"), before, "{p}"); + } +} + +/// A flare drawn again keeps its parts' pixel-aligned property, whatever the document's Align New +/// Objects to Pixel Grid is now, and a pixel-aligned flare that was moved is still a flare. +#[test] +fn edit_flare_keeps_its_parts_pixel_alignment() { + let mut s = session(); + let aligned = |s: &Session, id: NodeId| -> Vec { + s.doc().unwrap().doc.node(id).unwrap().children().unwrap().iter().map(|c| c.extras().pixel_aligned).collect() + }; + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap(); + let on = NodeId(s.execute("shape.flare", &json!({"cx": 100.3, "cy": 200.6, "rings": 2})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.move", &json!({"dx": 10.25, "dy": 3.5})).unwrap(); + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": false})).unwrap(); + let part = |s: &Session, id: NodeId, name: &str| -> NodeId { + s.doc().unwrap().doc.node(id).unwrap().children().unwrap().iter().find(|c| c.name.as_deref() == Some(name)).unwrap().id + }; + let centre = part(&s, on, "Center"); + s.execute("shape.editFlare", &json!({"rings": 4})).unwrap(); + assert!(aligned(&s, on).len() > 4 && aligned(&s, on).iter().all(|a| *a)); + // Each part drawn again keeps its id and its own property: without the rays, the center does + // not take theirs. + assert_eq!(part(&s, on, "Center"), centre); + s.execute("object.setPixelAligned", &json!({"ids": [centre.0], "on": false})).unwrap(); + s.execute("select.set", &json!({"ids": [on.0]})).unwrap(); + s.execute("shape.editFlare", &json!({"rays": 0})).unwrap(); + let node = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).unwrap().extras().pixel_aligned; + assert!(!node(&s, centre) && node(&s, part(&s, on, "Halo"))); + let off = NodeId(s.execute("shape.flare", &json!({"cx": 300.3, "cy": 200.6, "rings": 2})).unwrap()["id"].as_u64().unwrap()); + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap(); + s.execute("shape.editFlare", &json!({"rings": 4})).unwrap(); + assert!(aligned(&s, off).iter().all(|a| !*a)); +} + /// `shape.flare`'s `ringSeed` places the rings along the path anew and keeps their count and /// sizes and the other parts; the same `ringSeed` draws the same flare, neighboring ones differ, /// and a seed that is not a whole number of at least 0 (for `ringSeed`, below 2^53) is refused. @@ -3453,6 +3600,38 @@ fn flare_small_ring_seeds_spread_the_first_ring_along_the_path() { assert!(hi - lo > 250.0, "small seeds spread the first ring along the path: {positions:?}"); } +/// A flare drawn with a small `ringSeed` and then drawn again by `shape.editFlare` keeps its first +/// ring where `shape.flare` put it: the SplitMix64-initialized Xorshift64 stream's first value +/// along the path, for each seed. +#[test] +fn edit_flare_draws_the_first_ring_of_a_small_ring_seed_where_it_was() { + let first_t = |seed: u64| { + let mut z = seed.wrapping_add(0x9e37_79b9_7f4a_7c15); + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + let mut state = z ^ (z >> 31); + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + (state >> 11) as f64 / (1u64 << 53) as f64 + }; + let ring_x = |s: &Session, id: NodeId| { + let NodeKind::Group { children, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("flare is a group") }; + children.iter().find(|n| n.name.as_deref() == Some("Ring")).unwrap().geometric_bounds().unwrap().center().x + }; + let mut s = session(); + for seed in [0, 1, 2, 5, 11] { + let p = json!({"cx": 20, "cy": 30, "x2": 1020, "y2": 30, "rays": 0, "rings": 1, "ringSeed": seed}); + let id = NodeId(s.execute("shape.flare", &p).unwrap()["id"].as_u64().unwrap()); + let expected = 20.0 + 1000.0 * first_t(seed); + assert!((ring_x(&s, id) - expected).abs() < 1e-6, "seed {seed}: drawn at {}, expected {expected}", ring_x(&s, id)); + s.execute("shape.editFlare", &json!({"ids": [id.0], "opacity": 80})).unwrap(); + assert!((ring_x(&s, id) - expected).abs() < 1e-6, "seed {seed}: drawn again at {}, expected {expected}", ring_x(&s, id)); + s.execute("shape.editFlare", &json!({"ids": [id.0], "opacity": 40})).unwrap(); + assert!((ring_x(&s, id) - expected).abs() < 1e-6, "seed {seed}: a second edit keeps the ring"); + } +} + /// `shape.ellipse` without `anchors`, or with 4, draws the live ellipse it always drew. #[test] fn ellipse_with_four_anchors_is_the_live_ellipse() { @@ -4329,6 +4508,124 @@ fn object_mosaic_refuses_a_boolean_given_as_text() { assert_eq!((r["tiles"].clone(), images(&s)), (json!(2), 1)); } +/// The size of the mosaic a call makes from the 100 × 50 pt image selected in `s`, with its column and row counts. +fn mosaic_size(s: &mut Session, p: serde_json::Value) -> (f64, f64, serde_json::Value, serde_json::Value) { + let image = s.doc().unwrap().selection.objects.clone(); + let r = s.execute("object.createObjectMosaic", &p).unwrap(); + let b = s.doc().unwrap().doc.node(NodeId(r["id"].as_u64().unwrap())).unwrap().geometric_bounds().unwrap(); + s.execute("select.set", &json!({ "ids": image })).unwrap(); + ((b.width() * 1e6).round() / 1e6, (b.height() * 1e6).round() / 1e6, r["columns"].clone(), r["rows"].clone()) +} + +/// Resize Using Percentages reads the new width and height as percentages of the image's size; Constrain Ratio keeps +/// the image's proportions, the named side leading; Use Ratio makes the tiles square from the count on the +/// constrained side (columns by default), and the call answers the counts it used. +#[test] +fn object_mosaic_resizes_by_percentages_constrains_the_ratio_and_squares_the_tiles() { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 100.0, 50.0); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("object.rasterize", &json!({"ppi": 72})).unwrap(); + assert_eq!(mosaic_size(&mut s, json!({"columns": 2, "rows": 1})), (100.0, 50.0, json!(2), json!(1))); + assert_eq!(mosaic_size(&mut s, json!({"width": 50, "height": 200, "percentages": true})), (50.0, 100.0, json!(10), json!(10))); + // A side left out is 100% of the image's. + assert_eq!(mosaic_size(&mut s, json!({"width": 150, "percentages": true})).0, 150.0); + assert_eq!(mosaic_size(&mut s, json!({"width": 200, "height": 10, "constrain": "width"})), (200.0, 100.0, json!(10), json!(10))); + assert_eq!(mosaic_size(&mut s, json!({"width": 10, "height": 25, "constrain": "height"})), (50.0, 25.0, json!(10), json!(10))); + assert_eq!(mosaic_size(&mut s, json!({"width": 50, "constrain": "width", "percentages": true})), (50.0, 25.0, json!(10), json!(10))); + // Square tiles: 10 columns of 10 pt over 50 pt are 5 rows; 4 rows of 12.5 pt over 100 pt are 8 columns. + assert_eq!(mosaic_size(&mut s, json!({"columns": 10, "rows": 3, "useRatio": true})), (100.0, 50.0, json!(10), json!(5))); + assert_eq!(mosaic_size(&mut s, json!({"columns": 3, "rows": 4, "useRatio": true, "constrain": "height"})), (100.0, 50.0, json!(8), json!(4))); + // A side named for Use Ratio is kept without Constrain Ratio: the size stays as given. + assert_eq!(mosaic_size(&mut s, json!({"rows": 4, "height": 100, "useRatio": "height"})), (100.0, 100.0, json!(4), json!(4))); + // On a new size: 30 columns over 300 × 50 pt are 5 rows. + assert_eq!(mosaic_size(&mut s, json!({"columns": 30, "width": 300, "useRatio": true})), (300.0, 50.0, json!(30), json!(5))); + // The count is kept within 1..1000. + assert_eq!(mosaic_size(&mut s, json!({"columns": 1, "width": 1, "height": 5000, "useRatio": true})).3, json!(1000)); + assert_eq!(mosaic_size(&mut s, json!({"columns": 1, "width": 5000, "height": 1, "useRatio": true})).3, json!(1)); + // A size under 0.1 pt grows in proportion while Constrain Ratio keeps it. + let (w, h, ..) = mosaic_size(&mut s, json!({"width": 0.1, "constrain": "width"})); + assert!((w - 0.2).abs() < 1e-6 && (h - 0.1).abs() < 1e-6, "{w} × {h}"); + // A side Constrain Ratio works out above 1,000,000 pt shrinks to it, in proportion: a height of + // 1,000,000 pt over the 100 × 50 pt image would need a width of 2,000,000 pt. + assert_eq!(mosaic_size(&mut s, json!({"height": 1e6, "constrain": "height"})), (1e6, 5e5, json!(10), json!(10))); + // An image 20,000,000 times wider than it is tall has no such size: the call is refused. + s.execute("object.scale", &json!({"sx": 1, "sy": 1e-7})).unwrap(); + let r = s.execute("object.createObjectMosaic", &json!({"width": 1e6, "constrain": "width"})); + let msg = "the image's proportions leave no size with both sides between 0.1 and 1000000 pt"; + assert!(matches!(&r, Err(EngineError::BadParams { msg: m, .. }) if m == msg), "{r:?}"); +} + +/// Use Ratio squares the tiles as drawn: with 4 pt between columns, 10 columns of 10 pt cells draw 6 pt wide, so the +/// rows are 6 pt plus their own 4 pt apart (5 rows down 50 pt); on an image turned 90°, the tiles are measured along +/// its own axes. +#[test] +fn object_mosaic_use_ratio_takes_spacing_and_turned_images_into_account() { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 100.0, 50.0); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("object.rasterize", &json!({"ppi": 72})).unwrap(); + let image = s.doc().unwrap().selection.objects.clone(); + let counts = |s: &Session, p: serde_json::Value| crate::cmd::mosaic_counts(s, &p).unwrap(); + assert_eq!(counts(&s, json!({"columns": 10, "useRatio": true, "spacingX": 4, "spacingY": 4})), (10, 5)); + assert_eq!(counts(&s, json!({"columns": 10, "useRatio": true, "spacingX": 4})), (10, 8)); + assert_eq!(counts(&s, json!({"columns": 10, "rows": 7})), (10, 7), "without Use Ratio the counts are kept"); + let r = s.execute("object.createObjectMosaic", &json!({"columns": 10, "useRatio": true, "spacingX": 4})).unwrap(); + let g = s.doc().unwrap().doc.node(NodeId(r["id"].as_u64().unwrap())).unwrap().clone(); + let t = g.children().unwrap()[0].geometric_bounds().unwrap(); + assert!((t.width() - 6.0).abs() < 1e-6 && (t.height() - 6.25).abs() < 1e-6, "{t:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.set", &json!({ "ids": image })).unwrap(); + // Turned 90°, the image's 100 pt side runs down the page; 10 columns along it are still 5 rows across its 50. + s.execute("object.rotate", &json!({"angle": 90})).unwrap(); + assert_eq!(counts(&s, json!({"columns": 10, "useRatio": true})), (10, 5)); +} + +#[test] +fn object_mosaic_square_count_is_the_nearest_whole_count() { + use crate::cmd::menucmds::mosaic_square_count; + assert_eq!(mosaic_square_count(10, 100.0, 50.0, 0.0, 0.0), 5); + assert_eq!(mosaic_square_count(3, 100.0, 50.0, 0.0, 0.0), 2); + assert_eq!(mosaic_square_count(0, 100.0, 50.0, 0.0, 0.0), 1); + assert_eq!(mosaic_square_count(10, 0.0, 50.0, 0.0, 0.0), 1); + assert_eq!(mosaic_square_count(1000, 1.0, 1000.0, 0.0, 0.0), 1000); + // Spacing wider than a cell leaves 10% of it, on either side. + assert_eq!(mosaic_square_count(10, 100.0, 50.0, 50.0, 0.0), 50); + // 10 columns of 1 pt tiles (9 pt gaps) over 100 pt; rows 100 pt apart are capped too, so 10 rows draw 1 pt. + assert_eq!(mosaic_square_count(10, 100.0, 100.0, 9.0, 100.0), 10); + // 15 pt tiles over 50 pt: 3 rows draw 16.7 pt and 4 rows 12.5 pt, so 3. + assert_eq!(mosaic_square_count(1, 15.0, 50.0, 0.0, 0.0), 3); +} + +/// A Constrain Ratio side that is not "width" or "height", a new size of 0 or less, and Use Ratio or Resize Using +/// Percentages given as text are errors naming the key; no mosaic is made. +#[test] +fn object_mosaic_refuses_a_bad_ratio_side_size_or_switch() { + let mut s = session(); + rect(&mut s, 0.0, 0.0, 100.0, 50.0); + s.execute("object.rasterize", &json!({"ppi": 72})).unwrap(); + let undo = |s: &Session| s.doc().unwrap().history.undo.len(); + let before = undo(&s); + for (p, msg) in [ + (json!({"constrain": "both"}), "`constrain` must be one of \"width\", \"height\" or null"), + (json!({"constrain": 1}), "`constrain` must be one of \"width\", \"height\" or null"), + (json!({"width": 0}), "`width` must be between 0.1 and 1000000 (got 0)"), + (json!({"height": -5, "percentages": true}), "`height` must be between 0.1 and 1000000 (got -5)"), + (json!({"width": 2e6, "percentages": true}), "`width` must be between 0.1 and 1000000 (got 2000000)"), + // A side Constrain Ratio works out is not used, but a size given for it is still checked. + (json!({"width": 200, "height": 0, "constrain": "width"}), "`height` must be between 0.1 and 1000000 (got 0)"), + (json!({"useRatio": "true"}), "`useRatio` must be one of \"width\", \"height\", true, false or null"), + (json!({"useRatio": 1}), "`useRatio` must be one of \"width\", \"height\", true, false or null"), + (json!({"percentages": 1}), "`percentages` must be true or false"), + ] { + let r = s.execute("object.createObjectMosaic", &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg: m, .. }) if m == msg), "{p}: {r:?}"); + assert_eq!(undo(&s), before, "{p}"); + } + let r = s.execute("object.createObjectMosaic", &json!({"constrain": null, "useRatio": null, "percentages": null})).unwrap(); + assert_eq!(r["tiles"], json!(100)); +} + #[test] fn snap_to_pixel_rounds_drawing_and_moves() { let mut s = session(); diff --git a/crates/engine/src/tests/anchor_edit_work.rs b/crates/engine/src/tests/anchor_edit_work.rs index 5401bc0bf8..38bb94a6f3 100644 --- a/crates/engine/src/tests/anchor_edit_work.rs +++ b/crates/engine/src/tests/anchor_edit_work.rs @@ -176,3 +176,123 @@ fn a_handle_already_in_place_on_a_smooth_anchor_records_no_undo_step() { .unwrap(); assert_eq!(undo_steps(&s), 1); } + +/// `path.setHandle` with `link` makes a corner smooth: the other handle turns in line at its own +/// length, a retracted one is pulled out to the moved handle's length where a segment leaves the +/// anchor on its side and stays retracted at an open end. A handle already in place on a corner +/// still links; a request that changes nothing records no undo step; `link` that is not a boolean +/// or goes with `independent` is refused. +#[test] +fn a_linked_handle_makes_the_anchor_smooth() { + let (mut s, id) = long_path(100); + let p = anchor(&s, id, 5).p; + let corner = Anchor { p, h_in: p + Vec2::new(-6.0, 8.0), h_out: p + Vec2::new(3.0, 0.0), kind: AnchorKind::Corner }; + let path = Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().path_data_mut().unwrap(); + path.subpaths[0].anchors[5] = corner; + let link = |x: f64, y: f64, ai: usize| json!({"id": id.0, "anchor": ai, "which": "out", "x": x, "y": y, "link": true}); + let near = |a: Point, b: Point| a.distance(b) < 1e-9; + + // The out handle stays where it is; the corner becomes smooth, the in handle turned opposite it. + s.execute("path.setHandle", &link(corner.h_out.x, corner.h_out.y, 5)).unwrap(); + assert_eq!(undo_steps(&s), 1); + let a = anchor(&s, id, 5); + assert_eq!((a.kind, a.h_out), (AnchorKind::Smooth, corner.h_out)); + assert!(near(a.h_in, p + Vec2::new(-10.0, 0.0)), "{a:?}"); + // Moved: the in handle keeps its length of 10. + let to = p + Vec2::new(4.0, 3.0); + s.execute("path.setHandle", &link(to.x, to.y, 5)).unwrap(); + assert_eq!(undo_steps(&s), 2); + let a = anchor(&s, id, 5); + assert!(a.kind == AnchorKind::Smooth && a.h_out == to && near(a.h_in, p + Vec2::new(-8.0, -6.0)), "{a:?}"); + // The same request again changes nothing. + s.execute("path.setHandle", &link(to.x, to.y, 5)).unwrap(); + assert_eq!(undo_steps(&s), 2); + + // A retracted in handle on an inner anchor is pulled out; at the open start it stays retracted. + let q = anchor(&s, id, 7).p; + s.execute("path.setHandle", &link(q.x, q.y + 5.0, 7)).unwrap(); + let a = anchor(&s, id, 7); + assert!(a.kind == AnchorKind::Smooth && near(a.h_in, q + Vec2::new(0.0, -5.0)), "{a:?}"); + let q = anchor(&s, id, 0).p; + s.execute("path.setHandle", &link(q.x, q.y + 5.0, 0)).unwrap(); + let a = anchor(&s, id, 0); + assert!(a.kind == AnchorKind::Smooth && a.h_in == q && a.h_out == q + Vec2::new(0.0, 5.0), "{a:?}"); + + let before = s.doc().unwrap().doc.clone(); + let undo = undo_steps(&s); + for bad in [ + json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": "yes"}), + json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": 1}), + json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": true, "independent": true}), + json!({"id": id.0, "anchor": 5, "which": "out", "x": 0, "y": 0, "link": true, "independent": "no"}), + json!({"id": id.0, "anchor": 100, "which": "out", "x": 0, "y": 0, "link": true}), + json!({"id": id.0, "anchor": 7, "which": "out", "x": 1.7e308, "y": 1.7e308, "link": true}), + json!({"id": id.0, "anchor": 7, "which": "out", "x": 0, "y": -1e9, "link": true}), + ] { + assert!(s.execute("path.setHandle", &bad).is_err(), "{bad}"); + } + assert!(s.doc().unwrap().doc == before, "a refused request changed the document"); + assert_eq!(undo_steps(&s), undo); +} + +/// A linked `path.setHandle` request repeated as it was changes nothing and records no undo step, +/// even where turning the other handle again from its stored end rounds it differently, near the +/// origin and 3e6 pt from it. On a smooth anchor whose other handle is off line by 1e-8, linking +/// the handle where it is still turns the other one into line and records an undo step, at both +/// places. 3.9e6 pt from the origin, a 1.5e-9 pt handle at right angles and a handle 1e-9 pt off +/// line are turned too, and so is an other handle on the same side as the linked one. +#[test] +fn a_repeated_linked_handle_records_no_undo_step() { + let (mut s, id) = long_path(100); + let near = anchor(&s, id, 5).p; + for p in [near, Point::new(3e6, -2e6)] { + let corner = + Anchor { p, h_in: p + Vec2::new(117.73528366134629, 927.4795508230089), h_out: p + Vec2::new(3.0, 0.0), kind: AnchorKind::Corner }; + let path = Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().path_data_mut().unwrap(); + path.subpaths[0].anchors[5] = corner; + for i in 0..40 { + let t = f64::from(i) * 0.37; + let to = p + Vec2::new(8.028549152229672 * t.cos() + 0.1 * f64::from(i), -9.388200339328929 * t.sin() - 0.03 * f64::from(i)); + let link = json!({"id": id.0, "anchor": 5, "which": "out", "x": to.x, "y": to.y, "link": true}); + s.execute("path.setHandle", &link).unwrap(); + let (steps, a) = (undo_steps(&s), anchor(&s, id, 5)); + s.execute("path.setHandle", &link).unwrap(); + assert_eq!(undo_steps(&s), steps, "request {i} at {p:?} repeated recorded an undo step"); + assert_eq!(anchor(&s, id, 5), a, "request {i} at {p:?} repeated changed the anchor"); + } + + let skewed = Anchor { p, h_in: p + Vec2::new(-10.0, 1e-8), h_out: p + Vec2::new(10.0, 0.0), kind: AnchorKind::Smooth }; + let path = Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().path_data_mut().unwrap(); + path.subpaths[0].anchors[5] = skewed; + let steps = undo_steps(&s); + s.execute("path.setHandle", &json!({"id": id.0, "anchor": 5, "which": "out", "x": skewed.h_out.x, "y": skewed.h_out.y, "link": true})) + .unwrap(); + assert_eq!(undo_steps(&s), steps + 1, "the off-line handle at {p:?} was left as it was"); + let a = anchor(&s, id, 5); + assert!(a.h_out == skewed.h_out && a.h_in.y == p.y, "{a:?}"); + } + + // Far from the origin, a short handle at right angles and a handle 1e-9 pt off line are still + // turned into line. + let p = Point::new(3.9e6, 0.0); + for h_in in [Point::new(p.x, 1.5e-9), Point::new(p.x - 10.0, 1e-9)] { + let off = Anchor { p, h_in, h_out: p + Vec2::new(10.0, 0.0), kind: AnchorKind::Smooth }; + let path = Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().path_data_mut().unwrap(); + path.subpaths[0].anchors[5] = off; + let steps = undo_steps(&s); + s.execute("path.setHandle", &json!({"id": id.0, "anchor": 5, "which": "out", "x": off.h_out.x, "y": off.h_out.y, "link": true})).unwrap(); + assert_eq!(undo_steps(&s), steps + 1, "the handle at {h_in:?} was left as it was"); + let a = anchor(&s, id, 5); + assert!(a.h_in.y == 0.0 && a.h_in.x < p.x, "{a:?}"); + } + + // An other handle on the same side as the linked one is turned to the far side. + let p = near; + let same = Anchor { p, h_in: p + Vec2::new(5.0, 0.0), h_out: p + Vec2::new(10.0, 0.0), kind: AnchorKind::Smooth }; + let path = Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().path_data_mut().unwrap(); + path.subpaths[0].anchors[5] = same; + let steps = undo_steps(&s); + s.execute("path.setHandle", &json!({"id": id.0, "anchor": 5, "which": "out", "x": same.h_out.x, "y": same.h_out.y, "link": true})).unwrap(); + assert_eq!(undo_steps(&s), steps + 1, "the handle on the same side was left as it was"); + assert!(anchor(&s, id, 5).h_in.distance(p + Vec2::new(-5.0, 0.0)) < 1e-9, "{:?}", anchor(&s, id, 5)); +} diff --git a/crates/engine/src/tests/assets_3d.rs b/crates/engine/src/tests/assets_3d.rs index d546eed793..1a647fb798 100644 --- a/crates/engine/src/tests/assets_3d.rs +++ b/crates/engine/src/tests/assets_3d.rs @@ -312,6 +312,112 @@ fn export_3d_paints_mapped_graphics_on_their_caps_in_every_format() { assert_eq!(image::load_from_memory(&png).unwrap().to_rgba8().dimensions(), (1024, 1024), "1024 pixels by default"); } +/// A blue 100 × 100 square revolved straight on about its left edge with `params`, with the red +/// 10 × 20 graphic "Mark" mapped onto its side `x` pt from the middle, collected as a 3D asset named +/// "Ball" in `format`. +fn revolved(format: &str, params: Value, x: f64) -> (Session, u64) { + let mut s = session(); + let mark = run(&mut s, "path.create", json!({"d": "M300 300L310 300L310 320L300 320Z"}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "threeD.addGraphic", json!({"name": "Mark", "ids": [mark]})); + let id = run(&mut s, "path.create", json!({"d": "M100 100L200 100L200 200L100 200Z"}))["id"].as_u64().unwrap(); + run(&mut s, "paint.setFill", json!({"color": "#0000ff"})); + let mut p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0}); + p.as_object_mut().unwrap().extend(params.as_object().unwrap().clone()); + run(&mut s, "effect.apply", json!({"effect": "threeD.revolve", "params": p})); + run(&mut s, "threeD.mapGraphic", json!({"symbol": "Mark", "x": x, "ids": [id]})); + run(&mut s, "layer.setProps", json!({"id": id, "name": "Ball"})); + let asset = run(&mut s, "assets.add3D", json!({"ids": [id], "format": format}))["assets"][0].as_u64().unwrap(); + (s, asset) +} + +#[test] +fn export_3d_paints_graphics_mapped_onto_a_revolves_side_in_every_format() { + for (format, names) in [ + ("usda", vec!["Ball.usda", "Ball-texture-1.png"]), + ("usdz", vec!["Ball.usdz"]), + ("gltf", vec!["Ball.gltf"]), + ("obj", vec!["Ball.obj", "Ball.mtl", "Ball-texture-1.png"]), + ] { + let (mut s, _) = revolved(format, json!({}), 0.0); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::>(), names, "{format}"); + } + // The side unrolled is 200π around the axis (the square's far edge is 100 from it) by 300 + // along the profile (its edge on the axis sweeps nothing): 512 × 245 pixels, blue with the red + // graphic at the middle. + let (mut s, _) = revolved("usda", json!({}), 0.0); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 512}))); + let picture = &out[1].1; + let scale = 512.0 / (200.0 * std::f64::consts::PI); + assert_eq!(image::load_from_memory(picture).unwrap().to_rgba8().dimensions(), (512, (300.0 * scale).ceil() as u32)); + let middle = (150.0 * scale) as u32; + assert!(is_red(pixel(picture, 256, middle)) && is_blue(pixel(picture, 10, 10)), "{:?}", pixel(picture, 256, middle)); + let usda = String::from_utf8(out[0].1.clone()).unwrap(); + assert_eq!((usda.matches("def Mesh").count(), usda.matches("primvars:st").count()), (1, 1), "the side is the only face"); + // Moved 50 pt around the axis, the graphic moves as far across the picture. + let (mut s, _) = revolved("usda", json!({}), 50.0); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 512}))); + let moved = (256.0 + 50.0 * scale).round() as u32; + assert!(is_red(pixel(&out[1].1, moved, middle)) && is_blue(pixel(&out[1].1, 256, middle))); + // An OBJ's texture coordinates stay inside the picture, as OBJ reads them (up from its bottom). + let (mut s, _) = revolved("obj", json!({}), 0.0); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + let obj = String::from_utf8(out[0].1.clone()).unwrap(); + let vt: Vec = obj.lines().filter_map(|l| l.strip_prefix("vt ")).flat_map(|l| l.split(' ').map(|v| v.parse::().unwrap())).collect(); + assert!(!vt.is_empty() && vt.iter().all(|v| (-1e-9..=1.0 + 1e-9).contains(v)), "{vt:?}"); + assert!(String::from_utf8(out[1].1.clone()).unwrap().contains("map_Kd -clamp on Ball-texture-1.png")); + // glTF embeds the picture, and the side's coordinates are its TEXCOORD_0. + let (mut s, _) = revolved("gltf", json!({}), 0.0); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + let g: Value = serde_json::from_slice(&out[0].1).unwrap(); + assert_eq!(g["images"].as_array().map(Vec::len), Some(1)); + assert!(g["meshes"].as_array().unwrap().iter().any(|m| !m["primitives"][0]["attributes"]["TEXCOORD_0"].is_null())); +} + +#[test] +fn a_partial_revolve_keeps_its_cut_sides_plain_beside_its_textured_side() { + let (mut s, asset) = revolved("usda", json!({"angle": 270.0}), 0.0); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::>(), ["Ball.usda", "Ball-texture-1.png"]); + let usda = String::from_utf8(out[0].1.clone()).unwrap(); + assert_eq!((usda.matches("def Mesh").count(), usda.matches("primvars:st").count()), (2, 1), "the cut sides and the side"); + let d = &s.doc().unwrap().doc; + let id = d.asset(asset).unwrap().nodes[0].0; + // Without its graphics the surface is one plain mesh, as before. + run(&mut s, "select.set", json!({"ids": [id]})); + run(&mut s, "effect.setParams", json!({"index": 0, "params": {"graphics": []}})); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::>(), ["Ball.usda"]); + assert_eq!(String::from_utf8(out[0].1.clone()).unwrap().matches("def Mesh").count(), 1); +} + +#[test] +fn a_revolved_groups_graphics_export_on_its_longest_members_side_only() { + let mut s = session(); + let mark = run(&mut s, "path.create", json!({"d": "M300 300L310 300L310 320L300 320Z"}))["id"].clone(); + run(&mut s, "threeD.addGraphic", json!({"name": "Mark", "ids": [mark]})); + let a = run(&mut s, "path.create", json!({"d": "M100 100L140 100L140 200L100 200Z"}))["id"].as_u64().unwrap(); + let b = run(&mut s, "path.create", json!({"d": "M100 120L160 120L160 130L100 130Z"}))["id"].as_u64().unwrap(); + let g = run(&mut s, "object.group", json!({"ids": [a, b]}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [g]})); + run(&mut s, "effect.apply", json!({"effect": "threeD.revolve", "params": {"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0}})); + run(&mut s, "threeD.mapGraphic", json!({"symbol": "Mark", "ids": [g]})); + let d = &s.doc().unwrap().doc; + let parts = vectorcraft_render::effects::three_d_meshes_in(Some(d), d.node(vectorcraft_doc::NodeId(g)).unwrap()).unwrap(); + assert_eq!(parts.len(), 2); + let textured: Vec = parts.iter().enumerate().filter(|(_, p)| p.graphics.is_some()).map(|(k, _)| k).collect(); + assert_eq!(textured, [0], "the taller member's side"); + // A half-opaque member: as on the canvas, its opacity applies to its side and the graphics + // together, and the graphics keep the opacity of the fill. + run(&mut s, "transparency.set", json!({"ids": [a], "opacity": 50})); + let d = &s.doc().unwrap().doc; + let parts = vectorcraft_render::effects::three_d_meshes_in(Some(d), d.node(vectorcraft_doc::NodeId(g)).unwrap()).unwrap(); + let graphics = parts[0].graphics.as_ref().unwrap(); + assert_eq!((graphics.opacity, graphics.object), (1.0, 0.5)); + assert!((parts[0].color[3] - 0.5).abs() < 1e-6, "{:?}", parts[0].color); +} + #[test] fn a_texture_takes_the_opacity_of_the_fill_and_of_the_object_as_the_canvas_draws_them() { let half = |a: u8| (120..=135).contains(&a); diff --git a/crates/engine/src/tests/attributes.rs b/crates/engine/src/tests/attributes.rs index b6d00111e2..35dda8656b 100644 --- a/crates/engine/src/tests/attributes.rs +++ b/crates/engine/src/tests/attributes.rs @@ -90,6 +90,23 @@ fn values_that_differ_read_null_and_recent_urls_keep_the_newest_first() { assert_eq!(info(&mut s, json!({"ids": [p.0, a.0]}))["showCenter"], Value::Null); } +/// The recent URLs keep the 30 newest distinct URLs, the most the panel's URL menu can list, and +/// a URL given again moves to the front without taking a second place. +#[test] +fn recent_urls_keep_the_thirty_newest() { + let mut s = session(); + rect(&mut s, 0.0); + for i in 0..35 { + run(&mut s, "attributes.set", json!({"url": format!("https://example.com/{i}")})); + } + let want: Vec = (5..35).rev().map(|i| format!("https://example.com/{i}")).collect(); + assert_eq!(info(&mut s, json!({}))["recentUrls"], json!(want)); + run(&mut s, "attributes.set", json!({"url": "https://example.com/20"})); + let urls = info(&mut s, json!({}))["recentUrls"].as_array().unwrap().clone(); + assert_eq!((urls.len(), urls[0].as_str(), urls[1].as_str()), (30, Some("https://example.com/20"), Some("https://example.com/34"))); + assert_eq!(urls.iter().filter(|u| *u == "https://example.com/20").count(), 1); +} + /// A five-pointed star drawn as one self-intersecting path (its centre is wound twice). fn star(s: &mut Session) -> NodeId { let (c, r) = (50.0f64, 45.0f64); diff --git a/crates/engine/src/tests/blendspine.rs b/crates/engine/src/tests/blendspine.rs index c22eb188b7..7f7c7fffa4 100644 --- a/crates/engine/src/tests/blendspine.rs +++ b/crates/engine/src/tests/blendspine.rs @@ -431,3 +431,35 @@ fn a_spine_segment_bends_with_perpendicular_handles() { use vectorcraft_geom::kurbo::ParamCurve; assert!(sp.segment(0).eval(0.5).distance(Point::new(55.0, 45.0)) < 1e-9, "{sp:?}"); } + +/// `link` with `handle` makes a spine point smooth, the other handle in line opposite the moved +/// one, without moving the keys; the same request again records no undo step, and `link` that is +/// not a boolean, goes with `independent` or comes without `handle` is refused. +#[test] +fn a_linked_spine_handle_makes_the_point_smooth() { + let mut s = session(); + let (_, _, g) = blend(&mut s); + s.execute("object.blend.spine.addAnchor", &json!({"x": 55, "y": 5})).unwrap(); + let undo = |s: &Session| s.doc().unwrap().history.undo.len(); + let link = json!({"anchor": 1, "handle": "out", "x": 75, "y": 25, "link": true}); + s.execute("object.blend.spine.moveAnchor", &link).unwrap(); + let a = spec(&s, g).spine.unwrap().subpaths[0].anchors[1]; + assert_eq!((a.kind, a.h_out), (vectorcraft_geom::AnchorKind::Smooth, Point::new(75.0, 25.0))); + let (din, dout) = (a.h_in - a.p, a.h_out - a.p); + assert!(din.hypot() > 1e-6 && (din.normalize() + dout.normalize()).hypot() < 1e-9, "{a:?}"); + let st = steps(&s, g); + assert_eq!((center(&st[0]), center(&st[2])), (Point::new(5.0, 5.0), Point::new(105.0, 5.0)), "the keys stay put"); + let done = undo(&s); + s.execute("object.blend.spine.moveAnchor", &link).unwrap(); + assert_eq!(undo(&s), done, "an unchanged spine recorded an undo step"); + let before = spec(&s, g); + for bad in [ + json!({"anchor": 1, "handle": "out", "x": 75, "y": 25, "link": "yes"}), + json!({"anchor": 1, "handle": "out", "x": 75, "y": 25, "link": true, "independent": true}), + json!({"anchor": 1, "x": 75, "y": 25, "link": true}), + ] { + assert!(s.execute("object.blend.spine.moveAnchor", &bad).is_err(), "{bad}"); + } + assert_eq!(spec(&s, g), before); + assert_eq!(undo(&s), done); +} diff --git a/crates/engine/src/tests/brushlib.rs b/crates/engine/src/tests/brushlib.rs index 4f0b739951..1010f6f3d3 100644 --- a/crates/engine/src/tests/brushlib.rs +++ b/crates/engine/src/tests/brushlib.rs @@ -110,40 +110,53 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { "art-ribbons", "ink-and-wash", "calligraphic-nibs", + "pressure-sensitive", "bristle-brushes", "pattern-borders", "scatter-shapes", + "stipple", "game-trails", "energy-beams", "dry-media", - "tech-circuit" + "tech-circuit", + "arrows", + "image-brush" ] ); assert!(libs.iter().all(|l| l["category"] == "builtIn")); + // Looked up by id, so a library added to the list does not shift these checks. + let entry = |id: &str| libs.iter().find(|l| l["id"] == id).unwrap(); let lib = run(&mut s, "brush.library", json!({"library": "art ribbons"})); assert_eq!( lib["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::>(), ["Notched Ribbon", "Double Line", "Wave", "Teardrop", "Striped Ribbon"] ); - assert_eq!(libs[0]["count"].as_u64(), Some(5)); + assert_eq!(entry("art-ribbons")["count"].as_u64(), Some(5)); let trails = run(&mut s, "brush.library", json!({"library": "game-trails"})); assert_eq!( trails["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::>(), ["Speed Line", "Dash Trail", "Burst Ray", "Zigzag"] ); - assert_eq!(libs[6]["count"].as_u64(), Some(4)); + assert_eq!(entry("game-trails")["count"].as_u64(), Some(4)); let beams = run(&mut s, "brush.library", json!({"library": "energy-beams"})); assert_eq!( beams["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::>(), ["Laser Bolt", "Plasma Arc", "Charge Wave", "Spark Trail"] ); - assert_eq!(libs[7]["count"].as_u64(), Some(4)); + assert_eq!(entry("energy-beams")["count"].as_u64(), Some(4)); let dry = run(&mut s, "brush.library", json!({"library": "Dry Media"})); assert_eq!( dry["brushes"].as_array().unwrap().iter().map(|b| (b["name"].as_str().unwrap(), b["type"].as_str().unwrap())).collect::>(), [("Chalk Grain", "art"), ("Graphite Pencil", "art"), ("Wax Crayon", "art"), ("Charcoal Dust", "art")] ); - assert_eq!((libs[8]["name"].as_str(), libs[8]["count"].as_u64()), (Some("Dry Media"), Some(4))); + assert_eq!((entry("dry-media")["name"].as_str(), entry("dry-media")["count"].as_u64()), (Some("Dry Media"), Some(4))); + let arrows = run(&mut s, "brush.library", json!({"library": "Arrows"})); + assert_eq!( + arrows["brushes"].as_array().unwrap().iter().map(|b| (b["name"].as_str().unwrap(), b["type"].as_str().unwrap())).collect::>(), + [("Solid Arrow", "art"), ("Open Arrow", "art"), ("Double Arrow", "art"), ("Chevron Arrow", "art"), ("Dashed Arrow", "art")] + ); + assert_eq!((entry("arrows")["name"].as_str(), entry("arrows")["count"].as_u64()), (Some("Arrows"), Some(5))); + assert_eq!((entry("stipple")["name"].as_str(), entry("stipple")["count"].as_u64()), (Some("Stipple"), Some(4))); run(&mut s, "file.new", json!({"width": 200, "height": 200})); let id = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 40, "height": 8}))["id"].as_u64().unwrap(); let added = run(&mut s, "brush.addFromLibrary", json!({"library": "energy-beams", "name": "Laser Bolt", "apply": true, "ids": [id]})); @@ -154,17 +167,21 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { ("art-ribbons", "art"), ("ink-and-wash", "art"), ("calligraphic-nibs", "calligraphic"), + ("pressure-sensitive", "art"), ("bristle-brushes", "bristle"), ("pattern-borders", "pattern"), ("scatter-shapes", "scatter"), + ("stipple", "scatter"), ("game-trails", "art"), ("energy-beams", "art"), ("dry-media", "art"), + ("arrows", "art"), + ("image-brush", "scatter"), ] { let (_, lib) = cmd::brushlib::library(&s, id).unwrap(); assert!(lib.len() >= 4, "{id}"); for b in &lib.brushes { - let kind = if b.name == "Brush Pen" { "calligraphic" } else { kind }; + let kind = if ["Brush Pen", "Round Flow", "Chisel Flow"].contains(&b.name.as_str()) { "calligraphic" } else { kind }; assert_eq!(b.kind.type_id(), kind, "{}", b.name); let mut line = vectorcraft_geom::BezPath::new(); line.move_to((0.0, 0.0)); @@ -190,6 +207,43 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { assert!(s.execute("brush.library", &json!({"library": "nope"})).is_err()); } +#[test] +fn image_brush_stamps_draw_and_carry_their_pixels_when_added_and_saved() { + let mut s = session(); + let (_, lib) = cmd::brushlib::library(&s, "image-brush").unwrap(); + let names = ["Soft Bloom", "Halftone Field", "Solar Grain", "Color Flecks"]; + assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::>(), names); + assert_eq!(lib.doc.images.len(), 4); + let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 40, "x2": 190, "y2": 40}))["id"].as_u64().unwrap(); + for b in &lib.brushes { + let BrushKind::Scatter(sc) = &b.kind else { panic!("{} is not a scatter brush", b.name) }; + let NodeKind::Image(image) = &sc.art.kind else { panic!("{} has no image stamp", b.name) }; + assert!(lib.doc.images.get(&image.key).is_some_and(|blob| blob.bytes.starts_with(b"\x89PNG\r\n\x1a\n"))); + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &black_stroke()); + assert!(pieces.len() >= 3 && pieces.iter().all(|p| matches!(p.kind, NodeKind::Image(_))), "{}", b.name); + // A short accent shows at least one stamp at a 1 pt stroke. + let short = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(10.0), &black_stroke()); + assert!(!short.is_empty() && short.iter().all(|p| matches!(p.kind, NodeKind::Image(_))), "{} on a 10 pt line", b.name); + let before = undo_len(&s); + let added = run(&mut s, "brush.addFromLibrary", json!({"library": "image-brush", "name": b.name, "apply": true, "ids": [path]})); + assert_eq!(strs(&added["added"]), [b.name.as_str()]); + assert_eq!(added["applied"], json!([path])); + assert_eq!(undo_len(&s), before + 1); + assert!(doc(&s).images.contains_key(&image.key), "{} pixels were not copied", b.name); + } + let saved = run(&mut s, "brush.saveLibrary", json!({"names": names})); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let reopened = vectorcraft_format::load(&bytes).unwrap(); + let mut saved_brushes = vectorcraft_brush::library(&reopened); + for brush in &mut saved_brushes { + if let BrushKind::Scatter(sc) = &mut brush.kind { + sc.art.id = NodeId(0); // Loaded image art is given a fresh document node ID. + } + } + assert_eq!(saved_brushes, lib.brushes); + assert_eq!(reopened.images, lib.doc.images); +} + /// Every path of brush art `n`: (anchors, opacity). fn art_paths(n: &vectorcraft_doc::Node) -> Vec<(usize, f32)> { let mut out = vec![]; @@ -218,6 +272,126 @@ fn black_stroke() -> vectorcraft_doc::StrokeLayer { vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0) } +#[test] +fn stipple_library_draws_dot_textures_and_survives_save() { + let mut s = session(); + let (_, lib) = cmd::brushlib::library(&s, "stipple").unwrap(); + let names: Vec<&str> = lib.brushes.iter().map(|b| b.name.as_str()).collect(); + assert_eq!(names, ["Fine Stipple", "Dense Stipple", "Soft Stipple", "Bold Stipple"]); + let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 20, "x2": 210, "y2": 20}))["id"].as_u64().unwrap(); + for b in &lib.brushes { + let BrushKind::Scatter(scatter) = &b.kind else { panic!("{} is not a scatter brush", b.name) }; + assert_eq!(scatter.colorization, vectorcraft_brush::Colorization::Tints); + assert!(scatter.spacing.0 > 0.0 && scatter.spacing.1 >= scatter.spacing.0); + // A red stroke: the black dots take it as their color, and Soft Stipple's dots stay translucent. + let red = vectorcraft_color::Color::rgb(0.8, 0.1, 0.2); + let stroke = vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(red), 1.0); + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(200.0), &stroke); + let points = anchors(&pieces.iter().collect::>()); + assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name); + let mut dots = vec![]; + for piece in &pieces { + piece.walk(&mut |c| { + if c.path_data().is_some() { + let fill = c.appearance.fill().unwrap_or_else(|| panic!("a {} dot has no fill", b.name)); + dots.push((fill.paint.color(), fill.opacity)); + } + }); + } + assert!(!dots.is_empty(), "{}", b.name); + for (color, opacity) in dots { + let rgb = color.unwrap_or_else(|| panic!("a {} dot is not a solid color", b.name)).to_rgb(); + assert!(rgb.iter().zip(red.to_rgb()).all(|(a, e)| (a - e).abs() < 1e-4), "{} dot is {rgb:?}, not the stroke color", b.name); + if b.name == "Soft Stipple" { + assert!(opacity > 0.0 && opacity < 1.0, "Soft Stipple dot opacity {opacity}"); + } else { + assert_eq!(opacity, 1.0, "{}", b.name); + } + } + let before = undo_len(&s); + let result = run(&mut s, "brush.addFromLibrary", json!({"library": "stipple", "name": b.name, "apply": true, "ids": [path]})); + assert_eq!(strs(&result["added"]), [b.name.as_str()]); + assert_eq!(undo_len(&s), before + 1); + assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str())); + } + let saved = run(&mut s, "brush.saveLibrary", json!({"names": names})); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let reopened = vectorcraft_format::load(&bytes).unwrap(); + assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); +} + +#[test] +fn arrows_library_lists_renders_and_applies_original_brushes() { + let mut s = session(); + let listed = run(&mut s, "brush.libraries", json!({})); + let entry = listed["libraries"].as_array().unwrap().iter().find(|l| l["id"] == "arrows").unwrap(); + assert_eq!((entry["name"].as_str(), entry["category"].as_str(), entry["count"].as_u64()), (Some("Arrows"), Some("builtIn"), Some(5))); + let (_, lib) = cmd::brushlib::library(&s, "Arrows").unwrap(); + assert_eq!( + lib.brushes.iter().map(|b| (b.name.as_str(), b.kind.type_id())).collect::>(), + [("Solid Arrow", "art"), ("Open Arrow", "art"), ("Double Arrow", "art"), ("Chevron Arrow", "art"), ("Dashed Arrow", "art")] + ); + for b in &lib.brushes { + for length in [2.0, 200.0] { + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(length), &black_stroke()); + let pts = anchors(&pieces.iter().collect::>()); + assert!(!pts.is_empty() && pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{} at {length} pt", b.name); + } + } + let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 20, "x2": 210, "y2": 20}))["id"].as_u64().unwrap(); + let before = undo_len(&s); + let added = run(&mut s, "brush.addFromLibrary", json!({"library": "arrows", "name": "Double Arrow", "apply": true, "ids": [path]})); + assert_eq!(strs(&added["added"]), ["Double Arrow"]); + assert_eq!(added["applied"], json!([path])); + assert_eq!(undo_len(&s), before + 1); + assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some("Double Arrow")); + run(&mut s, "edit.undo", json!({})); + assert!(vectorcraft_brush::find(doc(&s), "Double Arrow").is_none()); + run(&mut s, "edit.redo", json!({})); + assert_eq!(brush(&s, "Double Arrow"), lib.brushes[2]); +} + +#[test] +fn the_chevron_arrows_second_chevron_keeps_its_length_on_a_long_path() { + let s = session(); + let (_, lib) = cmd::brushlib::library(&s, "Arrows").unwrap(); + let b = lib.brush("Chevron Arrow").unwrap(); + let widths = |length: f64| { + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(length), &black_stroke()); + let children = pieces[0].children().unwrap(); + assert_eq!(children.len(), 3, "shaft, head and second chevron"); + children[1..].iter().map(|n| n.geometric_bounds().unwrap().width()).collect::>() + }; + let short = widths(100.0); + for (long, short) in widths(400.0).into_iter().zip(short) { + assert!((long - short).abs() < 1e-6, "the heads keep their length: {long} on 400 pt, {short} on 100 pt"); + } +} + +#[test] +fn dashed_arrow_keeps_separate_dashes_and_survives_library_save() { + let mut s = session(); + let (_, lib) = cmd::brushlib::library(&s, "Arrows").unwrap(); + let b = lib.brush("Dashed Arrow").unwrap(); + let mut curve = line_to(40.0); + curve.curve_to((60.0, -40.0), (140.0, 40.0), (200.0, 0.0)); + for path in [line_to(2.0), line_to(200.0), curve] { + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &path, &black_stroke()); + let pts = anchors(&pieces.iter().collect::>()); + assert!(!pts.is_empty() && pts.iter().all(|p| p.x.is_finite() && p.y.is_finite())); + } + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(200.0), &black_stroke()); + let children = pieces[0].children().unwrap(); + assert_eq!(children.len(), 6, "five separate dashes and one head"); + let bounds: Vec<_> = children.iter().map(|n| n.geometric_bounds().unwrap()).collect(); + assert!(bounds.windows(2).all(|p| p[0].x1 < p[1].x0), "the dashes and head remain separated"); + run(&mut s, "brush.addFromLibrary", json!({"library": "arrows", "name": "Dashed Arrow"})); + let saved = run(&mut s, "brush.saveLibrary", json!({"names": ["Dashed Arrow"]})); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let reopened = vectorcraft_format::load(&bytes).unwrap(); + assert_eq!(vectorcraft_brush::find(&reopened, "Dashed Arrow").unwrap(), *b); +} + /// Original circuit art and repeat tiles survive adding, applying and saving a library. #[test] fn the_tech_circuit_library_constructs_adds_and_applies_each_brush() { @@ -299,6 +473,52 @@ fn the_tech_circuit_library_constructs_adds_and_applies_each_brush() { assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); } +#[test] +fn pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_library() { + let mut s = session(); + let (_, lib) = cmd::brushlib::library(&s, "Pressure Sensitive").unwrap(); + let names = ["Flex Ribbon", "Pulse Stroke", "Round Flow", "Chisel Flow"]; + assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::>(), names); + let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 40, "x2": 190, "y2": 40}))["id"].as_u64().unwrap(); + let mut curve = line_to(20.0); + curve.curve_to((60.0, -25.0), (140.0, 25.0), (180.0, 0.0)); + for b in &lib.brushes { + let width_at = |pressure| { + let stroke = vectorcraft_doc::StrokeLayer { + pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, pressure), (1.0, pressure)] }), + ..black_stroke() + }; + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &stroke); + let points = anchors(&pieces.iter().collect::>()); + assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{} at pressure {pressure}", b.name); + let min = points.iter().map(|p| p.y).fold(f64::INFINITY, f64::min); + let max = points.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max); + max - min + }; + let light = width_at(0.0); + let heavy = width_at(1.0); + for width in [light, heavy] { + assert!(width.is_finite() && width > 0.0, "{}: light={light}, heavy={heavy}", b.name); + } + assert!(heavy > light * 1.3, "{}: light={light}, heavy={heavy}", b.name); + for line in [line_to(2.0), curve.clone()] { + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line, &black_stroke()); + let points = anchors(&pieces.iter().collect::>()); + assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name); + } + let before = undo_len(&s); + let added = run(&mut s, "brush.addFromLibrary", json!({"library": "pressure-sensitive", "name": b.name, "apply": true, "ids": [path]})); + assert_eq!(strs(&added["added"]), [b.name.as_str()]); + assert_eq!(added["applied"], json!([path])); + assert_eq!(undo_len(&s), before + 1); + assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str())); + } + let saved = run(&mut s, "brush.saveLibrary", json!({"names": names})); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let reopened = vectorcraft_format::load(&bytes).unwrap(); + assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); +} + /// Ink and Wash: a tapered ink art brush, a brush pen whose size follows the pen pressure and two /// translucent washes, with names of their own and a few paths of art each. #[test] diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 3a3a07a2c1..1d53214ec9 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1572,6 +1572,79 @@ fn freehand_points_record_the_pens_tilt_bearing_and_rotation() { assert_eq!(tilt.unwrap().at(0.9), vectorcraft_doc::PressureProfile::MID, "half way over without one"); } +/// The airbrush finger wheel recorded on the stroke `id`. +fn wheel_of(s: &Session, id: NodeId) -> Option { + node(s, id).appearance.stroke().and_then(|st| st.wheel.clone()) +} + +/// `path.freehand` points carry an airbrush pen's finger wheel seventh (or as `wheel`), 0..1; the +/// stroke keeps it, a continued or reversed stroke keeps it in step, a wheel that is not a number +/// or is outside 0..1 is refused, and the Paintbrush records it from the pen. A Calligraphic brush with +/// Size on Stylus Wheel draws it, and it lasts through saving, new art leaving it behind. +#[test] +fn freehand_points_record_the_stylus_wheel() { + let mut s = session(); + let draw = |s: &mut Session, points: Value| { + NodeId(s.execute("path.freehand", &json!({"points": points, "style": "brush"})).unwrap()["id"].as_u64().unwrap()) + }; + let id = draw(&mut s, json!([[0, 50, null, null, null, null, 0], [100, 50, null, null, null, null, 1]])); + let w = wheel_of(&s, id).unwrap(); + assert!(w.at(0.0) < 1e-6 && (w.at(1.0) - 1.0).abs() < 1e-6, "{w:?}"); + assert_eq!(pose_of(&s, id), (None, None, None), "the wheel alone"); + assert_eq!(pressure_of(&s, id), None); + // As keys; a point without one is half way. + let id = draw(&mut s, json!([{"x": 0, "y": 150, "wheel": 0}, {"x": 50, "y": 150}, {"x": 100, "y": 150, "wheel": 1}])); + let w = wheel_of(&s, id).unwrap(); + assert!(w.at(0.0) < 1e-6 && (w.at(0.5) - 0.5).abs() < 1e-6 && (w.at(1.0) - 1.0).abs() < 1e-6, "{w:?}"); + // No wheel given: none recorded. + let id = draw(&mut s, json!([[0, 250, 0.5, 30, 0, 90], [100, 250, 0.5, 30, 0, 90]])); + assert_eq!(wheel_of(&s, id), None); + // Not a number: refused, and nothing drawn. + let before = s.doc().unwrap().doc.clone(); + let err = s.execute("path.freehand", &json!({"points": [[0, 0, null, null, null, null, "0.5"], [10, 0]], "style": "brush"})); + assert!(err.unwrap_err().to_string().contains("`wheel` must be a number")); + assert_eq!(s.doc().unwrap().doc.layers, before.layers, "the document is unchanged"); + // Outside 0..1: refused, and nothing drawn. + for points in [json!([{"x": 0, "y": 0, "wheel": -2}, {"x": 10, "y": 0}]), json!([[0, 0], [10, 0, null, null, null, null, 9]])] { + let err = s.execute("path.freehand", &json!({"points": points, "style": "brush"})); + assert!(err.unwrap_err().to_string().contains("`wheel` must be from 0 to 1")); + assert_eq!(s.doc().unwrap().doc.layers, before.layers, "the document is unchanged"); + } + // Continued at its end by a stroke without a wheel: the old part keeps it, the new one is half way. + let id = draw(&mut s, json!([[0, 350, null, null, null, null, 1], [100, 350, null, null, null, null, 1]])); + s.execute("path.freehand", &json!({"points": [[100, 350], [200, 350]], "style": "brush", "extend": {"id": id.0, "end": "end"}})).unwrap(); + let w = wheel_of(&s, id).unwrap(); + assert!((w.at(0.25) - 1.0).abs() < 1e-6 && (w.at(0.9) - 0.5).abs() < 1e-6, "{w:?}"); + // The Paintbrush records it, and a brush with Size on Stylus Wheel draws it. + let params = json!({"angle": 0, "roundness": 100, "size": 6, "variation": [0, 0, 4], "modes": ["fixed", "fixed", "stylusWheel"]}); + s.execute("brush.options", &json!({"name": "3 pt. Round", "params": params})).unwrap(); + s.execute("brush.setCurrent", &json!({"name": "3 pt. Round"})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("paintbrush", v).unwrap(); + let strokes = |s: &mut Session, y: f64, wheel: Option| { + let pen = wheel.map(|w| PenPose { wheel: Some(w), ..PenPose::default() }); + for (k, x) in [(PointerKind::Down, 20.0), (PointerKind::Drag, 120.0), (PointerKind::Drag, 220.0), (PointerKind::Up, 320.0)] { + s.pointer(&PointerEvent { pen, ..PointerEvent::new(k, x, y) }, v).unwrap(); + } + let id = s.doc().unwrap().selection.objects[0]; + select(s, &[]); + id + }; + let far = strokes(&mut s, 500.0, Some(1.0)); + let near = strokes(&mut s, 600.0, Some(0.0)); + let mouse = strokes(&mut s, 700.0, None); + assert_eq!(wheel_of(&s, far).map(|w| w.at(0.5)), Some(1.0)); + assert_eq!(wheel_of(&s, mouse), None, "a mouse has no wheel"); + let height = |s: &Session, id| brushed_bounds(s, id).height(); + assert!((height(&s, far) - 10.0).abs() < 0.1 && (height(&s, near) - 2.0).abs() < 0.1, "{} {}", height(&s, far), height(&s, near)); + assert!((height(&s, mouse) - 6.0).abs() < 0.1, "the brush's own size: {}", height(&s, mouse)); + // Saved and reopened as it was; new art takes the look without the wheel. + let doc: Document = (*s.doc().unwrap().doc).clone(); + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + assert_eq!(back.node(far).unwrap().appearance.stroke(), doc.node(far).unwrap().appearance.stroke()); + assert!(vectorcraft_doc::Appearance::clone(&doc.node(far).unwrap().appearance).without_pressure().stroke().is_some_and(|st| st.wheel.is_none())); +} + /// #764: a stroke that connects two paths joins the pen's tilt, bearing and rotation of both, the /// connected path's after the stroke's. #[test] @@ -1611,7 +1684,7 @@ fn paintbrush_records_the_pens_tilt_on_the_stroke() { select(s, &[]); id }; - let pen = strokes(&mut s, 60.0, Some(PenPose { tilt: Some([0.0, 0.0]), rotation: Some(30.0) })); + let pen = strokes(&mut s, 60.0, Some(PenPose { tilt: Some([0.0, 0.0]), rotation: Some(30.0), wheel: None })); let (tilt, bearing, rotation) = pose_of(&s, pen); assert_eq!(tilt.as_ref().map(|t| t.at(0.5)), Some(0.0), "upright"); assert!(bearing.is_some() && (rotation.unwrap().at(0.5) + 30.0).abs() < 1e-6); diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index dfab5336de..9d1447adb8 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -3189,6 +3189,283 @@ fn live_paint_stroke_edge() { assert!(s.execute("livePaint.strokeEdge", &json!({"group": g.0, "point": [300, 300]})).is_err()); } +/// While the Live Paint Bucket is active, a fill or stroke color chosen without `ids`, `id` or +/// `item` becomes the color the bucket paints with: the selected Live Paint group and other +/// selected art keep their paint, and the next bucket click paints one face in that color. Given +/// `ids`, the paint still goes to those objects. +#[test] +fn live_paint_bucket_color_choice_leaves_the_selection_unpainted() { + use vectorcraft_tools::builder::{edges, faces}; + let mut s = session(); + let g = live(&mut s); + let rect = rect(&mut s, 300.0, 300.0, 40.0, 40.0); + let rect_fill = node(&s, rect).appearance.fill_paint(); + s.execute("select.set", &json!({"ids": [g.0, rect.0]})).unwrap(); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + let before = node(&s, g); + let steps = s.doc().unwrap().history.undo.len(); + let magenta = Paint::solid(Color::from_hex("#ff00ff").unwrap()); + let r = s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap(); + assert_eq!(r["objects"], 0); + s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap(); + assert_eq!(s.paint.fill, magenta, "the bucket's fill color"); + assert_eq!(s.paint.stroke, Paint::solid(Color::from_hex("#0000ff").unwrap())); + assert_eq!(node(&s, g), before, "the group keeps its paint"); + assert_eq!(node(&s, rect).appearance.fill_paint(), rect_fill, "other selected art keeps its paint"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no undo step"); + // The proxies show the bucket's colors, not the selection's. + assert_eq!(s.proxy_paints(), (magenta.clone(), s.paint.stroke.clone())); + assert_eq!(s.proxy_mixed(), (false, false)); + // Invert recolors the bucket's color, not the selection. + s.execute("paint.invert", &json!({"stroke": false})).unwrap(); + assert_eq!(s.paint.fill, Paint::solid(Color::from_hex("#00ff00").unwrap())); + assert_eq!(node(&s, g), before, "Invert leaves the group as it was"); + // A previewed color (the Color Picker) that is canceled puts the bucket's color back. + s.begin_interaction("Fill Color").unwrap(); + s.preview("paint.setFill", &json!({"color": "#123456"})).unwrap(); + assert_eq!(s.paint.fill, Paint::solid(Color::from_hex("#123456").unwrap())); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.fill, Paint::solid(Color::from_hex("#00ff00").unwrap()), "the canceled color is not kept"); + // With New Art Has Basic Appearance off, the selection's appearance does not replace them. + s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap(); + assert_eq!(s.paint.fill, magenta, "the bucket's fill color stays"); + // The bucket paints the face it clicks in the color chosen. + let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [75, 50]})).unwrap(); + let face = NodeId(r["face"].as_u64().unwrap()); + let gn = node(&s, g); + assert_eq!(faces(&gn).iter().filter(|f| f.appearance.fill_paint() == magenta).map(|f| f.id).collect::>(), vec![face]); + assert!(edges(&gn).iter().all(|e| e.appearance.fill_paint().is_none())); + // Named objects still take the paint. + s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": [rect.0]})).unwrap(); + assert_eq!(node(&s, rect).appearance.fill_paint(), Paint::solid(Color::from_hex("#00ff00").unwrap())); +} + +/// While the Live Paint Bucket is active, each paint and stroke command run without `ids`, `id` or +/// `item` changes only the fill, stroke or weight the bucket paints with: the selection keeps its +/// paint and no undo step is recorded. Each command runs in its own session, and every command that +/// fails is listed. +#[test] +fn live_paint_bucket_paint_and_stroke_commands_leave_the_selection_unpainted() { + let red = Paint::solid(Color::from_hex("#ff0000").unwrap()); + let cyan = Paint::solid(Color::from_hex("#00ffff").unwrap()); + let blue = Color::from_hex("#0000ff").unwrap(); + let is_gradient = |p: &Paint| matches!(p, Paint::Gradient(_)); + type Check = Box bool>; + let cases: Vec<(&str, Value, Check)> = vec![ + ( + "paint.swap", + json!({}), + Box::new({ + let red = red.clone(); + move |s: &Session| s.paint.stroke == red + }), + ), + ("paint.default", json!({}), Box::new(|s: &Session| s.paint.fill == Paint::solid(Color::WHITE))), + ("paint.none", json!({}), Box::new(|s: &Session| s.paint.fill == Paint::None)), + ("paint.lastColor", json!({"stroke": false}), Box::new(move |s: &Session| s.paint.fill == Paint::solid(blue))), + ("paint.lastGradient", json!({"stroke": false}), Box::new(move |s: &Session| is_gradient(&s.paint.fill))), + ( + "paint.complement", + json!({"stroke": false}), + Box::new({ + let cyan = cyan.clone(); + move |s: &Session| s.paint.fill == cyan + }), + ), + ( + "paint.sampleColor", + json!({"color": "#00ffff", "stroke": false}), + Box::new({ + let cyan = cyan.clone(); + move |s: &Session| s.paint.fill == cyan + }), + ), + // A null `ids` or `id` names no object, as it does for every other command. + ("paint.setFill", json!({"color": "#00ffff", "ids": null, "id": null}), Box::new(move |s: &Session| s.paint.fill == cyan)), + ("paint.editGradient", json!({"stroke": false, "angle": 45}), Box::new(move |s: &Session| is_gradient(&s.paint.fill))), + ( + "paint.editGradient", + json!({"stroke": true, "strokeMode": "along"}), + Box::new(move |s: &Session| { + is_gradient(&s.paint.stroke) && s.new_art_stroke().gradient_mode == vectorcraft_doc::StrokeGradientMode::Along + }), + ), + ("stroke.set", json!({"weight": 5}), Box::new(|s: &Session| s.paint.stroke_width == 5.0 && s.shown_stroke().map(|st| st.width) == Some(5.0))), + ("stroke.weightUp", json!({}), Box::new(|s: &Session| s.paint.stroke_width == 3.0)), + ("stroke.weightDown", json!({}), Box::new(|s: &Session| s.paint.stroke_width == 1.0)), + ("stroke.set", json!({"weight": 6, "ids": null}), Box::new(|s: &Session| s.paint.stroke_width == 6.0)), + ("stroke.weightUp", json!({"id": null}), Box::new(|s: &Session| s.paint.stroke_width == 3.0)), + ( + "stroke.setAdvanced", + json!({"arrowScale": [150, 200]}), + Box::new(|s: &Session| s.shown_stroke().map(|st| st.arrow_scale) == Some((150.0, 200.0))), + ), + ]; + let mut failed = vec![]; + for (cmd, params, check) in cases { + let mut s = session(); + let g = live(&mut s); + let rect = rect(&mut s, 300.0, 300.0, 40.0, 40.0); + s.execute("select.set", &json!({"ids": [g.0, rect.0]})).unwrap(); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + s.paint.fill = red.clone(); + s.paint.stroke_width = 2.0; + s.last_solid = blue; + let (group, art) = (node(&s, g), node(&s, rect)); + let steps = s.doc().unwrap().history.undo.len(); + if let Err(e) = s.execute(cmd, ¶ms) { + failed.push(format!("{cmd}: {e}")); + continue; + } + if !check(&s) { + failed.push(format!("{cmd}: the bucket's paint did not change as expected")); + } + if node(&s, g) != group || node(&s, rect) != art { + failed.push(format!("{cmd}: the selection was painted")); + } + if s.doc().unwrap().history.undo.len() != steps { + failed.push(format!("{cmd}: an undo step was recorded")); + } + } + assert!(failed.is_empty(), "{failed:#?}"); +} + +/// With the Live Paint Bucket active, objects named with `ids` still take a stroke, and a brush +/// still goes to the selection. +#[test] +fn live_paint_bucket_named_objects_and_brushes_still_take_the_stroke() { + let mut s = session(); + let g = live(&mut s); + let rect = rect(&mut s, 300.0, 300.0, 40.0, 40.0); + s.execute("select.set", &json!({"ids": [g.0, rect.0]})).unwrap(); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + s.execute("stroke.set", &json!({"weight": 4, "ids": [rect.0]})).unwrap(); + assert_eq!(node(&s, rect).appearance.stroke_width(), 4.0); + // A brush still goes to the selection. + s.execute("select.set", &json!({"ids": [rect.0]})).unwrap(); + s.execute("stroke.setAdvanced", &json!({"brush": "3 pt. Round"})).unwrap(); + assert_eq!(node(&s, rect).appearance.stroke().and_then(|st| st.brush.clone()).as_deref(), Some("3 pt. Round")); +} + +/// While the Live Paint Bucket is active and the Fill proxy is in front, a gradient preset and a +/// color sampled into a gradient stop change the bucket's fill, even when the selection's active +/// Appearance row is a stroke. +#[test] +fn live_paint_bucket_gradient_preset_and_sampled_stop_follow_the_active_proxy() { + let mut s = session(); + live(&mut s); + let rect = rect(&mut s, 300.0, 300.0, 40.0, 40.0); + s.execute("select.set", &json!({"ids": [rect.0]})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": 1})).unwrap(); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + s.execute("paint.toggleActive", &json!({"fill": true})).unwrap(); + assert_eq!(s.appearance_item(), Some(1), "the stroke row stays active"); + let (art, stroke) = (node(&s, rect), s.paint.stroke.clone()); + s.execute("gradient.presets.apply", &json!({"name": "vignette"})).unwrap(); + let Paint::Gradient(g) = &s.paint.fill else { panic!("the bucket's fill is not a gradient") }; + assert_eq!(g.gradient.kind, vectorcraft_color::GradientKind::Radial); + assert_eq!(s.paint.stroke, stroke, "the bucket's stroke stays"); + s.execute("paint.sampleColor", &json!({"color": "#00ffff", "stop": 0})).unwrap(); + let Paint::Gradient(g) = &s.paint.fill else { panic!("the bucket's fill is not a gradient") }; + assert_eq!(g.gradient.stops[0].color, Color::from_hex("#00ffff").unwrap(), "the sampled stop"); + assert_eq!(node(&s, rect), art, "the selection keeps its paint"); +} + +/// A gradient stop selected on the selection's gradient is not selected once the Live Paint +/// Bucket is active (its proxies show the default paint), and one selected on the bucket's +/// gradient is not selected once another tool is chosen. +#[test] +fn live_paint_bucket_and_the_selection_keep_their_own_selected_stop() { + let mut s = session(); + live(&mut s); + let rect = rect(&mut s, 300.0, 300.0, 40.0, 40.0); + s.execute("select.set", &json!({"ids": [rect.0]})).unwrap(); + s.execute("paint.editGradient", &json!({"stroke": false, "kind": "linear"})).unwrap(); + s.execute("gradient.selectStop", &json!({"index": 1})).unwrap(); + assert_eq!(s.selected_stop(), Some(1)); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + assert_eq!(s.selected_stop(), None, "the selection's stop is not the bucket's"); + s.execute("paint.editGradient", &json!({"stroke": false, "kind": "linear"})).unwrap(); + s.execute("gradient.selectStop", &json!({"index": 0})).unwrap(); + assert_eq!(s.selected_stop(), Some(0)); + s.select_tool("selection", ViewInfo::default()).unwrap(); + assert_eq!(s.selected_stop(), None, "the bucket's stop is not the selection's"); +} + +/// While the Live Paint Bucket is active, a paint or stroke command with a bad `target` or +/// `aligned` is refused, as it is with the Selection tool, and the bucket's fill, stroke and weight +/// stay. +#[test] +fn live_paint_bucket_refuses_a_bad_target_or_aligned() { + let refused = [ + ("paint.setFill", json!({"color": "#00ffff", "target": "bogus"})), + ("paint.invert", json!({"ids": null, "aligned": "bad"})), + ("paint.complement", json!({"aligned": "bad"})), + ("stroke.set", json!({"weight": 6, "target": "bogus"})), + ("stroke.set", json!({"weight": 6, "aligned": "bad"})), + ("stroke.weightUp", json!({"target": "bogus"})), + ("stroke.weightUp", json!({"aligned": "bad"})), + ("stroke.weightDown", json!({"target": "bogus"})), + ("stroke.weightDown", json!({"aligned": "bad"})), + ("paint.swap", json!({"aligned": "bad"})), + ("paint.default", json!({"target": "bogus"})), + ]; + for tool in ["selection", "livePaintBucket"] { + let mut s = session(); + let g = live(&mut s); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.select_tool(tool, ViewInfo::default()).unwrap(); + let before = (s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width); + for (cmd, p) in &refused { + assert!(s.execute(cmd, p).is_err(), "{tool}: {cmd} {p}"); + assert_eq!((s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width), before, "{tool}: {cmd} {p}"); + } + } +} + +/// While the Live Paint Bucket is active, each preview of a paint command in one interaction starts +/// from the colors the interaction began with, so previewing a swap twice and committing swaps once. +#[test] +fn live_paint_bucket_previews_start_from_the_interaction_colors() { + let mut s = session(); + let g = live(&mut s); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap(); + let (fill, stroke) = (s.paint.fill.clone(), s.paint.stroke.clone()); + s.begin_interaction("Swap").unwrap(); + s.preview("paint.swap", &json!({})).unwrap(); + s.preview("paint.swap", &json!({})).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!((s.paint.fill.clone(), s.paint.stroke.clone()), (stroke, fill), "one swap"); +} + +/// A color chosen with the Live Paint Bucket is the current fill: a tool held for a moment (the +/// Hand) and let go leaves it in place, so the bucket paints with it afterwards, with New Art Has +/// Basic Appearance off and on. +#[test] +fn a_held_tool_keeps_the_live_paint_bucket_color() { + for basic in [false, true] { + let mut s = session(); + live(&mut s); + let rect = rect(&mut s, 300.0, 300.0, 40.0, 40.0); + s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": [rect.0]})).unwrap(); + s.execute("appearance.setNewArtBasic", &json!({"on": basic})).unwrap(); + s.execute("select.set", &json!({"ids": [rect.0]})).unwrap(); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap(); + let magenta = Paint::solid(Color::from_hex("#ff00ff").unwrap()); + s.select_tool("hand", ViewInfo::default()).unwrap(); + assert_eq!(s.paint.fill, magenta, "basic {basic}: the Hand keeps the current fill"); + s.switch_tool("livePaintBucket", ViewInfo::default()).unwrap(); + assert_eq!(s.paint.fill, magenta, "basic {basic}: the bucket paints with its color"); + assert_eq!(s.proxy_paints().0, magenta, "basic {basic}: the Fill proxy shows it"); + assert_eq!(node(&s, rect).appearance.fill_paint(), Paint::solid(Color::from_hex("#00ff00").unwrap()), "basic {basic}"); + } +} + /// The undo and redo depths, the unsaved state and the revision of the active document. fn history_state(s: &Session) -> (usize, usize, bool, u64) { let st = s.doc().unwrap(); @@ -3507,6 +3784,419 @@ fn live_paint_fill_skips_hidden_faces() { assert!(!node(&s, hidden).visible); } +/// The appearance of each face and each edge of Live Paint group `g`. +fn part_looks(s: &Session, g: NodeId) -> (Vec, Vec) { + use vectorcraft_tools::builder::{edges, faces}; + let n = node(s, g); + let looks = |parts: Vec<&Arc>| parts.iter().map(|p| (*p.appearance).clone()).collect(); + (looks(faces(&n)), looks(edges(&n))) +} + +/// The appearance of each hidden source path of Live Paint group `g`. +fn sources_looks(s: &Session, g: NodeId) -> Vec { + let n = node(s, g); + let src = vectorcraft_tools::builder::sources(&n).unwrap(); + src.children().unwrap().iter().map(|c| (*c.appearance).clone()).collect() +} + +/// With a tool other than the Live Paint Bucket, a fill given to a whole selected Live Paint group +/// paints its faces and leaves its edges as they are, and a stroke paints its edges and leaves its +/// faces as they are. The Fill and Stroke proxies show the faces' fill and the edges' stroke. +#[test] +fn live_paint_group_fill_goes_to_faces_and_stroke_to_edges() { + let mut s = session(); + let g = live(&mut s); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + let (faces0, edges0) = part_looks(&s, g); + let magenta = Paint::solid(Color::from_hex("#ff00ff").unwrap()); + let sources0 = sources_looks(&s, g); + assert_eq!(s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap()["objects"], faces0.len()); + let (faces1, edges1) = part_looks(&s, g); + assert!(faces1.iter().all(|f| f.fill_paint() == magenta)); + assert_eq!(edges1, edges0, "edges take no fill"); + let p = s.execute("paint.proxies", &json!({})).unwrap(); + assert_eq!(p["fillMixed"], false); + assert_eq!(p["fill"], serde_json::to_value(&magenta).unwrap()); + let blue = Paint::solid(Color::from_hex("#0000ff").unwrap()); + assert_eq!(s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap()["objects"], edges0.len()); + assert_eq!(sources_looks(&s, g), sources0, "the hidden source paths keep their paint"); + let (faces2, edges2) = part_looks(&s, g); + assert!(edges2.iter().all(|e| e.stroke_paint() == blue)); + assert_eq!(faces2, faces1, "faces take no stroke"); + let p = s.execute("paint.proxies", &json!({})).unwrap(); + assert_eq!(p["strokeMixed"], false); + assert_eq!(p["stroke"], serde_json::to_value(&blue).unwrap()); + // The same with the group given by id, and inside a selected group. + s.execute("paint.setFill", &json!({"ids": [g.0], "color": "#00ff00"})).unwrap(); + let (faces3, edges3) = part_looks(&s, g); + assert_eq!(edges3, edges2, "edges take no fill given by id"); + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + assert!(faces3.iter().all(|f| f.fill_paint() == green)); + s.execute("object.group", &json!({"ids": [g.0]})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#ff0000"})).unwrap(); + let (faces4, edges4) = part_looks(&s, g); + assert_eq!(faces4, faces3, "faces of a grouped Live Paint group take no stroke"); + assert!(edges4.iter().all(|e| e.stroke_paint() == Paint::solid(Color::from_hex("#ff0000").unwrap()))); + // The bucket then paints one face, and nothing in the group draws a fill over it. + let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [75, 50], "color": "#ffff00"})).unwrap(); + let face = NodeId(r["face"].as_u64().unwrap()); + assert_eq!(node(&s, face).appearance.fill_paint(), Paint::solid(Color::from_hex("#ffff00").unwrap())); + assert!(part_looks(&s, g).1.iter().all(|e| e.fill_paint().is_none())); +} + +/// Swap Fill and Stroke on a whole selected Live Paint group gives its faces the stroke its edges +/// share and its edges the fill its faces share; with faces of different fills, or without faces, +/// it leaves the group as it is. +#[test] +fn live_paint_group_swap_trades_the_faces_fill_and_the_edges_stroke() { + let mut s = session(); + let g = live(&mut s); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + let sources0 = sources_looks(&s, g); + // The faces are red and blue: nothing on the group changes, in no undo step. + let (faces0, edges0) = part_looks(&s, g); + let depth = history_state(&s).0; + s.execute("paint.swap", &json!({})).unwrap(); + assert_eq!(part_looks(&s, g), (faces0, edges0)); + assert_eq!(history_state(&s).0, depth); + // One fill on every face: the faces take the edges' black, the edges the faces' red, at their weight. + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 2})).unwrap(); + s.execute("paint.swap", &json!({})).unwrap(); + let (faces1, edges1) = part_looks(&s, g); + assert!(faces1.iter().all(|f| f.fill_paint() == Paint::solid(Color::BLACK))); + assert!(edges1.iter().all(|e| e.stroke_paint() == Paint::solid(Color::rgb(1.0, 0.0, 0.0)) && e.stroke_width() == 2.0)); + assert!(edges1.iter().all(|e| e.fill_paint().is_none()), "edges take no fill"); + assert_eq!(sources_looks(&s, g), sources0); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(part_looks(&s, g).0.iter().all(|f| f.fill_paint() == Paint::solid(Color::rgb(1.0, 0.0, 0.0))), "one undo step"); + // A gradient placed on each face's own bounds is one shared fill: the edges take it, fitted to each edge. + s.execute("paint.setFill", &json!({"gradient": {"aspect": 50}})).unwrap(); + let placed: Vec = part_looks(&s, g).0.iter().map(|f| f.fill_paint()).collect(); + assert!(placed.iter().all(|p| matches!(p, Paint::Gradient(gr) if gr.geom.is_some())) && placed[0] != placed[1]); + s.execute("paint.swap", &json!({})).unwrap(); + let (faces2, edges2) = part_looks(&s, g); + assert!(faces2.iter().all(|f| f.fill_paint() == Paint::solid(Color::BLACK))); + assert!(edges2.iter().all(|e| matches!(e.stroke_paint(), Paint::Gradient(gr) if gr.geom.is_none() && gr.freeform.is_none()))); + // A freeform gradient's points belong to its face: faces with freeform fills keep their paint, in no undo step. + s.execute("paint.setFill", &json!({"gradient": {"kind": "freeform"}})).unwrap(); + assert!( + part_looks(&s, g) + .0 + .iter() + .all(|f| matches!(f.fill_paint(), Paint::Gradient(gr) if gr.gradient.kind == vectorcraft_color::GradientKind::Freeform)) + ); + let looks = part_looks(&s, g); + let depth = history_state(&s).0; + s.execute("paint.swap", &json!({})).unwrap(); + assert_eq!(part_looks(&s, g), looks); + assert_eq!(history_state(&s).0, depth); + // A group with edges and no faces keeps its paint. + let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 300, "x2": 100, "y2": 300})).unwrap()["id"].as_u64().unwrap()); + let edges_only = NodeId(s.execute("livePaint.make", &json!({"ids": [line.0]})).unwrap()["id"].as_u64().unwrap()); + assert!(part_looks(&s, edges_only).0.is_empty()); + s.execute("select.set", &json!({"ids": [edges_only.0]})).unwrap(); + let looks = part_looks(&s, edges_only); + s.execute("paint.swap", &json!({})).unwrap(); + assert_eq!(part_looks(&s, edges_only), looks); +} + +/// Default Fill and Stroke on a whole selected Live Paint group leaves its faces with no fill and +/// gives its edges a 0.5 pt black stroke, and new art takes the same; other art selected with it +/// takes the white fill and 1 pt black stroke. +#[test] +fn live_paint_group_default_clears_the_faces_and_gives_the_edges_a_thin_black_stroke() { + let mut s = session(); + let g = live(&mut s); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + let sources0 = sources_looks(&s, g); + s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap(); + s.execute("paint.default", &json!({})).unwrap(); + let (faces, edges) = part_looks(&s, g); + assert!(faces.iter().all(|f| f.fill_paint().is_none() && f.stroke_paint().is_none())); + assert!(edges.iter().all(|e| e.stroke_paint() == Paint::solid(Color::BLACK) && e.stroke_width() == 0.5 && e.fill_paint().is_none())); + assert_eq!(sources_looks(&s, g), sources0); + assert_eq!((s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width), (Paint::None, Paint::solid(Color::BLACK), 0.5)); + let p = s.execute("paint.proxies", &json!({})).unwrap(); + assert_eq!((p["fillMixed"].clone(), p["strokeMixed"].clone()), (json!(false), json!(false))); + // The next shape drawn has no fill and a 0.5 pt black stroke. + let next = rect(&mut s, 400.0, 0.0, 50.0, 50.0); + let look = node(&s, next).appearance.clone(); + assert!(!look.has_visible_fill()); + assert_eq!((look.stroke_paint(), look.stroke_width()), (Paint::solid(Color::BLACK), 0.5)); + // With a plain rectangle selected too, the rectangle and new art take the white fill and 1 pt black stroke. + let r = rect(&mut s, 300.0, 0.0, 50.0, 50.0); + s.execute("paint.setFill", &json!({"ids": [r.0], "color": "#00ff00"})).unwrap(); + s.execute("select.set", &json!({"ids": [g.0, r.0]})).unwrap(); + s.execute("paint.default", &json!({})).unwrap(); + assert_eq!(node(&s, r).appearance.fill_paint(), Paint::solid(Color::WHITE)); + assert_eq!(part_looks(&s, g), (faces.clone(), edges.clone())); + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::solid(Color::WHITE), 1.0)); + // A redefined Default Graphic Style goes to other art; the parts still take no fill and a 0.5 pt black stroke. + s.execute("select.set", &json!({"ids": [r.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + s.execute("graphicStyle.redefine", &json!({"name": "Default Graphic Style"})).unwrap(); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 3})).unwrap(); + s.execute("select.set", &json!({"ids": [g.0, r.0]})).unwrap(); + s.execute("paint.default", &json!({})).unwrap(); + assert_eq!(part_looks(&s, g), (faces, edges), "the parts do not take the redefined style"); + assert_eq!(node(&s, r).appearance.fill_paint(), Paint::solid(Color::from_hex("#00ff00").unwrap())); +} + +/// Invert on a whole selected Live Paint group recolors its faces' fills and leaves its edges and +/// hidden source paths as they are. +#[test] +fn live_paint_group_invert_recolors_the_faces_fill() { + let mut s = session(); + let g = live(&mut s); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let sources0 = sources_looks(&s, g); + let (_, edges0) = part_looks(&s, g); + s.execute("paint.invert", &json!({"stroke": false})).unwrap(); + let (faces, edges) = part_looks(&s, g); + assert!(faces.iter().all(|f| f.fill_paint() == Paint::solid(Color::rgb(0.0, 1.0, 1.0)))); + assert_eq!(edges, edges0); + assert_eq!(sources_looks(&s, g), sources0); + // The same with `target: "contents"`, for the stroke. + s.execute("paint.invert", &json!({"stroke": true, "target": "contents"})).unwrap(); + let (faces1, edges1) = part_looks(&s, g); + assert_eq!(faces1, faces); + assert!(edges1.iter().all(|e| e.stroke_paint() == Paint::solid(Color::WHITE))); + assert_eq!(sources_looks(&s, g), sources0); + // A gradient edit of the fill goes to the faces only. + s.execute("paint.setFill", &json!({"gradient": {}})).unwrap(); + s.execute("paint.editGradient", &json!({"stroke": false, "angle": 45})).unwrap(); + let (faces2, edges2) = part_looks(&s, g); + assert!(faces2.iter().all(|f| matches!(f.fill_paint(), Paint::Gradient(_)))); + assert_eq!(edges2, edges1, "edges take no fill gradient"); + assert_eq!(sources_looks(&s, g), sources0); + // Selecting a Live Paint group with edges and no faces gives new art its edges' stroke. + let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 300, "x2": 100, "y2": 300})).unwrap()["id"].as_u64().unwrap()); + let edges_only = NodeId(s.execute("livePaint.make", &json!({"ids": [line.0]})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setStroke", &json!({"ids": [edges_only.0], "color": "#00ff00"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.paint.stroke = Paint::None; + s.execute("select.set", &json!({"ids": [edges_only.0]})).unwrap(); + assert_eq!(s.paint.stroke, Paint::solid(Color::from_hex("#00ff00").unwrap())); +} + +/// A gradient vector or freeform point edit of a whole selected Live Paint group's fill changes its +/// faces' gradients and leaves its edges and hidden source paths as they are. +#[test] +fn live_paint_group_gradient_vector_and_freeform_edits_change_its_faces() { + let mut s = session(); + let g = live(&mut s); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("paint.setFill", &json!({"gradient": {}})).unwrap(); + let sources0 = sources_looks(&s, g); + let (_, edges0) = part_looks(&s, g); + let face_ids: Vec = vectorcraft_tools::builder::faces(&node(&s, g)).iter().map(|f| f.id.0).collect(); + let r = s.execute("paint.setGradientGeom", &json!({"stroke": false, "start": [0, 0], "end": [100, 0]})).unwrap(); + let mut changed: Vec = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + changed.sort_unstable(); + let mut faces = face_ids.clone(); + faces.sort_unstable(); + assert_eq!(changed, faces, "only the faces take the vector"); + assert_eq!(part_looks(&s, g).1, edges0); + assert_eq!(sources_looks(&s, g), sources0); + s.execute("paint.setFill", &json!({"gradient": {"kind": "freeform"}})).unwrap(); + s.execute("paint.freeform.addPoint", &json!({"stroke": false, "at": [25, 50], "color": "#00ff00"})).unwrap(); + assert!(part_looks(&s, g).0.iter().all(|f| matches!(f.fill_paint(), Paint::Gradient(gr) if gr.freeform.is_some()))); + assert_eq!(part_looks(&s, g).1, edges0); + assert_eq!(sources_looks(&s, g), sources0); +} + +/// The Live Paint rules stop where a paint command stops: a Live Paint group in a compound shape or +/// a blend keeps its parts' paint when the compound shape or blend takes the default, Invert +/// remembers the faces' color the proxy shows, and a Live Paint group without faces lets the Fill +/// proxy show the next selected object's fill, while an empty plain group does not. +#[test] +fn live_paint_group_rules_stop_where_paint_commands_stop() { + let mut s = session(); + let g = live(&mut s); + let looks = part_looks(&s, g); + let r = rect(&mut s, 300.0, 0.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [g.0, r.0]})).unwrap(); + let c = NodeId(s.execute("object.compoundShape.make", &json!({"mode": "add"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); + s.execute("paint.default", &json!({})).unwrap(); + s.execute("paint.swap", &json!({})).unwrap(); + assert_eq!(part_looks(&s, g), looks, "a compound shape's member keeps its paint"); + s.execute("paint.default", &json!({"ids": [c.0, g.0]})).unwrap(); + assert_eq!(part_looks(&s, g), looks, "a compound shape's member given as well keeps its paint"); + // Given alone, the member is a Live Paint group: a fill paints its faces and leaves its edges. + s.execute("paint.setFill", &json!({"ids": [g.0], "color": "#ff00ff"})).unwrap(); + let (faces, edges) = part_looks(&s, g); + assert!(faces.iter().all(|f| f.fill_paint() == Paint::solid(Color::from_hex("#ff00ff").unwrap()))); + assert_eq!(edges, looks.1, "the edges of a member given alone take no fill"); + + // A Live Paint group selected with one of its edges: the edge counts with the group. + let mut s = session(); + let g = live(&mut s); + let edge = vectorcraft_tools::builder::edges(&node(&s, g))[0].id; + s.execute("select.set", &json!({"ids": [g.0, edge.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + assert_eq!(s.execute("paint.proxies", &json!({})).unwrap()["fillMixed"], false); + assert!(node(&s, edge).appearance.fill_paint().is_none(), "an edge selected with its group takes no fill"); + // The same for an edge given in `ids` with its group. + s.execute("paint.setFill", &json!({"ids": [g.0, edge.0], "color": "#0000ff"})).unwrap(); + assert!(node(&s, edge).appearance.fill_paint().is_none(), "an edge given with its group takes no fill"); + + // The same for a blend's key. + let mut s = session(); + let g = live(&mut s); + let looks = part_looks(&s, g); + let r = rect(&mut s, 300.0, 0.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [g.0, r.0]})).unwrap(); + let b = NodeId(s.execute("object.blend.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("paint.default", &json!({})).unwrap(); + s.execute("paint.swap", &json!({})).unwrap(); + assert_eq!(part_looks(&s, g), looks, "a blend's key keeps its paint"); + + // A Live Paint group inside a selected group: Invert recolors its faces' fills only. + let mut s = session(); + let g = live(&mut s); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let sources0 = sources_looks(&s, g); + let (_, edges0) = part_looks(&s, g); + s.execute("object.group", &json!({"ids": [g.0]})).unwrap(); + s.execute("paint.invert", &json!({"stroke": false})).unwrap(); + assert!(part_looks(&s, g).0.iter().all(|f| f.fill_paint() == Paint::solid(Color::rgb(0.0, 1.0, 1.0)))); + assert_eq!(part_looks(&s, g).1, edges0); + assert_eq!(sources_looks(&s, g), sources0); + + let mut s = session(); + let g = live(&mut s); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + s.edit("t", |d, _| { + d.node_mut(g).unwrap().appearance.set_fill(Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + Ok(()) + }) + .unwrap(); + s.execute("paint.invert", &json!({"stroke": false})).unwrap(); + // Like any group's, the group's own row is recolored too; the color remembered is the faces' one the proxy shows. + assert_eq!(node(&s, g).appearance.fill_paint(), Paint::solid(Color::rgb(1.0, 1.0, 0.0))); + assert!(part_looks(&s, g).0.iter().all(|f| f.fill_paint() == Paint::solid(Color::rgb(0.0, 1.0, 1.0)))); + assert_eq!(s.last_solid, Color::rgb(0.0, 1.0, 1.0)); + + let mut s = session(); + let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 100, "y2": 0})).unwrap()["id"].as_u64().unwrap()); + let edges_only = NodeId(s.execute("livePaint.make", &json!({"ids": [line.0]})).unwrap()["id"].as_u64().unwrap()); + assert!(part_looks(&s, edges_only).0.is_empty()); + let r = rect(&mut s, 300.0, 0.0, 50.0, 50.0); + set_fill(&mut s, r, Color::from_hex("#00ff00").unwrap()); + s.execute("select.set", &json!({"ids": [edges_only.0, r.0]})).unwrap(); + let p = s.execute("paint.proxies", &json!({})).unwrap(); + assert_eq!(p["fill"], serde_json::to_value(Paint::solid(Color::from_hex("#00ff00").unwrap())).unwrap()); + // The edges-only group shows its edges' stroke in the Stroke panel. + let edge_width = part_looks(&s, edges_only).1[0].stroke_width(); + assert_eq!(s.shown_stroke().map(|st| st.width), Some(edge_width)); + + // Any other object with nothing painted in it first in the selection (a group left empty) shows + // the defaults for new art, not the next object's paint. + let inner = rect(&mut s, 0.0, 300.0, 50.0, 50.0); + let empty = NodeId(s.execute("object.group", &json!({"ids": [inner.0]})).unwrap()["id"].as_u64().unwrap()); + s.edit("t", |d, _| { + d.children_mut(Some(empty)).unwrap().clear(); + Ok(()) + }) + .unwrap(); + s.execute("stroke.set", &json!({"ids": [r.0], "weight": 7})).unwrap(); + s.paint.fill = Paint::None; + s.execute("select.set", &json!({"ids": [empty.0, r.0]})).unwrap(); + let p = s.execute("paint.proxies", &json!({})).unwrap(); + assert_eq!(p["fill"], serde_json::to_value(Paint::None).unwrap()); + assert!(s.shown_stroke().is_none()); +} + +/// Stroke panel edits of a whole selected Live Paint group (a weight, a step up or down, options) +/// change its edges and leave its faces as they are, and the panel shows the edges' stroke. +#[test] +fn live_paint_group_stroke_panel_edits_change_its_edges() { + let mut s = session(); + let g = live(&mut s); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + let (faces0, edges0) = part_looks(&s, g); + assert_eq!(s.execute("stroke.set", &json!({"weight": 5})).unwrap()["objects"], edges0.len()); + let (faces1, edges1) = part_looks(&s, g); + assert_eq!(faces1, faces0, "faces take no stroke weight"); + assert!(edges1.iter().all(|e| e.stroke().is_some_and(|st| st.width == 5.0))); + assert_eq!(s.shown_stroke().map(|st| st.width), Some(5.0)); + assert!(!s.doc().unwrap().stroke_mixed().weight); + s.execute("stroke.weightUp", &json!({})).unwrap(); + s.execute("stroke.set", &json!({"cap": "round"})).unwrap(); + let (faces2, edges2) = part_looks(&s, g); + assert_eq!(faces2, faces0, "faces take no stroke step or cap"); + assert!(edges2.iter().all(|e| e.stroke().is_some_and(|st| st.width == 6.0 && st.cap == LineCap::Round))); + // A stroke on the faces (from a file, say) leaves the panel showing the edges' stroke. + let face_ids: Vec = vectorcraft_tools::builder::faces(&node(&s, g)).iter().map(|f| f.id).collect(); + s.edit("t", |d, _| { + for id in &face_ids { + let face = d.node_mut(*id).unwrap(); + face.appearance.set_stroke(Paint::solid(Color::BLACK)); + face.appearance.stroke_at_mut(None).unwrap().width = 2.0; + } + Ok(()) + }) + .unwrap(); + assert_eq!(s.shown_stroke().map(|st| st.width), Some(6.0)); + assert!(!s.doc().unwrap().stroke_mixed().weight); + // A face selected with its group counts with the group, whose stroke is its edges'. + s.execute("select.set", &json!({"ids": [g.0, face_ids[0].0]})).unwrap(); + assert!(!s.doc().unwrap().stroke_mixed().weight); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + // A stroke row on the group itself: a weight still goes to the edges the panel shows. + s.edit("t", |d, _| { + d.node_mut(g).unwrap().appearance.set_stroke(Paint::solid(Color::BLACK)); + Ok(()) + }) + .unwrap(); + s.execute("stroke.set", &json!({"weight": 3})).unwrap(); + assert!(part_looks(&s, g).1.iter().all(|e| e.stroke_width() == 3.0)); + assert_eq!(node(&s, g).appearance.stroke().map(|st| st.width), Some(1.0)); +} + +/// A selected Live Paint group with no part of the edited kind is still a selection: a stroke edit +/// of a group without edges, or a fill gradient edit of a group without faces, changes nothing and +/// leaves the settings for new art as they are. +#[test] +fn live_paint_group_without_parts_of_the_edited_kind_leaves_new_art_alone() { + let mut s = session(); + let g = live(&mut s); + let edge_ids: Vec = vectorcraft_tools::builder::edges(&node(&s, g)).iter().map(|e| e.id).collect(); + s.edit("t", |d, _| { + d.children_mut(Some(g)).unwrap().retain(|c| !edge_ids.contains(&c.id)); + Ok(()) + }) + .unwrap(); + assert!(part_looks(&s, g).1.is_empty()); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + let looks = part_looks(&s, g); + let (paint0, stroke0) = (s.paint.clone(), s.new_art_stroke()); + s.execute("stroke.set", &json!({"cap": "round"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 4})).unwrap(); + s.execute("stroke.weightUp", &json!({})).unwrap(); + s.execute("stroke.setAdvanced", &json!({"arrowScale": [200, 150]})).unwrap(); + assert_eq!((s.paint.clone(), s.new_art_stroke()), (paint0, stroke0), "new art keeps its stroke"); + assert_eq!(part_looks(&s, g), looks); + + let mut s = session(); + let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 100, "y2": 0})).unwrap()["id"].as_u64().unwrap()); + let edges_only = NodeId(s.execute("livePaint.make", &json!({"ids": [line.0]})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [edges_only.0]})).unwrap(); + let looks = part_looks(&s, edges_only); + let paint0 = s.paint.clone(); + s.execute("paint.editGradient", &json!({"stroke": false, "angle": 45})).unwrap(); + assert_eq!(s.paint, paint0, "new art keeps its fill"); + assert_eq!(part_looks(&s, edges_only), looks); +} + /// A Live Paint group of 50 pt squares side by side, 50 pt tall, with their left sides at each of /// `xs`. fn live_squares(s: &mut Session, xs: &[f64]) -> NodeId { @@ -5027,6 +5717,73 @@ fn live_paint_does_not_count_art_named_like_its_parts() { } } +/// A path drawn in an isolated Live Paint group can't be named Face or Edge, the names of the +/// group's faces and edges: `object.setProps` and `layer.setProps` return an error and rename +/// nothing, so Gap Options and a path dragged into the group keep the path. A face keeps its name. +#[test] +fn live_paint_refuses_part_names_for_paths_drawn_in_it() { + use vectorcraft_tools::builder::{EDGE_NAME, FACE_NAME, faces}; + let mut s = session(); + let g = live(&mut s); + let face = faces(&node(&s, g))[0].id; + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let a = line_across(&mut s, 50.0); + // Hidden, the path stays in the group as drawn when isolation mode ends. + s.execute("object.setProps", &json!({"id": a.0, "visible": false})).unwrap(); + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + for name in [FACE_NAME, EDGE_NAME] { + let calls = [ + ("object.setProps", json!({"id": a.0, "name": name})), + ("layer.setProps", json!({"id": a.0, "name": name})), + ("layer.setProps", json!({"ids": [face.0, a.0], "name": name})), + ]; + for (c, p) in calls { + let err = s.execute(c, &p).unwrap_err().to_string(); + assert!(err.contains("give the path another name"), "{c} {p}: {err}"); + } + } + assert!(s.doc().unwrap().doc == before.0, "nothing was renamed"); + assert_eq!(s.doc().unwrap().history.undo.len(), before.1); + s.execute("layer.setProps", &json!({"id": face.0, "name": FACE_NAME})).unwrap(); + s.execute("object.exitIsolation", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "the hidden path stays in the group"); + s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "Gap Options keeps the path"); + let b = line_to_right_face(&mut s, 30.0); + s.execute("layer.move", &json!({"ids": [b.0], "target": g.0, "place": "inside"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "a path dragged in keeps it"); + assert_eq!(faces(&node(&s, g)).len(), 5); +} + +/// A path pasted into an isolated Live Paint group under the name of a face or an edge loses the +/// name, so Gap Options keeps it and it joins the group's paths when isolation mode ends. +#[test] +fn live_paint_paste_clears_part_names() { + use vectorcraft_tools::builder::{EDGE_NAME, FACE_NAME, faces, sources}; + for name in [FACE_NAME, EDGE_NAME] { + let mut s = session(); + let g = live(&mut s); + let r = rect(&mut s, 20.0, 40.0, 60.0, 20.0); + s.execute("object.setProps", &json!({"id": r.0, "name": name})).unwrap(); + s.execute("select.set", &json!({"ids": [r.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + s.execute("edit.pasteInPlace", &json!({})).unwrap(); + let pasted = s.doc().unwrap().selection.objects.clone(); + assert_eq!(pasted.len(), 1); + let d = &s.doc().unwrap().doc; + assert_eq!(d.parent_of(pasted[0]), Some(g), "{name}: the paste goes into the group"); + assert_eq!(d.node(pasted[0]).unwrap().name, None, "{name}: the paste loses the name"); + assert_eq!(d.node(r).unwrap().name.as_deref(), Some(name), "the path outside keeps its name"); + s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(pasted[0]), Some(g), "{name}: Gap Options keeps the paste"); + s.execute("object.exitIsolation", &json!({})).unwrap(); + let n = node(&s, g); + assert_eq!(s.doc().unwrap().doc.parent_of(pasted[0]), Some(sources(&n).unwrap().id), "{name}: the paste joined"); + assert!(faces(&n).len() > 3); + } +} + /// With Real-time Drawing and Editing off, a rectangle still being drawn in a Live Paint group /// isolated in a pattern tile is drawn first when Exit Isolation Mode leaves pattern editing, and /// joins the group with the tile saved. @@ -5098,6 +5855,399 @@ fn live_paint_isolation_adds_a_drawn_group_isolated_inside_it() { } } +/// With Live Paint group `inner` made in isolated Live Paint group `outer` and then isolated itself, +/// leaving both levels (`object.exitIsolation`, or `object.isolate` on the layer) adds the path drawn +/// in `inner` to it and then `inner` and the path drawn directly in `outer` to `outer`, one undo step +/// each. Isolating `outer` from `inner` adds only `inner`'s drawn path, and `outer` keeps its own. +#[test] +fn live_paint_isolation_merges_nested_live_paint_groups_it_leaves() { + use vectorcraft_tools::builder::{faces, sources}; + for to in ["exit", "layer", "outer"] { + let mut s = session(); + let outer = live(&mut s); + let layer = s.doc().unwrap().doc.parent_of(outer).unwrap(); + s.execute("object.isolate", &json!({"id": outer.0})).unwrap(); + let a = line_across(&mut s, 50.0); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(outer)); + let inner = live(&mut s); + assert_eq!(s.doc().unwrap().doc.parent_of(inner), Some(outer), "the inner group is drawn in the outer one"); + s.execute("object.isolate", &json!({"id": inner.0})).unwrap(); + let b = line_across(&mut s, 30.0); + assert_eq!(s.doc().unwrap().doc.parent_of(b), Some(inner)); + let steps = s.doc().unwrap().history.undo.len(); + match to { + "exit" => s.execute("object.exitIsolation", &json!({})).unwrap(), + "layer" => s.execute("object.isolate", &json!({"id": layer.0})).unwrap(), + _ => s.execute("object.isolate", &json!({"id": outer.0})).unwrap(), + }; + let d = &s.doc().unwrap().doc; + if to == "outer" { + assert_eq!(s.doc().unwrap().isolation, Some(outer)); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "only the inner group's path joins"); + let n = node(&s, inner); + assert_eq!(d.parent_of(b), Some(sources(&n).unwrap().id), "the path drawn in the inner group joined it"); + assert_eq!(d.parent_of(inner), Some(outer), "the inner group stays drawn in the outer one"); + assert_eq!(d.parent_of(a), Some(outer), "the path drawn in the outer group stays as drawn"); + continue; + } + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 2, "{to}: one undo step for each group"); + assert!(d.node(inner).is_none(), "{to}: the inner group joined the outer one"); + let n = node(&s, outer); + let src = sources(&n).unwrap().id; + assert_eq!(d.parent_of(a), Some(src), "{to}: the path drawn in the outer group joined it"); + assert!(d.ancestry(b).unwrap().contains(&src), "{to}: the path drawn in the inner group is among the outer group's paths"); + assert!(n.children().unwrap().iter().all(|c| c.id == src || c.path_data().is_some()), "{to}: only parts are left in the outer group"); + assert!(faces(&n).len() > 3, "{to}: the added paths cut the outer group's faces"); + if to == "exit" { + assert_eq!(s.doc().unwrap().selection.objects, vec![outer]); + } + } +} + +/// A line from left of the [`live`] group to its right face, so it cuts the two faces left of it. +fn line_to_right_face(s: &mut Session, y: f64) -> NodeId { + let r = s.execute("path.create", &json!({"anchors": [{"x": -10, "y": y}, {"x": 105, "y": y}]})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) +} + +fn undo_label(s: &Session) -> Option { + s.doc().unwrap().history.undo.last().map(|e| e.label.clone()) +} + +/// Paths dragged into a Live Paint group in the Layers panel join its paths as Live Paint › Merge +/// adds them: they go among its sources and cut the faces they cross, a painted face they do not +/// cross keeps its fill, and the drop is one "Merge Live Paint" undo step that selects the group. +#[test] +fn layers_drag_adds_paths_to_a_live_paint_group() { + use vectorcraft_tools::builder::{face_at, faces, sources}; + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let mut s = session(); + let g = live(&mut s); + s.execute("livePaint.fill", &json!({"group": g.0, "point": [125, 50], "color": "#00ff00"})).unwrap(); + let layer = s.doc().unwrap().doc.parent_of(g); + let (a, b) = (line_to_right_face(&mut s, 30.0), line_to_right_face(&mut s, 70.0)); + assert_eq!(s.doc().unwrap().doc.parent_of(a), layer); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute("layer.move", &json!({"ids": [a.0, b.0], "target": g.0, "place": "inside"})).unwrap(); + assert_eq!(r["ids"], json!([g.0]), "the rows that joined are listed as the group"); + let d = s.doc().unwrap(); + assert_eq!(d.history.undo.len(), steps + 1, "both paths join in one undo step"); + assert_eq!(undo_label(&s).as_deref(), Some("Merge Live Paint")); + assert_eq!(s.doc().unwrap().selection.objects, vec![g]); + let n = node(&s, g); + let src = sources(&n).unwrap(); + assert_eq!(src.children().unwrap().len(), 4); + for id in [a, b] { + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(src.id), "{id} joined the sources"); + } + assert_eq!(faces(&n).len(), 7, "two lines cut each of the two faces they cross in three"); + assert_eq!(face_at(&n, Point::new(125.0, 50.0)).unwrap().appearance.fill_paint(), green, "the face the lines do not cross keeps its fill"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(faces(&node(&s, g)).len(), 3); + for id in [a, b] { + assert_eq!(s.doc().unwrap().doc.parent_of(id), layer, "Undo puts {id} back where it was"); + } + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(faces(&node(&s, g)).len(), 7); +} + +/// A path named like a Live Paint group's sources group joins the group when it is dragged in, in +/// front of the sources group or behind it: the group keeps its own sources group and the path +/// goes among its paths. +#[test] +fn layers_drag_of_a_path_named_like_the_sources_group_joins_a_live_paint_group() { + use vectorcraft_tools::builder::{SOURCES_NAME, faces, sources}; + for index in [0, 99] { + let mut s = session(); + let g = live(&mut s); + let a = line_to_right_face(&mut s, 30.0); + s.execute("object.setProps", &json!({"id": a.0, "name": SOURCES_NAME})).unwrap(); + s.execute("node.move", &json!({"id": a.0, "parent": g.0, "index": index})).unwrap(); + assert_eq!(undo_label(&s).as_deref(), Some("Merge Live Paint"), "index {index}"); + let n = node(&s, g); + let src = sources(&n).unwrap(); + assert!(src.children().is_some(), "index {index}: the sources group is a group"); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(src.id), "index {index}: the path joined the sources"); + assert_eq!(faces(&n).len(), 5, "index {index}"); + } +} + +/// An object drawn in a Live Paint group and named like its sources group can be moved ahead of the +/// sources group: the group keeps its own sources group and stays a Live Paint group. +#[test] +fn layers_reorder_of_an_object_named_like_the_sources_group_keeps_the_live_paint_group() { + use vectorcraft_tools::builder::{SOURCES_NAME, is_live_paint, sources}; + let mut s = session(); + let g = live(&mut s); + let real = sources(&node(&s, g)).unwrap().id; + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let a = line_across(&mut s, 50.0); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g)); + s.execute("object.setProps", &json!({"id": a.0, "name": SOURCES_NAME})).unwrap(); + s.execute("node.move", &json!({"id": a.0, "parent": g.0, "index": 0})).unwrap(); + let n = node(&s, g); + assert!(is_live_paint(&n)); + assert_eq!(sources(&n).unwrap().id, real); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "the object stays where it was drawn"); +} + +/// A path named `Face` that is dragged into a Live Paint group is not one of its faces: the face it +/// covers keeps its own fill. +#[test] +fn layers_drag_of_a_path_named_face_does_not_repaint_the_group() { + use vectorcraft_tools::builder::{face_at, faces}; + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let mut s = session(); + let g = live(&mut s); + s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "color": "#00ff00"})).unwrap(); + let a = rect(&mut s, 0.0, 0.0, 50.0, 100.0); + set_fill(&mut s, a, Color::rgb(0.0, 0.0, 1.0)); + s.execute("object.setProps", &json!({"id": a.0, "name": "Face"})).unwrap(); + s.execute("node.move", &json!({"id": a.0, "parent": g.0, "index": 99})).unwrap(); + let n = node(&s, g); + assert_eq!(faces(&n).len(), 3); + assert_eq!(face_at(&n, Point::new(25.0, 50.0)).unwrap().appearance.fill_paint(), green); +} + +/// An Alt-drag into a Live Paint group adds a copy and leaves the path where it was; a drop above +/// one of the group's faces, and `node.move` into the group, add the path the same way. +#[test] +fn layers_drag_copy_and_drop_beside_a_part_add_to_a_live_paint_group() { + use vectorcraft_tools::builder::{faces, sources}; + let mut s = session(); + let g = live(&mut s); + let layer = s.doc().unwrap().doc.parent_of(g); + let a = line_to_right_face(&mut s, 30.0); + s.execute("layer.move", &json!({"ids": [a.0], "target": g.0, "copy": true})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(a), layer, "the path itself stays"); + let n = node(&s, g); + assert_eq!(faces(&n).len(), 5); + let src = sources(&n).unwrap().children().unwrap().clone(); + assert_eq!(src.len(), 3); + assert!(src.iter().all(|c| c.id != a), "a copy joined"); + let (face, other_face) = (faces(&n)[0].id, faces(&n)[1].id); + let b = line_to_right_face(&mut s, 70.0); + // A face dragged along is made again with the others, so only the group is listed. + let r = s.execute("layer.move", &json!({"ids": [b.0, other_face.0], "target": face.0, "place": "above"})).unwrap(); + assert_eq!(r["ids"], json!([g.0])); + assert_eq!(s.doc().unwrap().layer_rows, vec![g]); + let n = node(&s, g); + assert_eq!(s.doc().unwrap().doc.parent_of(b), Some(sources(&n).unwrap().id), "a drop beside a face joins"); + assert_eq!(faces(&n).len(), 7); + let c = line_to_right_face(&mut s, 50.0); + s.execute("node.move", &json!({"id": c.0, "parent": g.0, "index": 0})).unwrap(); + assert_eq!(undo_label(&s).as_deref(), Some("Merge Live Paint")); + let n = node(&s, g); + assert_eq!(s.doc().unwrap().doc.parent_of(c), Some(sources(&n).unwrap().id), "node.move into the group joins"); + assert_eq!(faces(&n).len(), 9); +} + +/// Dragging type, or type with a path, into a Live Paint group is refused with Make's message and +/// moves nothing, as Merge refuses it; a drop beside the group is an ordinary move. +#[test] +fn layers_drag_refuses_type_into_a_live_paint_group() { + use vectorcraft_tools::builder::faces; + let mut s = session(); + let g = live(&mut s); + let layer = s.doc().unwrap().doc.parent_of(g); + let a = line_to_right_face(&mut s, 30.0); + let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap()); + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + for p in [json!({"ids": [a.0, text.0], "target": g.0}), json!({"ids": [text.0], "target": g.0, "copy": true})] { + let err = s.execute("layer.move", &p).unwrap_err().to_string(); + assert!(err.contains("Live Paint takes paths and compound paths"), "{err}"); + } + assert!(s.execute("node.move", &json!({"id": text.0, "parent": g.0, "index": 0})).is_err()); + assert!(s.doc().unwrap().doc == before.0, "nothing moved"); + assert_eq!(s.doc().unwrap().history.undo.len(), before.1); + s.execute("layer.move", &json!({"ids": [a.0, text.0], "target": g.0, "place": "above"})).unwrap(); + assert_eq!(undo_label(&s).as_deref(), Some("Move Rows")); + assert_eq!(s.doc().unwrap().doc.parent_of(text), layer); + assert_eq!(faces(&node(&s, g)).len(), 3); +} + +/// A path dragged out of a Live Paint group's sources leaves its faces and edges: the group makes +/// them again from the paths left, and with none left it has no faces until a path joins it again. +/// Reordering the sources, or the group's own faces, makes nothing again. +#[test] +fn layers_drag_out_of_a_live_paint_group_makes_its_faces_again() { + use vectorcraft_tools::builder::{faces, sources}; + let mut s = session(); + let g = live(&mut s); + let layer = s.doc().unwrap().doc.parent_of(g).unwrap(); + let n = node(&s, g); + let src: Vec = sources(&n).unwrap().children().unwrap().iter().map(|c| c.id).collect(); + let face_ids: Vec = faces(&n).iter().map(|f| f.id).collect(); + s.execute("layer.move", &json!({"ids": [src[0].0], "target": src[1].0, "place": "above"})).unwrap(); + s.execute("layer.move", &json!({"ids": [face_ids[0].0], "target": face_ids[2].0, "place": "above"})).unwrap(); + let n = node(&s, g); + assert_eq!(sources(&n).unwrap().children().unwrap().len(), 2, "a reorder keeps the sources"); + let mut now: Vec = faces(&n).iter().map(|f| f.id).collect(); + now.sort(); + let mut was = face_ids.clone(); + was.sort(); + assert_eq!(now, was, "and the faces"); + s.execute("layer.move", &json!({"ids": [src[0].0], "target": layer.0})).unwrap(); + assert_eq!(undo_label(&s).as_deref(), Some("Move Rows")); + let n = node(&s, g); + assert_eq!(s.doc().unwrap().doc.parent_of(src[0]), Some(layer)); + assert_eq!(sources(&n).unwrap().children().unwrap().len(), 1); + assert_eq!(faces(&n).len(), 1, "one rectangle left"); + s.execute("node.move", &json!({"id": src[1].0, "parent": layer.0, "index": 0})).unwrap(); + let n = node(&s, g); + assert!(vectorcraft_tools::builder::is_live_paint(&n), "the group stays a Live Paint group"); + assert!(sources(&n).unwrap().children().unwrap().is_empty()); + assert!(faces(&n).is_empty() && vectorcraft_tools::builder::edges(&n).is_empty()); + s.execute("layer.move", &json!({"ids": [src[0].0], "target": g.0})).unwrap(); + assert_eq!(faces(&node(&s, g)).len(), 1, "a path joins the empty group"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(faces(&node(&s, g)).len(), 1); +} + +/// A path dragged from a Live Paint group's sources into the group itself stays among its paths, +/// and the faces it bounds keep their paint, also when it is the group's only path. +#[test] +fn layers_drag_a_source_path_into_its_own_live_paint_group_keeps_the_paint() { + use vectorcraft_tools::builder::{face_at, faces, sources}; + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let blue = Paint::solid(Color::from_hex("#0000ff").unwrap()); + let mut s = session(); + let g = live(&mut s); + let layer = s.doc().unwrap().doc.parent_of(g).unwrap(); + s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "color": "#00ff00"})).unwrap(); + let src: Vec = sources(&node(&s, g)).unwrap().children().unwrap().iter().map(|c| c.id).collect(); + s.execute("layer.move", &json!({"ids": [src[0].0], "target": g.0, "place": "inside"})).unwrap(); + let n = node(&s, g); + assert_eq!(s.doc().unwrap().doc.parent_of(src[0]), Some(sources(&n).unwrap().id), "the path stays among the group's paths"); + assert_eq!(faces(&n).len(), 3); + assert_eq!(face_at(&n, Point::new(25.0, 50.0)).unwrap().appearance.fill_paint(), green, "the face it bounds keeps its fill"); + s.execute("layer.move", &json!({"ids": [src[1].0], "target": layer.0})).unwrap(); + s.execute("livePaint.fill", &json!({"group": g.0, "point": [50, 50], "color": "#0000ff"})).unwrap(); + s.execute("layer.move", &json!({"ids": [src[0].0], "target": g.0, "place": "inside"})).unwrap(); + let n = node(&s, g); + assert_eq!(faces(&n).len(), 1); + assert_eq!(face_at(&n, Point::new(50.0, 50.0)).unwrap().appearance.fill_paint(), blue, "the only path's face keeps its fill"); +} + +/// A Live Paint group among another Live Paint group's paths gives it faces and edges: a path +/// dragged into or out of the inner group's paths, or from the outer group's paths into the inner +/// group's, makes the inner group's faces and edges again and then the outer group's. +#[test] +fn layers_drag_into_a_nested_live_paint_group_makes_the_outer_group_again() { + use vectorcraft_tools::builder::{faces, sources}; + let mut s = session(); + let outer = live(&mut s); + let inner = live(&mut s); + let layer = s.doc().unwrap().doc.parent_of(outer).unwrap(); + let first_source = |s: &Session, g: NodeId| sources(&node(s, g)).unwrap().children().unwrap()[0].id; + let into = |s: &mut Session, row: NodeId, g: NodeId| { + let target = first_source(s, g); + s.execute("layer.move", &json!({"ids": [row.0], "target": target.0, "place": "above"})).unwrap(); + }; + into(&mut s, inner, outer); + assert_eq!(s.doc().unwrap().doc.parent_of(inner), Some(sources(&node(&s, outer)).unwrap().id)); + let plain = faces(&node(&s, outer)).len(); + let a = line_to_right_face(&mut s, 30.0); + into(&mut s, a, inner); + assert_eq!(faces(&node(&s, inner)).len(), 5); + let cut = faces(&node(&s, outer)).len(); + assert!(cut > plain, "a path joining the inner group cuts the outer group's faces: {cut} faces, {plain} before"); + s.execute("layer.move", &json!({"ids": [a.0], "target": layer.0})).unwrap(); + assert_eq!(faces(&node(&s, inner)).len(), 3); + assert_eq!(faces(&node(&s, outer)).len(), plain, "a path leaving the inner group leaves the outer group's faces"); + into(&mut s, a, outer); + assert_eq!(faces(&node(&s, outer)).len(), cut); + into(&mut s, a, inner); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(sources(&node(&s, inner)).unwrap().id)); + assert_eq!(faces(&node(&s, inner)).len(), 5); + assert_eq!(faces(&node(&s, outer)).len(), cut, "the outer group is made after the inner one"); +} + +/// A Live Paint group's sources group can't be dragged out of the group, which would leave faces +/// and edges with no paths: the move is refused and changes nothing. A reorder within the group, +/// and a copy dragged out, are allowed. +#[test] +fn layers_drag_keeps_the_sources_group_in_its_live_paint_group() { + use vectorcraft_tools::builder::{faces, is_live_paint, sources}; + let mut s = session(); + let g = live(&mut s); + let layer = s.doc().unwrap().doc.parent_of(g).unwrap(); + let src = sources(&node(&s, g)).unwrap().id; + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let err = s.execute("layer.move", &json!({"ids": [src.0], "target": layer.0})).unwrap_err().to_string(); + assert!(err.contains("sources group stays in the group"), "{err}"); + let err = s.execute("node.move", &json!({"id": src.0, "parent": layer.0, "index": 0})).unwrap_err().to_string(); + assert!(err.contains("sources group stays in the group"), "{err}"); + assert!(s.doc().unwrap().doc == before.0, "nothing moved"); + assert_eq!(s.doc().unwrap().history.undo.len(), before.1); + s.execute("node.move", &json!({"id": src.0, "parent": g.0, "index": 99})).unwrap(); + let n = node(&s, g); + assert!(is_live_paint(&n)); + assert_eq!(sources(&n).unwrap().id, src); + assert_eq!(faces(&n).len(), 3); + s.execute("layer.move", &json!({"ids": [src.0], "target": layer.0, "copy": true})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(src), Some(g), "a copy leaves the sources group where it is"); +} + +/// A shown path dragged into a hidden group among a Live Paint group's paths stops cutting its +/// faces, and dragged back out of it cuts them again. +#[test] +fn layers_drag_into_a_hidden_group_among_the_sources_makes_the_faces_again() { + use vectorcraft_tools::builder::{faces, sources}; + let mut s = session(); + let g = live(&mut s); + let first_source = |s: &Session| sources(&node(s, g)).unwrap().children().unwrap()[0].id; + let a = line_to_right_face(&mut s, 30.0); + let target = first_source(&s); + s.execute("layer.move", &json!({"ids": [a.0], "target": target.0, "place": "above"})).unwrap(); + assert_eq!(faces(&node(&s, g)).len(), 5); + let b = line_to_right_face(&mut s, 70.0); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let hidden = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap(); + let target = first_source(&s); + s.execute("layer.move", &json!({"ids": [hidden.0], "target": target.0, "place": "above"})).unwrap(); + let src = sources(&node(&s, g)).unwrap().id; + assert_eq!(s.doc().unwrap().doc.parent_of(hidden), Some(src)); + assert_eq!(faces(&node(&s, g)).len(), 5, "a hidden group cuts nothing"); + s.execute("layer.move", &json!({"ids": [a.0], "target": hidden.0, "place": "inside"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(hidden)); + assert_eq!(faces(&node(&s, g)).len(), 3, "the path in the hidden group no longer cuts the faces"); + let target = first_source(&s); + s.execute("layer.move", &json!({"ids": [a.0], "target": target.0, "place": "above"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(sources(&node(&s, g)).unwrap().id)); + assert_eq!(faces(&node(&s, g)).len(), 5, "back among the shown paths, it cuts them again"); +} + +/// A Live Paint group with no paths dragged into another one with none joins it: the drop is one +/// "Merge Live Paint" step, and the group stays a Live Paint group with no faces or edges. +#[test] +fn layers_drag_of_an_empty_live_paint_group_into_another_joins_it() { + use vectorcraft_tools::builder::{edges, faces, is_live_paint, sources}; + let mut s = session(); + let empty = |s: &mut Session| { + let g = live(s); + let layer = s.doc().unwrap().doc.parent_of(g).unwrap(); + for p in sources(&node(s, g)).unwrap().children().unwrap().iter().map(|c| c.id).collect::>() { + s.execute("layer.move", &json!({"ids": [p.0], "target": layer.0})).unwrap(); + } + assert!(faces(&node(s, g)).is_empty()); + g + }; + let (g, h) = (empty(&mut s), empty(&mut s)); + let r = s.execute("layer.move", &json!({"ids": [h.0], "target": g.0, "place": "inside"})).unwrap(); + assert_eq!(r["ids"], json!([g.0])); + assert_eq!(undo_label(&s).as_deref(), Some("Merge Live Paint")); + let n = node(&s, g); + assert!(is_live_paint(&n)); + assert!(sources(&n).unwrap().children().unwrap().is_empty()); + assert!(faces(&n).is_empty() && edges(&n).is_empty()); + assert!(s.doc().unwrap().doc.node(h).is_none(), "the dropped group joined"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(h).is_some()); +} + /// Give Live Paint group `g` a lock, hidden state, appearance, knockout, opacity mask and /// graphic style link, and return it as it then is. fn dress_live_group(s: &mut Session, g: NodeId) -> Node { @@ -8241,6 +9391,54 @@ fn image_trace_view_is_stored_kept_and_validated() { assert!(s.execute("imageTrace.setView", &json!({"id": a.0, "view": "outlines"})).is_err()); } +/// The Split view's divider is set with the view, kept when omitted, when tracing again and through +/// save and open, adds no undo step when unchanged and one when changed, and is checked. On screen +/// the source image shows left of it and the result right of it; exports draw the result. +#[test] +fn image_trace_split_view_keeps_and_validates_its_divider() { + let mut s = session(); + let g = disc_on_blue(&mut s); + // The image covers 50 to 250 across; the disc 90 to 210, so the divider moves over the disc. + let r = s.execute("imageTrace.setView", &json!({"view": "split"})).unwrap(); + assert_eq!((r["view"].as_str(), r["split"].as_f64()), (Some("split"), Some(0.5))); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute("imageTrace.setView", &json!({"view": "split", "split": 0.25})).unwrap(); + assert_eq!(r["split"].as_f64(), Some(0.25)); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + assert_eq!(node(&s, g).trace_split(), 0.25); + for same in [json!({"view": "split", "split": 0.25}), json!({"view": "split"})] { + let r = s.execute("imageTrace.setView", &same).unwrap(); + assert_eq!(r["split"].as_f64(), Some(0.25), "{same}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{same}: no undo step"); + } + // Pixels at y = 60 (above the disc): the image's blue left of x = 100, white right of it. + let blue = |p: [u8; 4]| p[0] < 200 && p[2] > 245; + let white = |p: [u8; 4]| p[0] > 245 && p[1] > 245 && p[2] > 245; + let screen = render_doc(&s, true); + assert!(blue(screen.pixel(60, 60)) && blue(screen.pixel(95, 60)), "{:?}", screen.pixel(95, 60)); + assert!(white(screen.pixel(105, 60)) && white(screen.pixel(240, 60)), "{:?}", screen.pixel(105, 60)); + let export = render_doc(&s, false); + assert!(white(export.pixel(60, 60)), "exports draw the tracing result"); + // Another view keeps the divider for when Split is chosen again. + s.execute("imageTrace.setView", &json!({"view": "outlines"})).unwrap(); + assert_eq!(node(&s, g).trace_split(), 0.25); + s.execute("imageTrace.setView", &json!({"view": "split"})).unwrap(); + let g = NodeId(s.execute("imageTrace.make", &json!({"id": g.0, "params": {"ignoreWhite": true, "noise": 30}})).unwrap()["id"].as_u64().unwrap()); + assert_eq!((node(&s, g).trace_view(), node(&s, g).trace_split()), (vectorcraft_doc::TraceView::Split, 0.25), "tracing again"); + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + assert_eq!((back.node(g).unwrap().trace_view(), back.node(g).unwrap().trace_split()), (vectorcraft_doc::TraceView::Split, 0.25)); + // Bad dividers are refused and change nothing. + let steps = s.doc().unwrap().history.undo.len(); + for bad in [json!(-0.1), json!(1.01), json!("0.5"), json!(true), json!([0.5])] { + assert!(s.execute("imageTrace.setView", &json!({"view": "split", "split": bad})).is_err(), "{bad}"); + } + assert_eq!((s.doc().unwrap().history.undo.len(), node(&s, g).trace_split()), (steps, 0.25)); + for edge in [0.0, 1.0] { + s.execute("imageTrace.setView", &json!({"view": "split", "split": edge})).unwrap(); + assert_eq!(node(&s, g).trace_split(), edge); + } +} + #[test] fn image_trace_views_draw_on_screen_only_and_expand_to_the_result() { let mut s = session(); diff --git a/crates/engine/src/tests/compound_shape.rs b/crates/engine/src/tests/compound_shape.rs index 3f027254b0..0057af9253 100644 --- a/crates/engine/src/tests/compound_shape.rs +++ b/crates/engine/src/tests/compound_shape.rs @@ -696,3 +696,108 @@ fn a_locked_or_hidden_layer_keeps_the_isolated_compound_shape_from_clicks() { assert!(selected(&s).is_empty(), "{prop}: nor by a marquee"); } } + +/// A straight line, closed as a compound shape closes open paths, encloses no area, so it +/// contributes no area to the shape: Make Compound Shape still makes it, in any mode and at any +/// place in the stack, and its reply carries a warning that names Outline Stroke. The shape draws +/// the area the other members make in that mode: the square alone in Add, or on top in Subtract, +/// and nothing in Intersect or when the line is the backmost member in Subtract. A line in a group, +/// beside a closed path too, an open evenodd square traced twice, and open evenodd subpaths that cancel one another or a closed +/// subpath of the same path are the same. An open path that encloses an area once closed (a bow tie +/// whose lobes cancel in signed area included) and closed shapes alone give no warning (#7849). +#[test] +fn lines_that_add_no_area_are_reported() { + use crate::cmd::OPEN_PATHS_ADD_NO_AREA; + fn line_of(s: &mut Session) -> NodeId { + NodeId(run(s, "shape.line", json!({"x1": 20, "y1": 50, "x2": 180, "y2": 50}))["id"].as_u64().unwrap()) + } + fn vee_of(s: &mut Session) -> NodeId { + let anchors = json!([{"x": 20, "y": 50}, {"x": 100, "y": 150}, {"x": 180, "y": 50}]); + NodeId(run(s, "path.create", json!({ "anchors": anchors }))["id"].as_u64().unwrap()) + } + fn bow_tie_of(s: &mut Session) -> NodeId { + let anchors = json!([{"x": 20, "y": 0}, {"x": 180, "y": 100}, {"x": 180, "y": 0}, {"x": 20, "y": 100}]); + NodeId(run(s, "path.create", json!({ "anchors": anchors }))["id"].as_u64().unwrap()) + } + fn twice_around_of(s: &mut Session) -> NodeId { + let d = "M20 20 L80 20 L80 80 L20 80 L20 20 L80 20 L80 80 L20 80"; + let id = NodeId(run(s, "path.create", json!({ "d": d }))["id"].as_u64().unwrap()); + run(s, "path.setFillRule", json!({"rule": "evenOdd"})); + id + } + fn evenodd_of(s: &mut Session, d: &str) -> NodeId { + let id = NodeId(run(s, "path.create", json!({ "d": d }))["id"].as_u64().unwrap()); + run(s, "path.setFillRule", json!({"rule": "evenOdd"})); + id + } + fn two_open_squares_of(s: &mut Session) -> NodeId { + evenodd_of(s, "M20 20 L80 20 L80 80 L20 80 M20 20 L80 20 L80 80 L20 80") + } + fn open_over_closed_of(s: &mut Session) -> NodeId { + evenodd_of(s, "M20 20 L80 20 L80 80 L20 80 Z M20 20 L80 20 L80 80 L20 80") + } + fn group_of(s: &mut Session, ids: &[NodeId]) -> NodeId { + run(s, "select.set", json!({"ids": ids.iter().map(|i| i.0).collect::>()})); + NodeId(run(s, "object.group", json!({}))["id"].as_u64().unwrap()) + } + type Build = fn(&mut Session) -> NodeId; + // (case, mode, the other member, whether it goes behind the 100 pt square, warned, area drawn) + type Case = (&'static str, &'static str, Build, bool, bool, Option); + let cases: [Case; 13] = [ + ("an open evenodd square traced twice", "add", twice_around_of, false, true, Some(10_000.0)), + ("two open evenodd squares on one another", "add", two_open_squares_of, false, true, Some(10_000.0)), + ("an open evenodd square on the same closed square", "add", open_over_closed_of, false, true, Some(10_000.0)), + ("a line", "add", line_of, false, true, Some(10_000.0)), + ("a line, subtracting", "subtract", line_of, false, true, Some(10_000.0)), + ("a line, intersecting", "intersect", line_of, false, true, Some(0.0)), + ("a line behind, subtracting", "subtract", line_of, true, true, Some(0.0)), + ( + "a group of lines", + "add", + |s| { + let ids = [line_of(s), line_of(s)]; + group_of(s, &ids) + }, + false, + true, + Some(10_000.0), + ), + ( + "a group of a line and a square", + "add", + |s| { + let ids = [line_of(s), square(s, 200.0, "#00ff00")]; + group_of(s, &ids) + }, + false, + true, + Some(20_000.0), + ), + ("an open path that encloses an area", "add", vee_of, false, false, None), + ("an open bow tie, whose signed area is zero", "add", bow_tie_of, false, false, None), + ("a square", "add", |s| square(s, 50.0, "#0000ff"), false, false, Some(15_000.0)), + ("a square, subtracting", "subtract", |s| square(s, 50.0, "#0000ff"), false, false, Some(5_000.0)), + ]; + for (what, mode, build, behind, warned, want) in cases { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 400, "height": 300})); + let (back, front) = if behind { + let other = build(&mut s); + (other, square(&mut s, 0.0, "#ff0000")) + } else { + let sq = square(&mut s, 0.0, "#ff0000"); + (sq, build(&mut s)) + }; + run(&mut s, "select.set", json!({"ids": [back.0, front.0]})); + let r = run(&mut s, "object.compoundShape.make", json!({ "mode": mode })); + let id = NodeId(r["id"].as_u64().unwrap_or_else(|| panic!("{what}: {r}"))); + assert_eq!(node(&s, id).children().unwrap().len(), 2, "{what}: both are members"); + assert_eq!(r.get("warning").and_then(Value::as_str), warned.then_some(OPEN_PATHS_ADD_NO_AREA), "{what}: {r}"); + if let Some(want) = want { + let d = &s.doc().unwrap().doc; + let hook = |c: &Node| effects::outline_object(Some(d), c); + let got = effects::compound_shape_area(None, &node(&s, id), Some(&hook)).map_or(0.0, |p| area(&p)); + assert!((got - want).abs() < 0.5, "{what}: draws {got}, not {want}"); + } + } +} diff --git a/crates/engine/src/tests/curvature_circle.rs b/crates/engine/src/tests/curvature_circle.rs new file mode 100644 index 0000000000..e862a03aaf --- /dev/null +++ b/crates/engine/src/tests/curvature_circle.rs @@ -0,0 +1,226 @@ +//! `shape.curvatureCircle`: the circle that touches a path at a point and bends as the path bends +//! there, and the Curvature Circle tool that runs it. + +use serde_json::{Value, json}; +use vectorcraft_doc::LiveShape; +use vectorcraft_geom::{Point, Rect}; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; + +use crate::*; + +const C: &str = "shape.curvatureCircle"; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn object_count(s: &Session) -> usize { + let mut n = 0; + s.doc().unwrap().doc.walk(|_| n += 1); + n +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn center_of(v: &Value) -> Point { + Point::new(v["cx"].as_f64().unwrap(), v["cy"].as_f64().unwrap()) +} + +/// Whether the geometric bounds of `id` are `want` to within 10⁻⁶ pt. +fn bounds_are(s: &Session, id: NodeId, want: Rect) -> bool { + let b = s.doc().unwrap().doc.bounds_of(&[id], false).unwrap(); + [(b.x0, want.x0), (b.y0, want.y0), (b.x1, want.x1), (b.y1, want.y1)].iter().all(|(a, w)| (a - w).abs() < 1e-6) +} + +/// A circle of radius 100 centered at (200, 200). +fn circle(s: &mut Session) -> NodeId { + id_of(&s.execute("shape.ellipse", &json!({"x": 100, "y": 100, "width": 200, "height": 200})).unwrap()) +} + +/// The parabola y = 200 + (x − 200)² / 200 from x = 100 to 300, one cubic: its vertex is at +/// (200, 200), where it bends with radius 100 about (200, 300). +fn parabola(s: &mut Session) -> NodeId { + let (a, b) = (166.666_666_666_666_66, 233.333_333_333_333_34); + let d = format!("M100 250 C{a} 183.333333333333334 {b} 183.333333333333334 300 250"); + id_of(&s.execute("path.create", &json!({ "d": d })).unwrap()) +} + +/// On a circle, the curvature circle is the circle itself: a live ellipse with the current paint, +/// selected, in one undo step. On the other side, it is the same size and touches the circle from +/// outside. +#[test] +fn the_curvature_circle_of_a_circle_is_the_circle() { + let mut s = session(); + let path = circle(&mut s); + let (undo, count) = (undo_len(&s), object_count(&s)); + for seg in 0..4 { + let v = s.execute(C, &json!({"id": path.0, "segment": seg, "t": 0.5})).unwrap(); + assert!(v["nominal"].as_bool().unwrap() && (v["radius"].as_f64().unwrap() - 100.0).abs() < 1e-9, "{v}"); + assert!(center_of(&v).distance(Point::new(200.0, 200.0)) < 1e-9, "{v}"); + let id = id_of(&v); + assert!(bounds_are(&s, id, Rect::new(100.0, 100.0, 300.0, 300.0))); + let node = s.doc().unwrap().doc.node(id).unwrap().clone(); + let vectorcraft_doc::NodeKind::Path { live: Some(live), .. } = &node.kind else { panic!("a live shape: {node:?}") }; + assert!(matches!(**live, LiveShape::Ellipse { .. })); + assert_eq!(s.doc().unwrap().selection.objects, vec![id]); + } + assert_eq!((undo_len(&s), object_count(&s)), (undo + 4, count + 4)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(object_count(&s), count + 3); + let v = s.execute(C, &json!({"id": path.0, "segment": 1, "t": 0.5, "convex": true})).unwrap(); + assert!((center_of(&v).distance(Point::new(200.0, 200.0)) - 200.0).abs() < 1e-9 && (v["radius"].as_f64().unwrap() - 100.0).abs() < 1e-9, "{v}"); +} + +/// At the vertex of a parabola, the circle has the parabola's curvature, radius 100, on the side +/// it bends toward, or on the other side with `convex`. +#[test] +fn the_curvature_circle_at_a_parabola_vertex() { + let mut s = session(); + let path = parabola(&mut s); + let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5})).unwrap(); + assert!(!v["nominal"].as_bool().unwrap() && (v["radius"].as_f64().unwrap() - 100.0).abs() < 1e-6, "{v}"); + assert!(center_of(&v).distance(Point::new(200.0, 300.0)) < 1e-6, "{v}"); + let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5, "convex": true})).unwrap(); + assert!(center_of(&v).distance(Point::new(200.0, 100.0)) < 1e-6, "{v}"); +} + +/// A straight segment, a cusp, a corner anchor and a bend so slight that its circle would reach +/// past the canvas are errors, and nothing is drawn. +#[test] +fn straight_segments_cusps_and_huge_circles_are_refused() { + let mut s = session(); + let line = id_of(&s.execute("shape.line", &json!({"x1": 10, "y1": 20, "x2": 130, "y2": 70})).unwrap()); + let cusp = id_of(&s.execute("path.create", &json!({"d": "M0 0 C100 100 0 100 100 0"})).unwrap()); + let gentle = id_of(&s.execute("path.create", &json!({"d": "M0 0 C100 0.0000001 200 0.0000001 300 0"})).unwrap()); + // A curve that meets a line at a corner anchor (150, 0). + let corner = id_of(&s.execute("path.create", &json!({"d": "M0 0 C50 -50 100 -50 150 0 L300 0"})).unwrap()); + let (undo, count) = (undo_len(&s), object_count(&s)); + for (id, t, want) in [ + (line, 0.5, "the path is straight there, so no circle matches its curvature"), + (cusp, 0.5, "the path has a cusp there, so it has no single curvature"), + (corner, 1.0, "the path has a corner there, so it has no single curvature"), + (gentle, 0.5, "the circle that matches the path there would reach past the canvas"), + ] { + let e = s.execute(C, &json!({"id": id.0, "segment": 0, "t": t})).unwrap_err().to_string(); + assert!(e.contains(want), "{e}"); + } + assert_eq!((undo_len(&s), object_count(&s)), (undo, count)); +} + +/// Params that are missing or out of range are errors, and nothing is drawn. +#[test] +fn bad_params_are_refused() { + let mut s = session(); + let path = circle(&mut s); + let (undo, count) = (undo_len(&s), object_count(&s)); + for (p, want) in [ + (json!({"segment": 0, "t": 0.5}), "missing id"), + (json!({"id": path.0, "t": 0.5}), "missing segment"), + (json!({"id": path.0, "segment": 0}), "missing number `t`"), + (json!({"id": path.0, "segment": 0, "t": 1.5}), "`t` must be from 0 to 1"), + (json!({"id": path.0, "segment": 0, "t": -0.1}), "`t` must be from 0 to 1"), + (json!({"id": path.0, "segment": 0, "t": "0.5"}), "`t` must be a number"), + (json!({"id": path.0, "segment": 4, "t": 0.5}), "no such segment"), + (json!({"id": path.0, "subpath": 1, "segment": 0, "t": 0.5}), "no such subpath"), + (json!({"id": path.0, "segment": 0, "t": 0.5, "convex": "yes"}), "`convex` must be true or false"), + ] { + let e = s.execute(C, &p).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + } + assert!(s.execute(C, &json!({"id": 9999, "segment": 0, "t": 0.5})).is_err()); + assert_eq!((undo_len(&s), object_count(&s)), (undo, count)); +} + +/// A guide has no curvature circle, as the tool leaves guides out; an error names the command. +#[test] +fn a_guide_is_refused() { + let mut s = session(); + let path = circle(&mut s); + s.execute("view.guides.make", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(path).unwrap().is_guide()); + let (undo, count) = (undo_len(&s), object_count(&s)); + let e = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5})).unwrap_err().to_string(); + assert!(e.contains("a guide has no curvature circle") && e.contains(C), "{e}"); + assert_eq!((undo_len(&s), object_count(&s)), (undo, count)); +} + +/// With Align New Objects to Pixel Grid on, the circle still touches the path where it was asked: +/// it is not pixel-aligned, so the grid does not move it. +#[test] +fn the_circle_is_not_moved_onto_the_pixel_grid() { + let mut s = session(); + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap(); + let path = id_of(&s.execute("shape.ellipse", &json!({"x": 100.3, "y": 100.2, "width": 200.4, "height": 200.4})).unwrap()); + let v = s.execute(C, &json!({"id": path.0, "segment": 0, "t": 0.5})).unwrap(); + let (c, r) = (center_of(&v), v["radius"].as_f64().unwrap()); + let id = id_of(&v); + assert!(bounds_are(&s, id, Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)), "{v}"); + assert!(!s.doc().unwrap().doc.node(id).unwrap().extras().pixel_aligned); +} + +fn view() -> ViewInfo { + ViewInfo { smart_guides: false, ..ViewInfo::default() } +} + +fn click(s: &mut Session, mods: Mods, x: f64, y: f64) { + for k in [PointerKind::Move, PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(k, x, y).with_mods(mods), view()).unwrap(); + } +} + +/// With the Curvature Circle tool, a click on a path draws the circle that matches it there, in +/// one undo step; with Shift, on the other side. A click on a straight line or away from every +/// path draws nothing. +#[test] +fn the_curvature_circle_tool_draws_the_circle_where_it_clicks() { + let mut s = session(); + let path = circle(&mut s); + s.execute("shape.line", &json!({"x1": 10, "y1": 380, "x2": 390, "y2": 380})).unwrap(); + s.select_tool("curvatureCircle", view()).unwrap(); + let (undo, count) = (undo_len(&s), object_count(&s)); + click(&mut s, Mods::default(), 301.0, 200.0); + assert_eq!(undo_len(&s), undo + 1); + let id = *s.doc().unwrap().selection.objects.first().unwrap(); + assert_ne!(id, path); + assert!(bounds_are(&s, id, Rect::new(100.0, 100.0, 300.0, 300.0))); + let shift = Mods { shift: true, ..Mods::default() }; + click(&mut s, shift, 300.0, 200.0); + let id = *s.doc().unwrap().selection.objects.first().unwrap(); + assert!(bounds_are(&s, id, Rect::new(300.0, 100.0, 500.0, 300.0))); + assert_eq!(object_count(&s), count + 2); + click(&mut s, Mods::default(), 200.0, 381.0); + click(&mut s, Mods::default(), 20.0, 20.0); + assert_eq!((undo_len(&s), object_count(&s)), (undo + 2, count + 2)); +} + +/// After a click at a parabola's vertex, a click at (280, 236), 2.4 pt from the circle just drawn +/// and about 3.1 pt from the parabola, passes over that circle and draws the parabola's circle +/// there; after an Undo, the pointer reaches the circle again. +#[test] +fn the_next_click_passes_over_the_circle_the_tool_drew() { + let mut s = session(); + parabola(&mut s); + s.select_tool("curvatureCircle", view()).unwrap(); + click(&mut s, Mods::default(), 200.0, 200.0); + let first = *s.doc().unwrap().selection.objects.first().unwrap(); + assert!(bounds_are(&s, first, Rect::new(100.0, 200.0, 300.0, 400.0))); + click(&mut s, Mods::default(), 280.0, 236.0); + let second = *s.doc().unwrap().selection.objects.first().unwrap(); + assert_ne!(second, first); + let r = s.doc().unwrap().doc.bounds_of(&[second], false).unwrap().width() / 2.0; + assert!(r > 150.0, "the parabola's circle at x = 280 is larger than at its vertex: {r}"); + s.execute("edit.undo", &json!({})).unwrap(); + let count = object_count(&s); + click(&mut s, Mods::default(), 280.0, 241.0); + assert_eq!(object_count(&s), count + 1, "the circle drawn first is within reach again"); + let third = *s.doc().unwrap().selection.objects.first().unwrap(); + assert!(bounds_are(&s, third, Rect::new(100.0, 200.0, 300.0, 400.0)), "the click drew the first circle's own circle"); +} diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index dfa3e95aba..75d7d081d9 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -751,14 +751,14 @@ fn eraser_size_follows_the_pen_pressure() { assert!(err.to_string().contains("sizeMode"), "{err}"); } -/// Eraser Tool Options' Angle, Roundness and Size variation menus: a value on Rotation, Bearing, -/// Tilt or Pressure takes what the pen read along the drag, Random stays within its Variation, a +/// Eraser Tool Options' Angle, Roundness and Size variation menus: a value on Stylus Wheel, Rotation, +/// Bearing, Tilt or Pressure takes what the pen read along the drag, Random stays within its Variation, a /// drag without the reading erases at the value itself, an open path is cut where the varied tip /// covers it, and an unknown mode or a variation out of its range is refused with nothing erased. #[test] fn the_eraser_tip_varies_with_its_modes() { // Which of `probes` a level drag through the middle of a 400 by 200 rectangle erases, each of - // its points `[x, 100]` followed by `pen` ([pressure, tiltX, tiltY, rotation]). + // its points `[x, 100]` followed by `pen` ([pressure, tiltX, tiltY, rotation, wheel]). let erased = |tip: serde_json::Value, pen: serde_json::Value, probes: &[(f64, f64)]| -> Vec { let mut s = session(); rect(&mut s, 0.0, 0.0, 400.0, 200.0); @@ -785,6 +785,10 @@ fn the_eraser_tip_varies_with_its_modes() { // The barrel turned half way round reads the most, which turns the tip upright. assert_eq!(erased(on_rotation.clone(), json!([none, none, none, 180]), &probes), [true, true], "Rotation"); assert_eq!(erased(on_rotation.clone(), json!([]), &probes), [true, false], "Rotation without a reading"); + // The finger wheel at the far end of its travel reads the most; without a wheel the tip lies level. + let on_wheel = with(&level, json!({"angleMode": "stylusWheel", "angleVariation": 90})); + assert_eq!(erased(on_wheel.clone(), json!([none, none, none, none, 1.0]), &probes), [true, true], "Stylus Wheel"); + assert_eq!(erased(on_wheel, json!([none, none, none, none, none]), &probes), [true, false], "Stylus Wheel without a reading"); // Leaning to the left (a bearing of 180°) reads the most too. let on_bearing = with(&level, json!({"angleMode": "bearing", "angleVariation": 90})); assert_eq!(erased(on_bearing.clone(), json!([none, -45, 0, none]), &probes), [true, true], "Bearing"); @@ -831,11 +835,11 @@ fn the_eraser_tip_varies_with_its_modes() { let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0); s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); let stroke = json!({"points": [[-10, 50], [110, 50]]}); - let modes = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\" or \"rotation\""; + let modes = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\", \"rotation\" or \"stylusWheel\""; for (extra, want) in [ (json!({"angleMode": "wheel"}), format!("angleMode is one of {modes}, not `wheel`")), (json!({"roundnessMode": 3}), format!("roundnessMode is one of {modes}, not 3")), - (json!({"sizeMode": "stylusWheel"}), format!("sizeMode is one of {modes}, not `stylusWheel`")), + (json!({"sizeMode": "Pressure"}), format!("sizeMode is one of {modes}, not `Pressure`")), (json!({"angleVariation": 181}), "angleVariation must be at most 180".to_string()), (json!({"roundnessVariation": 101}), "roundnessVariation must be at most 100".to_string()), (json!({"roundnessVariation": -1}), "roundnessVariation must be 0 or more".to_string()), @@ -3171,8 +3175,9 @@ fn drawing_commands_refuse_a_point_or_pressure_given_as_text() { } /// The drawing tools' commands refuse a pen pressure outside 0 to 1, a tiltX or tiltY outside -90 -/// to 90 and a rotation outside 0 to 360, naming the key, and a point array of more than six -/// numbers, naming the point; the document, the selection and the undo history stay as they were. +/// to 90, a rotation outside 0 to 360 and a stylus wheel outside 0 to 1, naming the key, and a +/// point array of more than seven numbers, naming the point; the document, the selection and the +/// undo history stay as they were. /// The ends of each range, null, one tilt axis alone and a mouse point `[x, y]` still draw. #[test] fn pen_values_outside_their_ranges_are_refused() { @@ -3194,7 +3199,8 @@ fn pen_values_outside_their_ranges_are_refused() { let tilt_x = "`tiltX` must be from -90 to 90"; let tilt_y = "`tiltY` must be from -90 to 90"; let rotation = "`rotation` must be from 0 to 360"; - let entries = "`points[3]` must be an array of at most 6 entries"; + let wheel = "`wheel` must be from 0 to 1"; + let entries = "`points[3]` must be an array of at most 7 entries"; for cmd in cmds { for (bad, want) in [ (json!([150, 150, -0.01]), pressure), @@ -3208,8 +3214,11 @@ fn pen_values_outside_their_ranges_are_refused() { (json!([150, 150, null, null, null, -1]), rotation), (json!({"x": 150, "y": 150, "rotation": 360.5}), rotation), (json!([150, 150, null, null, null, 720]), rotation), - (json!([150, 150, 0.5, 0, 0, 0, 1]), entries), - (json!([150, 150, null, null, null, null, null]), entries), + (json!([150, 150, null, null, null, null, -0.01]), wheel), + (json!([150, 150, 0.5, 0, 0, 0, 1.5]), wheel), + (json!({"x": 150, "y": 150, "wheel": 1e300}), wheel), + (json!([150, 150, 0.5, 0, 0, 0, 1, 0]), entries), + (json!([150, 150, null, null, null, null, null, null]), entries), ] { let points: Vec<_> = good.iter().cloned().chain([bad]).collect(); let sel = s.doc().unwrap().selection.clone(); @@ -3220,8 +3229,8 @@ fn pen_values_outside_their_ranges_are_refused() { for (row, cmd) in ["path.freehand", "brush.freehand", "path.blob", "path.eraseRegion"].into_iter().enumerate() { let y = 300.0 + 50.0 * row as f64; let points = json!([ - [100, y, 0, -90, 90, 0], - [150, y, 1, 90, -90, 360], + [100, y, 0, -90, 90, 0, 0], + [150, y, 1, 90, -90, 360, 1], [200, y, 0.5, null, 30], {"x": 250, "y": y, "tiltX": -45, "pressure": null}, [300, y], diff --git a/crates/engine/src/tests/dynamic_symbols.rs b/crates/engine/src/tests/dynamic_symbols.rs index c3e8cf8ea0..e136d9f45b 100644 --- a/crates/engine/src/tests/dynamic_symbols.rs +++ b/crates/engine/src/tests/dynamic_symbols.rs @@ -1154,6 +1154,39 @@ fn the_fill_and_stroke_proxies_show_the_picked_object() { assert_eq!(proxy_colors(&mut s), (Some("#0000ff".into()), None)); } +/// With an object of a dynamic symbol instance picked and the Live Paint Bucket active, the stroke +/// weight commands step the weight the bucket paints with and leave the instance as it is. +#[test] +fn live_paint_bucket_weight_steps_with_a_picked_symbol_object() { + let mut s = session(); + let inst = pair(&mut s, "dynamic"); + s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap(); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + s.paint.stroke_width = 2.0; + for (cmd, weight) in [("stroke.weightUp", 3.0), ("stroke.weightDown", 2.0)] { + assert_eq!(s.execute(cmd, &json!({})).unwrap()["objects"], 0, "{cmd}"); + assert_eq!(s.paint.stroke_width, weight, "{cmd}"); + } + assert_eq!(overrides(&s, inst), 0); +} + +/// With an object of a dynamic symbol instance picked and the Live Paint Bucket active, a gradient +/// stop of the bucket's fill can be selected and cleared, and the instance keeps its art. +#[test] +fn live_paint_bucket_selects_its_gradient_stop_with_a_picked_symbol_object() { + let mut s = session(); + let inst = pair(&mut s, "dynamic"); + s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap(); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + s.fill_active = true; + s.execute("paint.editGradient", &json!({"kind": "linear"})).unwrap(); + s.execute("gradient.selectStop", &json!({"index": 1})).unwrap(); + assert_eq!(s.selected_stop(), Some(1)); + s.execute("gradient.selectStop", &json!({"index": null})).unwrap(); + assert_eq!(s.selected_stop(), None); + assert_eq!(overrides(&s, inst), 0); +} + #[test] fn selecting_a_guide_too_lets_go_of_the_picked_object() { let mut s = session(); diff --git a/crates/engine/src/tests/expand.rs b/crates/engine/src/tests/expand.rs index e728754655..b9a90f55c7 100644 --- a/crates/engine/src/tests/expand.rs +++ b/crates/engine/src/tests/expand.rs @@ -407,7 +407,7 @@ fn image_with_shaped_fill(s: &mut Session) -> NodeId { /// outline with `outline`. fn marquee_at(s: &Session, x0: f64, x1: f64, outline: bool) -> Vec { let r = vectorcraft_geom::Rect::new(x0, 90.0, x1, 110.0); - vectorcraft_doc::hit::marquee_in_view(&s.doc().unwrap().doc, r, None, true, outline) + vectorcraft_doc::hit::marquee_in_view(&s.doc().unwrap().doc, r, None, true, outline, false) } /// A marquee touches a symbol instance where the geometry effects of its fill or stroke paint its diff --git a/crates/engine/src/tests/ids_without_selection.rs b/crates/engine/src/tests/ids_without_selection.rs index b274e7956f..9a48655468 100644 --- a/crates/engine/src/tests/ids_without_selection.rs +++ b/crates/engine/src/tests/ids_without_selection.rs @@ -377,7 +377,7 @@ fn ids_cases(d: u64) -> Vec<(&'static str, &'static str, serde_json::Value, Unse ("addon.color.filter", "ids", json!({"effect": "addon.color.invert"}), Selected), ("addon.color.applyNearestSwatch", "ids", json!({}), Selected), ("edit.colors.overprintBlack", "ids", json!({}), Selected), - ("edit.findReplace", "ids", json!({"find": "A", "replace": "B"}), Gives(json!({"count": 1}))), + ("edit.findReplace", "ids", json!({"find": "A", "replace": "B"}), Gives(json!({"count": 1, "replaced": 1}))), ("layer.highlight", "ids", json!({}), Fails("missing ids")), ("layer.move", "ids", json!({ "target": d }), Fails("missing ids")), ("library.add", "ids", json!({"kind": "graphic"}), Selected), diff --git a/crates/engine/src/tests/journal.rs b/crates/engine/src/tests/journal.rs index 93c2390237..0b35b2f772 100644 --- a/crates/engine/src/tests/journal.rs +++ b/crates/engine/src/tests/journal.rs @@ -1290,3 +1290,132 @@ fn a_failed_preview_is_not_journaled_at_commit() { s.commit_interaction().unwrap(); assert_eq!(s.journal.len(), journal); } + +/// `take_shape_drawn` is true once after a shape tool's drag is released, a shape command runs (alone +/// or as a batch step), and false after a drag in progress, a canceled or failed one, a click (which +/// opens the tool's dialog), other commands and saved steps that play. +#[test] +fn take_shape_drawn_follows_the_shapes_that_were_drawn() { + use vectorcraft_tools::{Action, PointerEvent, PointerKind}; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + assert!(!s.take_shape_drawn(), "a new document draws no shape"); + let v = crate::tooling::ViewInfo { smart_guides: false, ..Default::default() }; + for (tool, kind) in [ + ("rectangle", "Rectangle"), + ("roundedRectangle", "Rectangle"), + ("ellipse", "Ellipse"), + ("polygon", "Polygon"), + ("star", "Star"), + ("lineSegment", "Line"), + ] { + s.select_tool(tool, v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 50.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 120.0, 110.0), v).unwrap(); + assert!(!s.take_shape_drawn(), "{tool}: a drag in progress"); + s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 130.0), v).unwrap(); + assert!(s.take_shape_drawn(), "{tool} ({kind}): the released drag"); + assert!(!s.take_shape_drawn(), "{tool}: once"); + // Nothing selected, so the next press is not on the new shape's bounding box. + s.execute("select.none", &json!({})).unwrap(); + // A click asks for the tool's dialog and draws nothing yet. + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0), v).unwrap(); + assert!(!s.take_shape_drawn(), "{tool}: a click"); + } + // A canceled drag, and a drag whose preview failed. + let rect = json!({"x": 10, "y": 10, "width": 40, "height": 30}); + s.apply_actions(vec![Action::Begin("Rectangle".into()), Action::Preview("shape.rectangle".into(), rect.clone()), Action::Cancel]).unwrap(); + assert!(!s.take_shape_drawn(), "a canceled drag"); + let bad = json!({"x": 10, "y": 10, "width": "wide", "height": 30}); + s.apply_actions(vec![Action::Begin("Rectangle".into()), Action::Preview("shape.rectangle".into(), bad.clone()), Action::Commit]).unwrap(); + assert!(!s.take_shape_drawn(), "a failed drag"); + // Commands: each shape command, a failed one, a batch with and without a shape, other edits. + for (id, p) in [ + ("shape.rectangle", rect.clone()), + ("shape.ellipse", rect.clone()), + ("shape.polygon", json!({"cx": 100, "cy": 100, "radius": 30})), + ("shape.star", json!({"cx": 100, "cy": 100, "radius1": 30, "radius2": 15, "points": 5})), + ("shape.line", json!({"x1": 0, "y1": 0, "x2": 50, "y2": 50})), + ] { + s.execute(id, &p).unwrap(); + assert!(s.take_shape_drawn(), "{id}"); + } + assert!(s.execute("shape.rectangle", &bad).is_err()); + assert!(!s.take_shape_drawn(), "a failed command"); + s.execute( + "command.batch", + &json!({"commands": [{"command": "shape.ellipse", "params": rect}, {"command": "object.move", "params": {"dx": 5, "dy": 0}}]}), + ) + .unwrap(); + assert!(s.take_shape_drawn(), "a batch that draws"); + s.execute("command.batch", &json!({"commands": [{"command": "object.move", "params": {"dx": 5, "dy": 0}}]})).unwrap(); + assert!(!s.take_shape_drawn(), "a batch that draws nothing"); + s.execute("shape.rectangularGrid", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(!s.take_shape_drawn(), "other commands, undo and redo"); + // Saved steps that play. + s.replay("shape.rectangle", &rect).unwrap(); + s.replay( + "command.batch", + &json!({"commands": [{"command": "shape.star", "params": {"cx": 50, "cy": 50, "radius1": 20, "radius2": 10, "points": 5}}]}), + ) + .unwrap(); + assert!(!s.take_shape_drawn(), "saved steps"); + // A script's commands. + let count = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + let shapes = count(&s); + s.execute("script.run", &json!({"source": "vc.run('shape.rectangle', {x:100,y:0,width:5,height:5});", "name": "t.js"})).unwrap(); + assert_eq!(count(&s), shapes + 1, "the script drew"); + assert!(!s.take_shape_drawn(), "a script"); +} + +/// With the perspective grid shown and a plane active, a shape tool's drag journals +/// `perspective.draw` naming the shape command: `take_shape_drawn` is true for a Rectangle drawn on +/// the plane and for `perspective.draw` naming a shape command (alone or as a batch step), and false +/// for one naming a shape outside [`crate::DRAWS_SHAPE`]. +#[test] +fn take_shape_drawn_counts_shapes_drawn_in_perspective() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let (mut s, _) = super::persp_select::persp_session(); + s.execute("perspective.grid.show", &json!({"visible": true})).unwrap(); + s.execute("perspective.plane.set", &json!({"plane": "left"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.take_shape_drawn(); + let v = crate::tooling::ViewInfo { smart_guides: false, ..Default::default() }; + s.select_tool("rectangle", v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 350.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 380.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 410.0), v).unwrap(); + assert_eq!(s.journal.last().unwrap().0, "perspective.draw"); + assert!(s.take_shape_drawn(), "a Rectangle drawn on the plane"); + let rect = json!({"x": 260, "y": 360, "width": 30, "height": 30}); + s.execute("perspective.draw", &json!({"command": "shape.rectangle", "params": rect})).unwrap(); + assert!(s.take_shape_drawn(), "perspective.draw naming shape.rectangle"); + s.execute("command.batch", &json!({"commands": [{"command": "perspective.draw", "params": {"command": "shape.ellipse", "params": rect}}]})) + .unwrap(); + assert!(s.take_shape_drawn(), "a batch step drawing in perspective"); + s.execute("perspective.draw", &json!({"command": "shape.flare", "params": {"cx": 300, "cy": 380, "diameter": 40}})).unwrap(); + assert!(!s.take_shape_drawn(), "perspective.draw naming a flare"); +} + +/// Show on Shape Creation (`showOnShapeCreation`) is off until set, is set and read through +/// `prefs.set` and `prefs.get`, refuses a value that is not a boolean, and is kept with the saved +/// preferences. +#[test] +fn show_on_shape_creation_is_a_saved_preference() { + let mut s = Session::new(); + assert!(!s.prefs.show_on_shape_creation); + assert_eq!(s.execute("prefs.get", &json!({"key": "showOnShapeCreation"})).unwrap(), json!(false)); + s.execute("prefs.set", &json!({"key": "showOnShapeCreation", "value": true})).unwrap(); + assert!(s.prefs.show_on_shape_creation); + assert_eq!(s.execute("prefs.get", &json!({"key": "showOnShapeCreation"})).unwrap(), json!(true)); + assert!(s.execute("prefs.set", &json!({"key": "showOnShapeCreation", "value": "yes"})).is_err()); + assert!(s.prefs.show_on_shape_creation, "a refused value changes nothing"); + let saved = serde_json::to_value(&s.prefs).unwrap(); + assert_eq!(saved["showOnShapeCreation"], json!(true)); + let read: Prefs = serde_json::from_value(saved).unwrap(); + assert!(read.show_on_shape_creation); +} diff --git a/crates/engine/src/tests/layers.rs b/crates/engine/src/tests/layers.rs index e5cb1c8f63..c3bba6803b 100644 --- a/crates/engine/src/tests/layers.rs +++ b/crates/engine/src/tests/layers.rs @@ -167,6 +167,183 @@ fn clicking_rows_at_any_depth_highlights_them_and_sets_the_current_layer() { assert_eq!(document_rows(&s), vec![g.0, c.0], "document.inspect lists the rows"); } +/// Run `layer.highlight` with `ids` and `mode` → (the rows it returned, the current layer), after +/// checking that the call counted one revision and left the rows it returned highlighted. +fn highlight_rows(s: &mut Session, ids: &[NodeId], mode: &str) -> (Vec, Option) { + let revision = s.doc().unwrap().revision; + let r = run(s, "layer.highlight", json!({"ids": ids.iter().map(|i| i.0).collect::>(), "mode": mode})); + let st = s.doc().unwrap(); + assert_eq!(st.revision, revision + 1, "{mode} {ids:?}"); + let rows: Vec = r["rows"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + assert_eq!(rows, st.layer_rows, "{mode} {ids:?}"); + (rows, st.active_layer) +} + +/// `layer.highlight` keeps the rows in highlight order: `set` and `add` take a repeated id once, +/// `toggle` takes an id listed twice off and on again (or on and off, and its layer becomes the +/// current one), unknown ids and ids after the first 100,000 are dropped, rows highlighted twice +/// stay as they are on `add`, and `toggle` takes every copy off. +#[test] +fn highlighting_rows_keeps_their_order_with_repeated_unknown_and_excess_ids() { + let mut s = session(); + let (layer, sub, a, g, b, c) = tree(&mut s); + let unknown = NodeId(9999); + assert_eq!(highlight_rows(&mut s, &[a, g, a, unknown, c], "set"), (vec![a, g, c], Some(layer))); + assert_eq!(highlight_rows(&mut s, &[g, b, a, b], "add"), (vec![a, g, c, b], Some(sub))); + assert_eq!(highlight_rows(&mut s, &[c, c], "toggle"), (vec![a, g, b, c], Some(layer))); + // `sub` goes on and off again; it was the last row added, so its layer is the current one. + assert_eq!(highlight_rows(&mut s, &[sub, sub], "toggle"), (vec![a, g, b, c], Some(sub))); + assert_eq!(highlight_rows(&mut s, &[a, unknown], "toggle"), (vec![g, b, c], Some(layer))); + assert_eq!(highlight_rows(&mut s, &[], "add"), (vec![g, b, c], Some(layer))); + assert_eq!(highlight_rows(&mut s, &[], "toggle"), (vec![g, b, c], Some(layer))); + s.doc_mut().unwrap().active_layer = Some(sub); + assert_eq!(highlight_rows(&mut s, &[], "set"), (vec![], Some(sub)), "no rows: the current layer stays"); + let mut excess = vec![unknown; 100_000]; + excess.push(a); + assert_eq!(highlight_rows(&mut s, &excess, "set"), (vec![], Some(sub)), "only the first 100,000 ids count"); + s.doc_mut().unwrap().layer_rows = vec![a, a, g]; + assert_eq!(highlight_rows(&mut s, &[a, c], "add"), (vec![a, a, g, c], Some(layer))); + assert_eq!(highlight_rows(&mut s, &[a], "toggle"), (vec![g, c], Some(layer))); + // The same with more than 8 ids. + s.doc_mut().unwrap().layer_rows = vec![a, a, g]; + assert_eq!(highlight_rows(&mut s, &[a, c, c, c, c, c, c, c, c], "add"), (vec![a, a, g, c], Some(layer))); + s.doc_mut().unwrap().layer_rows = vec![a, a, g]; + assert_eq!(highlight_rows(&mut s, &[a, b, b, b, b, b, b, b, b], "toggle"), (vec![g], Some(sub)), "`b` goes on and off 4 times"); + assert_eq!(highlight_rows(&mut s, &[c, g, sub, g, sub, a, unknown, a, c, layer], "toggle"), (vec![g, layer], Some(layer))); + let revision = s.doc().unwrap().revision; + assert!(s.execute("layer.highlight", &json!({"ids": [b.0], "mode": "nope"})).is_err()); + let st = s.doc().unwrap(); + assert_eq!((st.revision, st.layer_rows.clone()), (revision, vec![g, layer]), "a bad mode changes nothing"); +} + +/// `layer.highlight`'s rule as a search of the highlighted rows for each id in `p`. The tests +/// compare the command with it. +fn highlight_by_search(st: &mut DocState, p: &Value) -> Value { + let mut ids: Vec = p["ids"].as_array().unwrap().iter().map(|v| NodeId(v.as_u64().unwrap())).collect(); + ids.truncate(crate::cmd::layer::MAX_ROWS); + let mode = p["mode"].as_str().unwrap_or("set"); + ids.retain(|id| st.doc.node(*id).is_some()); + let mut rows = st.highlighted_rows(); + if mode == "set" { + rows.clear(); + } + let mut last = None; + for id in ids { + if mode == "toggle" && rows.contains(&id) { + rows.retain(|r| *r != id); + } else if !rows.contains(&id) { + rows.push(id); + last = Some(id); + } + } + if let Some(layer) = last.or(rows.last().copied()).and_then(|id| st.doc.layer_containing(id)) { + st.active_layer = Some(layer); + } + st.layer_rows = rows; + st.revision += 1; + json!({ "rows": st.layer_rows.iter().map(|i| i.0).collect::>() }) +} + +/// Two sessions with `n` squares on a layer and a sublayer after them, and the squares' ids. +fn highlight_pair(n: usize) -> (Session, Session, Vec, NodeId) { + let make = || { + let mut s = super::large_edits::session(n, super::large_edits::square); + let sub = id(&run(&mut s, "layer.newSublayer", json!({"name": "Sub"}))); + (s, sub) + }; + let ((cmd, sub), (search, other)) = (make(), make()); + assert_eq!(sub, other); + let squares = super::large_edits::layer(&cmd, 0).into_iter().filter(|i| *i != sub).collect(); + (cmd, search, squares, sub) +} + +/// `p` for `layer.highlight` with `ids` and `mode`. +fn highlight_params(ids: impl IntoIterator, mode: &str) -> Value { + json!({"ids": ids.into_iter().map(|i| i.0).collect::>(), "mode": mode}) +} + +/// On 3,000 rows `layer.highlight` gives what [`highlight_by_search`] gives: the same rows in the +/// same order, the same current layer and the same returned rows, with repeated, unknown and +/// toggled ids. +#[test] +fn layer_highlight_matches_a_search_of_the_rows_for_each_id() { + let (mut cmd, mut search, sq, sub) = highlight_pair(3_000); + let unknown = NodeId(u64::MAX); + let steps = [ + highlight_params(sq[..2_000].iter().copied(), "set"), + highlight_params(sq[1_000..].iter().copied().chain([sub, sq[0]]), "add"), + highlight_params([sq[5], sq[5], sub, sq[2_999], unknown, sub, sub], "toggle"), + highlight_params(sq[500..520].iter().chain(&sq[510..515]).copied(), "toggle"), + highlight_params(sq.iter().rev().step_by(7).copied(), "add"), + highlight_params(sq.iter().step_by(3).copied().chain([sub]), "toggle"), + highlight_params(Vec::new(), "add"), + highlight_params(sq.iter().rev().step_by(2).chain(&sq[..10]).copied(), "set"), + highlight_params(Vec::new(), "set"), + ]; + for p in &steps { + let r = run(&mut cmd, "layer.highlight", p.clone()); + let expected = highlight_by_search(search.doc_mut().unwrap(), p); + let (a, b) = (cmd.doc().unwrap(), search.doc().unwrap()); + assert_eq!(r, expected, "{}", p["mode"]); + assert_eq!((&a.layer_rows, a.active_layer, a.revision), (&b.layer_rows, b.active_layer, b.revision), "{}", p["mode"]); + } +} + +/// Time `layer.highlight` against [`highlight_by_search`] on one layer of 20,000 paths: `set` of +/// all of them, `add` of 10,000 already highlighted and `toggle` of one, 7 runs each, both checked +/// to give the same rows and current layer. +/// Run with `cargo test --release -p vectorcraft-engine --lib layer_highlight_timing -- --ignored --nocapture`. +#[test] +#[ignore = "manual timing probe; wall-clock performance depends on machine load"] +fn layer_highlight_timing() { + let (mut cmd, mut search, sq, _) = highlight_pair(20_000); + let steps = [ + ("set of 20,000", highlight_params(sq.iter().copied(), "set")), + ("add of 10,000", highlight_params(sq[5_000..15_000].iter().copied(), "add")), + ("toggle of 1", highlight_params([sq[10_000]], "toggle")), + ]; + let mut ms = vec![(Vec::new(), Vec::new()); steps.len()]; + for run_no in 0..7 { + for (i, (_, p)) in steps.iter().enumerate() { + let mut time_cmd = || { + let start = std::time::Instant::now(); + let r = cmd.execute("layer.highlight", p).unwrap(); + (start.elapsed().as_secs_f64() * 1000.0, r) + }; + let mut time_search = || { + let start = std::time::Instant::now(); + let r = highlight_by_search(search.doc_mut().unwrap(), p); + (start.elapsed().as_secs_f64() * 1000.0, r) + }; + // Alternate which goes first. + let ((tc, rc), (ts, rs)) = if run_no % 2 == 0 { + let c = time_cmd(); + (c, time_search()) + } else { + let s = time_search(); + (time_cmd(), s) + }; + assert_eq!(rc, rs); + let (a, b) = (cmd.doc().unwrap(), search.doc().unwrap()); + assert_eq!((&a.layer_rows, a.active_layer), (&b.layer_rows, b.active_layer)); + ms[i].0.push(ts); + ms[i].1.push(tc); + } + } + let median = |v: &[f64]| { + let mut v = v.to_vec(); + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + for ((name, _), (search_ms, cmd_ms)) in steps.iter().zip(&ms) { + println!( + "{name}: search {:.3} ms, command {:.3} ms (median of 7); search runs {search_ms:.3?}, command runs {cmd_ms:.3?}", + median(search_ms), + median(cmd_ms) + ); + } +} + fn document_rows(s: &Session) -> Vec { crate::inspect::document(s)["layerRows"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect() } @@ -1102,6 +1279,43 @@ fn locate_object_highlights_its_row() { assert!(s.execute("layer.locate", &json!({})).is_err()); } +/// With several objects selected, Locate Object finds the frontmost one in the stacking order, +/// whatever order they were selected in; an `id` still wins. +#[test] +fn locate_object_finds_the_frontmost_selected_object() { + let mut s = session(); + let (_, sub, a, g, b, c) = tree(&mut s); + let top = id(&run(&mut s, "layer.new", json!({"top": true}))); + let d = rect(&mut s, 400.0); + let locate = |s: &mut Session, ids: &[NodeId]| { + run(s, "select.set", json!({"ids": ids.iter().map(|i| i.0).collect::>()})); + assert_eq!(s.doc().unwrap().selection.objects.last(), ids.last(), "selected in this order"); + run(s, "layer.locate", json!({}))["id"].clone() + }; + // In one sublayer, the group in front of the rectangle selected last. + assert_eq!(locate(&mut s, &[g, a]), json!(g.0)); + assert_eq!(s.doc().unwrap().highlighted_rows(), vec![g]); + // The sublayer sits in front of the art directly in its layer. + assert_eq!(locate(&mut s, &[a, c]), json!(a.0)); + // A higher layer wins over everything below it. + assert_eq!(locate(&mut s, &[d, b, c]), json!(d.0)); + assert_eq!(s.doc().unwrap().highlighted_rows(), vec![d]); + // A group and its member: the member paints after the group it is in. + assert_eq!(locate(&mut s, &[b, g]), json!(b.0)); + // Added one at a time, as by Shift-clicks. + run(&mut s, "select.set", json!({"ids": [d.0]})); + run(&mut s, "select.add", json!({"ids": [a.0]})); + assert_eq!(run(&mut s, "layer.locate", json!({}))["id"], d.0); + // An id still locates that object, behind the selection or not. + assert_eq!(run(&mut s, "layer.locate", json!({"id": c.0}))["id"], c.0); + assert_eq!(s.doc().unwrap().highlighted_rows(), vec![c]); + // Locate Layer takes the layer of the frontmost selected object. + run(&mut s, "select.set", json!({"ids": [d.0, a.0]})); + assert_eq!(run(&mut s, "layer.locate", json!({"layersOnly": true})), json!({"id": top.0, "objectId": d.0, "ancestry": [top.0]})); + run(&mut s, "select.set", json!({"ids": [a.0, c.0]})); + assert_eq!(run(&mut s, "layer.locate", json!({"layersOnly": true}))["id"], sub.0); +} + /// Locate Layer (`layersOnly`, sent while Show Layers Only is on) highlights the innermost layer /// or sublayer holding the object, through any groups; a layer locates itself. #[test] diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 2656d8c4f8..ef14bbaef9 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -2377,7 +2377,8 @@ fn find_and_replace_leaves_type_on_a_locked_artboard() { /// Find and Replace that replaces each match with the text it is (`CAT` found in `cat`, ignoring /// case, and replaced by `cat`) records no undo step: the step to redo stays and the document stays -/// unmodified. It still replies with the count. A replacement that changes the text is one undo step. +/// unmodified. It still replies with the count, and with no match replaced. A replacement that +/// changes the text is one undo step. #[test] fn find_and_replace_that_changes_nothing_records_no_undo_step() { let mut s = session(); @@ -2385,9 +2386,9 @@ fn find_and_replace_that_changes_nothing_records_no_undo_step() { select_with_a_step_to_redo(&mut s, &[a]); let before = history(&s); assert_eq!((before.1, before.2), (1, false), "a step to redo, and nothing unsaved"); - assert_eq!(s.execute("edit.findReplace", &json!({"find": "CAT", "replace": "cat"})).unwrap(), json!({"count": 2})); + assert_eq!(s.execute("edit.findReplace", &json!({"find": "CAT", "replace": "cat"})).unwrap(), json!({"count": 2, "replaced": 0})); assert_eq!((history(&s), plain(&s, a)), (before, "cat cat".to_string())); - assert_eq!(s.execute("edit.findReplace", &json!({"find": "cat", "replace": "dog"})).unwrap(), json!({"count": 2})); + assert_eq!(s.execute("edit.findReplace", &json!({"find": "cat", "replace": "dog"})).unwrap(), json!({"count": 2, "replaced": 2})); assert_eq!((history(&s), plain(&s, a)), ((before.0 + 1, 0, true), "dog dog".to_string())); } @@ -2424,12 +2425,190 @@ fn find_next_cycles_through_text_objects() { let _ = text(&mut s, "banana"); let c = text(&mut s, "pineapple"); s.execute("select.none", &json!({})).unwrap(); - assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "APPLE"})).unwrap()), a); + // From the top of the stacking order down, then round again. + assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "APPLE"})).unwrap()), c); + assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "apple"})).unwrap()), a); assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "apple"})).unwrap()), c); + // A selection that starts with a shape goes on after its first type object. + let shape = rect(&mut s, 300.0, 300.0, 20.0, 20.0); + sel(&mut s, &[shape, c]); assert_eq!(id_of(&s.execute("edit.findNext", &json!({"find": "apple"})).unwrap()), a); assert!(s.execute("edit.findNext", &json!({"find": "zzz"})).unwrap()["id"].is_null()); } +/// The match `r` (an `edit.findNext` result) as (object, start, end, index, count). +fn found(r: &Value) -> (u64, u64, u64, u64, u64) { + let n = |k: &str| r[k].as_u64().unwrap_or_else(|| panic!("no `{k}` in {r}")); + (n("id"), n("start"), n("end"), n("index"), n("count")) +} + +/// Find Next steps through the matches one by one when each call is given the match before it: +/// the objects from the top of the stacking order down, each object's matches in reading order, +/// and round again after the last. Search Backwards visits them the other way. Each match is +/// returned with its bytes and its object is selected; nothing is recorded for undo. +#[test] +fn find_next_steps_through_the_matches_in_both_directions() { + let mut s = session(); + let bottom = text(&mut s, "cat éa cat"); + let _ = text(&mut s, "dog"); + let top = text(&mut s, "a cat"); + s.execute("select.none", &json!({})).unwrap(); + let before = history(&s); + let step = |s: &mut Session, from: &Value, backwards: bool| { + let from = if from.is_null() { Value::Null } else { json!({"id": from["id"], "start": from["start"], "end": from["end"]}) }; + s.execute("edit.findNext", &json!({"find": "cat", "from": from, "backwards": backwards})).unwrap() + }; + // "é" is two bytes, so the second match of the bottom object is at bytes 8..11. + let forward = [(top.0, 2, 5, 1, 3), (bottom.0, 0, 3, 2, 3), (bottom.0, 8, 11, 3, 3), (top.0, 2, 5, 1, 3)]; + let mut at = Value::Null; + for want in forward { + at = step(&mut s, &at, false); + assert_eq!((found(&at), selected(&s), at["selected"].clone()), (want, vec![NodeId(want.0)], json!(true))); + } + let backward = [(bottom.0, 8, 11, 3, 3), (bottom.0, 0, 3, 2, 3), (top.0, 2, 5, 1, 3), (bottom.0, 8, 11, 3, 3)]; + s.execute("select.none", &json!({})).unwrap(); + let mut at = Value::Null; + for want in backward { + at = step(&mut s, &at, true); + assert_eq!((found(&at), selected(&s)), (want, vec![NodeId(want.0)])); + } + assert_eq!(history(&s), before, "finding is no undo step"); + // A `from` in an object the search does not visit starts at the first match. + let r = s.execute("edit.findNext", &json!({"find": "cat", "from": {"id": 999_999, "start": 0, "end": 0}})).unwrap(); + assert_eq!(found(&r), (top.0, 2, 5, 1, 3)); + // So does a null `from`, with a type object selected. + sel(&mut s, &[top]); + let r = s.execute("edit.findNext", &json!({"find": "cat", "from": null})).unwrap(); + assert_eq!(found(&r), (top.0, 2, 5, 1, 3)); + // Nothing found: no match, and the selection stays. + let r = s.execute("edit.findNext", &json!({"find": "zebra"})).unwrap(); + assert_eq!((r, selected(&s)), (json!({"id": null, "count": 0}), vec![top])); +} + +/// Check Hidden Layers and Check Locked Layers: Find Next and Find and Replace leave the type of +/// a hidden layer and of a locked layer alone unless the switch for it is on. A match on such a +/// layer is returned without being selected. A hidden or locked object keeps its type out with +/// the switches on. +#[test] +fn find_and_replace_reach_hidden_and_locked_layers_only_when_asked() { + for (prop, switch, other) in [("visible", "hiddenLayers", "lockedLayers"), ("locked", "lockedLayers", "hiddenLayers")] { + let mut s = session(); + let open = text(&mut s, "cat one"); + let layer = id_of(&s.execute("layer.new", &json!({})).unwrap()); + let closed = text(&mut s, "cat two"); + let object = text(&mut s, "cat three"); + let off = |id: NodeId| if prop == "visible" { json!({"id": id.0, "visible": false}) } else { json!({"id": id.0, "locked": true}) }; + s.execute("object.setProps", &off(object)).unwrap(); + s.execute("layer.setProps", &off(layer)).unwrap(); + sel(&mut s, &[open]); + // Without the switch, and with only the other one, the one reachable match is found. + for p in [json!({"find": "cat"}), json!({"find": "cat", other: true})] { + let r = s.execute("edit.findNext", &p).unwrap(); + assert_eq!(found(&r), (open.0, 0, 3, 1, 1), "{prop} {p}"); + } + // With it, the layer's type is searched (it is above, so it comes first) and not selected. + s.execute("select.none", &json!({})).unwrap(); + let r = s.execute("edit.findNext", &json!({"find": "cat", switch: true})).unwrap(); + assert_eq!((found(&r), r["selected"].clone(), selected(&s)), ((closed.0, 0, 3, 1, 2), json!(false), vec![]), "{prop}"); + let r = s.execute("edit.findNext", &json!({"find": "cat", switch: true, "from": {"id": closed.0, "start": 0, "end": 3}})).unwrap(); + assert_eq!((found(&r), r["selected"].clone(), selected(&s)), ((open.0, 0, 3, 2, 2), json!(true), vec![open]), "{prop}"); + // Replace All: the same reach. + let n = undo_len(&s); + assert_eq!( + s.execute("edit.findReplace", &json!({"find": "cat", "replace": "dog", other: true})).unwrap(), + json!({"count": 1, "replaced": 1}), + "{prop}" + ); + assert_eq!((plain(&s, open), plain(&s, closed), plain(&s, object)), ("dog one".into(), "cat two".into(), "cat three".into()), "{prop}"); + assert_eq!( + s.execute("edit.findReplace", &json!({"find": "cat", "replace": "dog", switch: true})).unwrap(), + json!({"count": 1, "replaced": 1}), + "{prop}" + ); + assert_eq!((plain(&s, closed), plain(&s, object), undo_len(&s)), ("dog two".into(), "cat three".into(), n + 2), "{prop}"); + } +} + +/// Replace changes one match, the bytes Find Next returned, as one undo step, and returns the +/// replacement's bytes to go on from. Bytes that are no match are refused, and a match that +/// already reads as the replacement is left with no undo step. +#[test] +fn replace_match_replaces_the_one_match_found() { + let mut s = session(); + let t = text(&mut s, "cat cat Cat"); + s.execute("select.none", &json!({})).unwrap(); + let first = s.execute("edit.findNext", &json!({"find": "cat"})).unwrap(); + assert_eq!(found(&first), (t.0, 0, 3, 1, 3)); + let n = undo_len(&s); + let r = s.execute("edit.replaceMatch", &json!({"find": "cat", "replace": "horse", "id": t.0, "start": 0, "end": 3})).unwrap(); + assert_eq!(r, json!({"id": t.0, "start": 0, "end": 5, "replaced": true})); + assert_eq!((plain(&s, t), undo_len(&s)), ("horse cat Cat".to_string(), n + 1)); + // Replace & Find: on from the replacement, so text put in is not searched again. + let r = s.execute("edit.replaceMatch", &json!({"find": "cat", "replace": "a cat", "id": t.0, "start": 6, "end": 9})).unwrap(); + let next = s.execute("edit.findNext", &json!({"find": "cat", "from": {"id": r["id"], "start": r["start"], "end": r["end"]}})).unwrap(); + assert_eq!((plain(&s, t), found(&next)), ("horse a cat Cat".to_string(), (t.0, 12, 15, 2, 2))); + // Match Case decides what a match is. + let shape = rect(&mut s, 300.0, 300.0, 20.0, 20.0); + s.execute("select.none", &json!({})).unwrap(); + let before = (history(&s), plain(&s, t)); + for (p, want) in [ + (json!({"find": "cat", "replace": "x", "matchCase": true, "id": t.0, "start": 12, "end": 15}), "at bytes 12..15 of object"), + (json!({"find": "cat", "replace": "x", "id": t.0, "start": 1, "end": 4}), "at bytes 1..4 of object"), + (json!({"find": "cat", "replace": "x", "id": t.0, "start": 4, "end": 1}), "at bytes 1..4 of object"), + (json!({"find": "cat", "replace": "x", "id": t.0, "start": 0}), "missing `end`"), + (json!({"find": "cat", "replace": "x", "start": 0, "end": 3}), "missing `id`"), + (json!({"find": "cat", "replace": "x", "id": t.0, "start": "0", "end": 3}), "`start` must be a whole number"), + (json!({"find": "", "replace": "x", "id": t.0, "start": 0, "end": 3}), "missing `find`"), + (json!({"find": "cat", "replace": 5, "id": t.0, "start": 8, "end": 11}), "`replace` must be a string"), + (json!({"find": "cat", "replace": "x", "id": shape.0, "start": 0, "end": 3}), "is not text"), + ] { + let r = s.execute("edit.replaceMatch", &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains(want)), "{p}: {r:?}"); + assert_eq!((history(&s), plain(&s, t)), before, "{p}"); + } + let r = s.execute("edit.replaceMatch", &json!({"find": "cat", "replace": "x", "id": 999_999, "start": 0, "end": 3})); + assert!(matches!(r, Err(EngineError::NoNode(NodeId(999_999)))), "{r:?}"); + // A match that already reads as the replacement: nothing to undo. + let r = s.execute("edit.replaceMatch", &json!({"find": "CAT", "replace": "Cat", "id": t.0, "start": 12, "end": 15})).unwrap(); + assert_eq!((r, history(&s)), (json!({"id": t.0, "start": 12, "end": 15, "replaced": false}), before.0)); + // Find Next refuses a `from` that is not a match. + for (from, want) in [ + (json!(5), "missing `id`"), + (json!({"id": t.0, "start": 2}), "missing `end`"), + (json!({"id": "x", "start": 0, "end": 1}), "`id` must be a whole number"), + ] { + let r = s.execute("edit.findNext", &json!({"find": "cat", "from": from})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains(want)), "{from}: {r:?}"); + } + for key in ["backwards", "hiddenLayers", "lockedLayers"] { + let r = s.execute("edit.findNext", &json!({"find": "cat", key: "yes"})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if *msg == format!("`{key}` must be true or false")), "{key}: {r:?}"); + } + for key in ["hiddenLayers", "lockedLayers"] { + let r = s.execute("edit.findReplace", &json!({"find": "cat", key: 1})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if *msg == format!("`{key}` must be true or false")), "{key}: {r:?}"); + } +} + +/// Ruby over text after a replaced match moves with the text, for Replace and for Replace All, as +/// it does when the text is typed. +#[test] +fn find_and_replace_moves_the_ruby_after_a_match() { + for all in [false, true] { + let mut s = session(); + let t = text(&mut s, "ab 漢字"); + sel(&mut s, &[t]); + s.execute("type.ruby", &json!({"text": "かんじ", "start": 3, "end": 9})).unwrap(); + if all { + s.execute("edit.findReplace", &json!({"find": "ab", "replace": "abcd"})).unwrap(); + } else { + s.execute("edit.replaceMatch", &json!({"find": "ab", "replace": "abcd", "id": t.0, "start": 0, "end": 2})).unwrap(); + } + let NodeKind::Text(tt) = &node(&s, t).kind else { panic!() }; + assert_eq!((tt.plain_text().as_str(), tt.ruby.first().map(|r| (r.start, r.end))), ("abcd 漢字", Some((5, 11))), "all: {all}"); + } +} + /// The Type menu's commands and Find and Replace and Find Next refuse a param of the wrong type, or /// `ids` that name no object, with an error naming the param, and leave the text, the selection and /// the undo history as they were, even when Insert Character is also given a source it would use @@ -4473,6 +4652,17 @@ fn exit_isolation_leaves_a_locked_guide_path_deselected() { assert_eq!(selected(&s), vec![g]); } +/// A ruler guide is not isolated, and isolation mode stays as it was. +#[test] +fn ruler_guides_are_not_isolated() { + let mut s = session(); + s.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap(); + let guide = s.doc().unwrap().doc.ruler_guides()[0].id.unwrap(); + let err = s.execute("object.isolate", &json!({"id": guide.0})).unwrap_err(); + assert!(err.to_string().contains("ruler guides can't be isolated"), "{err}"); + assert_eq!(s.doc().unwrap().isolation, None); +} + /// Exit Isolation Mode on an isolated sublayer isolates its parent layer and selects the sublayer, one /// layer per call, without an undo step; from the top-level layer it leaves isolation mode. `all: true` /// leaves from any depth, a hidden parent layer is not isolated (the call leaves), and a group in a diff --git a/crates/engine/src/tests/overprint.rs b/crates/engine/src/tests/overprint.rs index 3f18ddf644..e73825e86f 100644 --- a/crates/engine/src/tests/overprint.rs +++ b/crates/engine/src/tests/overprint.rs @@ -281,6 +281,10 @@ fn overprint_black_covers_type_gradients_spots_and_groups() { /// pixel (0 full ink, 255 none). fn plate(doc: &Document, plate: &str) -> Vec { let mut r = Renderer::new(); + plate_with_renderer(&mut r, doc, plate) +} + +fn plate_with_renderer(r: &mut Renderer, doc: &Document, plate: &str) -> Vec { r.threads = 0; let seps = vectorcraft_render::proof::ProofSetup { separations: Some(vec![plate.into()]), ..Default::default() }; let opts = RenderOptions { background: Some([255, 255, 255, 255]), proof: Some(seps), ..Default::default() }; @@ -304,8 +308,18 @@ fn classic_3d_black_overprint_shades_on_the_black_plate() { let (over_doc, flat_doc) = (&over.doc().unwrap().doc, &flat.doc().unwrap().doc); let inked = |p: &[u8]| p.iter().filter(|v| **v < 250).count(); assert!(inked(&plate(over_doc, "Cyan")) > 1000, "the solid is drawn"); + for name in ["Cyan", "Magenta", "Yellow"] { + let shaded = plate(over_doc, name); + let unshaded = plate(flat_doc, name); + let changed = shaded.iter().zip(&unshaded).filter(|(s, u)| s.abs_diff(**u) > 1).count(); + assert_eq!(changed, 0, "Black Overprint changes the {name} plate"); + } assert!(inked(&plate(over_doc, "Black")) > 100, "the shading is on the black plate"); assert_eq!(inked(&plate(flat_doc, "Black")), 0, "No Shading adds no black"); + let mut renderer = Renderer::new(); + let first_cyan = plate_with_renderer(&mut renderer, over_doc, "Cyan"); + assert!(inked(&plate_with_renderer(&mut renderer, over_doc, "Black")) > 100); + assert_eq!(plate_with_renderer(&mut renderer, over_doc, "Cyan"), first_cyan, "switching plates preserves the Cyan preview"); // On screen a shaded face is the cyan darkened, not gray: the black multiplies the cyan. let image = |d: &Document| { let mut r = Renderer::new(); diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index 582543f7eb..f146e39941 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -326,9 +326,11 @@ fn a_confined_package_names_files_outside_the_read_root_by_name() { let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()); String::from_utf8(zip["poster Folder/poster Report.txt"].clone()).unwrap() }; + // Reopened existing links use native separators; missing links keep their stored path. + let red = dir.0.join("art").join("red.png").to_string_lossy().into_owned(); let person = report(&run(&mut s, "file.package", json!({}))); assert!(person.contains(&format!("From: {}\n", dir.file("poster.vectorcraft"))), "{person}"); - assert!(person.contains(&format!("{} → Links/red.png", dir.file("art/red.png"))), "{person}"); + assert!(person.contains(&format!("{red} → Links/red.png")), "{person}"); assert!(person.contains(&format!("blue.png: not found ({})", dir.file("art/blue.png"))), "{person}"); let in_root = dir.0.join("in"); @@ -339,16 +341,19 @@ fn a_confined_package_names_files_outside_the_read_root_by_name() { assert!(text.contains("\nred.png → Links/red.png\n") && text.contains("\nblue.png: not found (blue.png), not copied\n"), "{text}"); let base = dir.0.to_string_lossy().into_owned(); assert!(!text.contains(&base), "{text}"); + // Compare serialized JSON with the path encoded the same way, without its outer quotes. + let json_base = serde_json::to_string(&base).unwrap(); + let json_base = &json_base[1..json_base.len() - 1]; for key in ["missingLinks", "warnings", "files"] { - assert!(!client[key].to_string().contains(&base), "{key}: {client}"); + assert!(!client[key].to_string().contains(json_base), "{key}: {client}"); } // Document Info, whose report the package holds, gives no link either. for p in [json!({}), json!({"format": "text"})] { let info = crate::file_access::confine(roots.as_ref(), || run(&mut s, "document.info", p.clone())); - assert!(!info.to_string().contains(&base), "{p}: {info}"); + assert!(!info.to_string().contains(json_base), "{p}: {info}"); } let info = run(&mut s, "document.info", json!({"format": "text"})); - assert!(info.to_string().contains(&dir.file("art/red.png")), "the person's: {info}"); + assert!(info["text"].as_str().unwrap().contains(&red), "the person's: {info}"); } /// A confined request packages no document that links, or places a native document or a PDF with @@ -742,7 +747,9 @@ fn a_font_named_by_another_of_its_names_is_copied() { let zip = unzip(&vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap()); let report = String::from_utf8(zip["poster Folder/poster Report.txt"].clone()).unwrap(); assert!(report.contains("SourceSans3-Semibold Regular → Fonts/"), "{report}"); - let details = report.lines().find(|l| l.starts_with("SourceSans3-Semibold Regular: ")).unwrap_or_default(); + // The Font Details row: the Fonts rows above it start with the same label. + let font_details = report.split("\nFONT DETAILS\n").nth(1).unwrap_or_default(); + let details = font_details.lines().find(|l| l.starts_with("SourceSans3-Semibold Regular: ")).unwrap_or_default(); assert!(details.contains("embedding allowed") && !details.contains("missing"), "{report}"); } diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index f20af794c4..dff77c1ce4 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -1121,6 +1121,10 @@ fn path_commands_refuse_a_param_of_the_wrong_type() { s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); let r = ids(&s.execute("object.path.offsetPath", &json!({"offset": "0.1 in", "joins": "Bevel"})).unwrap()); assert!(close(bounds(&s, r[0]), Rect::new(92.8, 92.8, 157.2, 147.2), 1e-2), "{:?}", bounds(&s, r[0])); + // A product with a unit, which the offset used to refuse: 0.05x2 in is 0.1 in. + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let r = ids(&s.execute("object.path.offsetPath", &json!({"offset": "0.05x2 in", "joins": "Bevel"})).unwrap()); + assert!(close(bounds(&s, r[0]), Rect::new(92.8, 92.8, 157.2, 147.2), 1e-2), "{:?}", bounds(&s, r[0])); // Null switches keep Clean Up's defaults, which remove the stray point. let r = s.execute("object.path.cleanUp", &json!({"strayPoints": null, "unpaintedObjects": null, "emptyTextPaths": null})).unwrap(); assert_eq!(r["removed"], 1); diff --git a/crates/engine/src/tests/prefs_file.rs b/crates/engine/src/tests/prefs_file.rs index c2822ba937..bfe98b901b 100644 --- a/crates/engine/src/tests/prefs_file.rs +++ b/crates/engine/src/tests/prefs_file.rs @@ -176,3 +176,24 @@ fn a_file_over_the_limit_is_refused_before_it_is_parsed() { assert!(s.execute("prefs.import", &json!({"path": missing.to_string_lossy()})).is_err()); assert_eq!(s.prefs.to_json().to_string(), before); } + +/// Hold Shortcuts is off by default. The Hold Shortcut Delay takes 0.2 to 1.0 s and refuses other +/// values; a value from a settings file outside the range is brought inside it. +#[test] +fn hold_shortcut_preferences() { + let mut s = Session::new(); + assert!(!s.prefs.hold_shortcuts); + assert_eq!(s.prefs.key_hold_delay(), 0.35); + for ok in [0.2, 1.0] { + s.execute("prefs.set", &json!({"key": "keyHoldDelay", "value": ok})).unwrap(); + assert_eq!(s.prefs.key_hold_delay(), ok); + } + for bad in [0.1, 1.5] { + assert!(is_bad_params(s.execute("prefs.set", &json!({"key": "keyHoldDelay", "value": bad}))), "{bad}"); + } + s.execute("prefs.set", &json!({"key": "holdShortcuts", "value": true})).unwrap(); + assert!(s.prefs.hold_shortcuts); + let restored: Prefs = serde_json::from_value(json!({"keyHoldDelay": 5.0})).unwrap(); + assert_eq!(restored.key_hold_delay(), 1.0); + assert!(!restored.hold_shortcuts); +} diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs new file mode 100644 index 0000000000..66283183b9 --- /dev/null +++ b/crates/engine/src/tests/quickpen.rs @@ -0,0 +1,300 @@ +//! The Quick Pen tool driven through the session, and `path.quickPen`. + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_geom::{PathData, Point, SubPath}; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + +use crate::tooling::ViewInfo; +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn view() -> ViewInfo { + ViewInfo { smart_guides: false, ..Default::default() } +} + +fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn paths(s: &Session) -> Vec<(NodeId, PathData)> { + let mut v = vec![]; + s.doc().unwrap().doc.walk(|n| { + if let NodeKind::Path { path, .. } = &n.kind { + v.push((n.id, path.clone())); + } + }); + v +} + +fn only_path(s: &Session) -> SubPath { + let all = paths(s); + assert_eq!(all.len(), 1, "one path"); + all[0].1.subpaths[0].clone() +} + +fn pt(x: f64, y: f64) -> Point { + Point::new(x, y) +} + +fn press(s: &mut Session, pts: &[(f64, f64)]) { + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1), v).unwrap(); + for &(x, y) in &pts[1..] { + s.pointer(&PointerEvent::new(PointerKind::Drag, x, y), v).unwrap(); + } + let l = pts[pts.len() - 1]; + s.pointer(&PointerEvent::new(PointerKind::Up, l.0, l.1), v).unwrap(); +} + +fn click(s: &mut Session, x: f64, y: f64) { + press(s, &[(x, y)]); +} + +fn key(s: &mut Session, k: ToolKey) { + s.tool_key(k, Mods::default(), view()).unwrap(); +} + +fn quick_pen(s: &mut Session) { + s.select_tool("quickPen", view()).unwrap(); +} + +/// Clicks draw lines; Alt tapped alone switches to the next action, so the next clicks draw a +/// continuous arc and a sharp-corner half circle. Each piece is one undo step. +#[test] +fn clicks_draw_lines_and_arcs_one_undo_step_each() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + let undo = undo_steps(&s); + click(&mut s, 200.0, 100.0); + assert_eq!(undo_steps(&s), undo + 1); + key(&mut s, ToolKey::AltTap); + assert_eq!(s.tool_options()["action"], "continuousArc"); + click(&mut s, 300.0, 200.0); + key(&mut s, ToolKey::AltTap); + assert_eq!(s.tool_options()["action"], "sharpArc"); + click(&mut s, 300.0, 300.0); + assert_eq!(undo_steps(&s), undo + 3); + let sp = only_path(&s); + assert!(!sp.closed); + let ends: Vec = sp.anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends.first(), Some(&pt(100.0, 100.0))); + assert_eq!(ends.last(), Some(&pt(300.0, 300.0))); + // Line (2 points), quarter circle (1 more), half circle in two quarters (2 more). + assert_eq!(ends.len(), 5); + // The continuous arc left (200, 100) heading right, as the line arrived. + let joint = sp.anchors.get(1).unwrap(); + assert!((joint.h_out - joint.p).y.abs() < 1e-9 && joint.h_out.x > joint.p.x); + // The half circle on (300, 200)–(300, 300) bulges to the left of the way it was drawn + // (downward, so to the right on the page): its middle point is at x = 350. + assert!(sp.anchors.get(3).unwrap().p.distance(pt(350.0, 250.0)) < 1e-9); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(only_path(&s).anchors.len(), 3); +} + +/// C flips the last sharp-corner arc, and [ and ] make it 15° smaller or larger, each as one +/// undo step; the next arc keeps the new size. C is not taken while the last piece is a line. +#[test] +fn c_flips_and_brackets_size_the_last_sharp_arc() { + let mut s = session(); + quick_pen(&mut s); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + click(&mut s, 100.0, 300.0); + click(&mut s, 300.0, 300.0); + assert!(only_path(&s).anchors.get(1).unwrap().p.distance(pt(200.0, 200.0)) < 1e-9, "above the chord"); + assert!(s.tool_claims_key(ToolKey::Letter('c'), view())); + let undo = undo_steps(&s); + key(&mut s, ToolKey::Letter('c')); + assert!(only_path(&s).anchors.get(1).unwrap().p.distance(pt(200.0, 400.0)) < 1e-9, "below once flipped"); + assert_eq!(undo_steps(&s), undo + 1); + key(&mut s, ToolKey::BracketLeft); + assert_eq!(s.tool_options()["turn"], 165.0); + let sp = only_path(&s); + // A 165° arc is two segments; its middle point lies on the chord's perpendicular bisector, + // still below. + assert_eq!(sp.anchors.len(), 3); + let mid = sp.anchors.get(1).unwrap().p; + assert!((mid.x - 200.0).abs() < 1e-9 && mid.y > 300.0); + assert_eq!(undo_steps(&s), undo + 2); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "line"})).unwrap(); + click(&mut s, 400.0, 300.0); + assert!(!s.tool_claims_key(ToolKey::Letter('c'), view())); +} + +/// Alt tapped during a drag draws the piece with the next action: a continuous arc becomes a +/// sharp-corner arc with a corner where it starts, and the path goes on drawing after it. +#[test] +fn an_alt_tap_during_a_drag_switches_the_piece_and_drawing_goes_on() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "continuousArc"})).unwrap(); + // A quarter circle that arrives at (300, 200) heading down. + click(&mut s, 300.0, 200.0); + let joint = only_path(&s).anchors.len() - 1; + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 300.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 210.0, 310.0), v).unwrap(); + assert_eq!(only_path(&s).anchors.get(joint).unwrap().kind, vectorcraft_geom::AnchorKind::Smooth); + key(&mut s, ToolKey::AltTap); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 300.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 300.0), v).unwrap(); + assert_eq!(s.tool_options()["action"], "sharpArc"); + assert_eq!(only_path(&s).anchors.get(joint).unwrap().kind, vectorcraft_geom::AnchorKind::Corner); + click(&mut s, 100.0, 300.0); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(100.0, 300.0), "the same path"); +} + +/// A click on the first point closes the path; the next click starts a new one. +#[test] +fn a_click_on_the_first_point_closes_the_path() { + let mut s = session(); + quick_pen(&mut s); + for (x, y) in [(100.0, 100.0), (200.0, 100.0), (200.0, 200.0), (101.0, 101.0)] { + click(&mut s, x, y); + } + let sp = only_path(&s); + assert!(sp.closed); + assert_eq!(sp.anchors.len(), 3); + click(&mut s, 400.0, 400.0); + assert_eq!(paths(&s).len(), 2); +} + +/// Escape ends the path: the next click starts a new path. A press dragged places the piece +/// where it is let go. +#[test] +fn escape_ends_the_path_and_a_drag_places_the_piece() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + press(&mut s, &[(150.0, 100.0), (180.0, 120.0), (250.0, 150.0)]); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(250.0, 150.0)); + assert!(s.tool_ends_on_escape(view())); + key(&mut s, ToolKey::Escape); + assert!(!s.tool_ends_on_escape(view())); + click(&mut s, 500.0, 500.0); + assert_eq!(paths(&s).len(), 2); +} + +/// An anchor moved by another command ends the path being drawn: C does not flip the old arc back +/// over the edit, and the next click starts a new path instead of rebuilding the old one. +#[test] +fn an_edit_from_outside_ends_the_path() { + let mut s = session(); + quick_pen(&mut s); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + click(&mut s, 100.0, 300.0); + click(&mut s, 300.0, 300.0); + let (id, _) = paths(&s)[0].clone(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 2, "x": 320, "y": 280})).unwrap(); + assert!(!s.tool_claims_key(ToolKey::Letter('c'), view())); + click(&mut s, 500.0, 500.0); + let all = paths(&s); + assert_eq!(all.len(), 2, "a new path"); + assert_eq!(all[0].1.subpaths[0].anchors.last().unwrap().p, pt(320.0, 280.0), "the edit stays"); + // The same for a point of a path the tool went on from, and for the first point of a new path. + for new in [true, false] { + let mut s = session(); + let id = if new { + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + paths(&s)[0].0 + } else { + let r = s.execute("shape.line", &json!({"x1": 100, "y1": 100, "x2": 200, "y2": 100})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + quick_pen(&mut s); + click(&mut s, 200.0, 100.0); + click(&mut s, 200.0, 200.0); + id + }; + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap(); + click(&mut s, 400.0, 400.0); + assert_eq!(paths(&s).len(), 2, "a new path (new: {new})"); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors.first().unwrap().p, pt(90.0, 90.0)); + } +} + +/// A click on an end of an open path goes on drawing from it, in the same path; from its start, +/// the path is reversed first. +#[test] +fn a_click_on_an_open_end_continues_the_path() { + let mut s = session(); + let r = s.execute("shape.line", &json!({"x1": 100, "y1": 100, "x2": 200, "y2": 100})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 100.0, 200.0); + let all = paths(&s); + assert_eq!(all.len(), 1); + assert_eq!(all[0].0, id); + let ends: Vec = all[0].1.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(200.0, 100.0), pt(100.0, 100.0), pt(100.0, 200.0)]); +} + +/// `path.quickPen` makes a new path with the current paint, or a black stroke without any. +#[test] +fn path_quick_pen_makes_a_stroked_path() { + let mut s = session(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + let r = s + .execute( + "path.quickPen", + &json!({"start": [0, 0], "pieces": [{"x": 100, "y": 0}, {"x": 100, "y": 100, "action": "sharpArc", "turn": 90, "flip": true}]}), + ) + .unwrap(); + let id = r["id"].as_u64().unwrap(); + let n = s.doc().unwrap().doc.node(NodeId(id)).unwrap().clone(); + assert!(!n.appearance.stroke_paint().is_none(), "a black stroke"); + assert_eq!(n.path_data().unwrap().subpaths[0].anchors.len(), 3); +} + +/// Bad params are refused and change nothing. +#[test] +fn path_quick_pen_refuses_bad_params() { + let mut s = session(); + let r = s.execute("path.quickPen", &json!({"start": [0, 0], "pieces": [{"x": 100, "y": 0}]})).unwrap(); + let id = r["id"].as_u64().unwrap(); + let before = paths(&s); + let bad: [Value; 11] = [ + json!({}), + json!({"pieces": []}), + json!({"start": [0, 0], "pieces": [{"x": 1, "y": 1, "action": "arc"}]}), + json!({"start": [0, 0], "pieces": [{"x": 1, "y": 1, "action": "sharpArc", "turn": 0}]}), + json!({"start": [0, 0], "pieces": [{"x": 1, "y": 1, "turn": 360}]}), + json!({"start": [0, 0], "pieces": [{"x": "1", "y": 1}]}), + json!({"start": [0, 0], "pieces": [{"x": 1, "y": 1, "flip": "yes"}]}), + json!({"start": [0, 0], "keep": 1}), + json!({"id": id, "keep": 0}), + json!({"id": id, "keep": 3}), + json!({"id": id, "start": [0, 0]}), + ]; + for p in bad { + assert!(s.execute("path.quickPen", &p).is_err(), "{p}"); + } + assert!(s.execute("path.quickPen", &json!({"start": [0, 0], "pieces": vec![json!({"x": 1, "y": 1}); 10_001]})).is_err()); + s.execute("path.quickPen", &json!({"id": id, "closed": true})).unwrap(); + assert!(s.execute("path.quickPen", &json!({"id": id, "pieces": [{"x": 5, "y": 5}]})).is_err(), "closed"); + assert_eq!(paths(&s).len(), before.len()); +} + +/// With `id` and `keep`, the points after the first `keep` are replaced by the pieces. +#[test] +fn path_quick_pen_replaces_the_points_after_keep() { + let mut s = session(); + let r = s.execute("path.quickPen", &json!({"start": [0, 0], "pieces": [{"x": 100, "y": 0}, {"x": 100, "y": 100}]})).unwrap(); + let id = r["id"].as_u64().unwrap(); + s.execute("path.quickPen", &json!({"id": id, "keep": 2, "pieces": [{"x": 200, "y": 0}]})).unwrap(); + let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(0.0, 0.0), pt(100.0, 0.0), pt(200.0, 0.0)]); +} diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index dae6a1729f..10c2edcc17 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -836,6 +836,49 @@ fn a_null_in_group_colors_removes_that_swatch_and_the_ones_after_it_keep_their_p assert_eq!(link(&s, green), ("#00ff00".into(), Some(names[2].clone())), "art linked to a swatch that stays keeps its link"); } +/// A gradient or pattern swatch of the group keeps its place and its paint when `recolor.apply` +/// rewrites the group: the group's colors, from the rows or from `groupColors`, go to its color +/// swatches in order. +#[test] +fn apply_with_a_group_keeps_its_gradient_swatch() { + let mut s = session(); + run(&mut s, "swatch.newGroup", json!({"name": "Brand", "colors": ["#ff0000", "#0000ff"]})); + let fade = vectorcraft_color::Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient::default()))); + s.edit("test", |d, _| { + let w = vectorcraft_color::Swatch { name: "Fade".into(), paint: fade.clone(), global: false, spot: false }; + d.swatch_groups.iter_mut().find(|g| g.name == "Brand").unwrap().swatches.insert(1, w); + Ok(()) + }) + .unwrap(); + let group = |s: &Session| -> Vec<(String, Option)> { + let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Brand").unwrap().swatches.clone(); + g.iter().map(|w| (w.name.clone(), w.paint.color().map(|c| c.to_hex()))).collect() + }; + let names: Vec = group(&s).into_iter().map(|(n, _)| n).collect(); + rect(&mut s, json!("#ff0000")); + rect(&mut s, json!("#0000ff")); + select_all(&mut s); + // The rows' new colors go to the red and blue swatches; the gradient stays between them. + let map = json!([{"from": ["#ff0000"], "to": "#00ff00"}, {"from": ["#0000ff"], "to": "#ffff00"}]); + run(&mut s, "recolor.apply", json!({"map": map, "group": "Brand"})); + let want = |a: &str, b: &str| vec![(names[0].clone(), Some(a.to_string())), (names[1].clone(), None), (names[2].clone(), Some(b.to_string()))]; + assert_eq!(group(&s), want("#00ff00", "#ffff00")); + assert_eq!(gradient_at(&s, 1), fade, "the gradient swatch keeps its paint"); + // `groupColors` counts the color swatches only: "keep" is the first, and the second color is + // the blue swatch's. + run(&mut s, "recolor.apply", json!({"map": [], "group": "Brand", "groupColors": ["keep", "#123456"]})); + assert_eq!(group(&s), want("#00ff00", "#123456")); + // A null removes the color swatch at its place and leaves the gradient. + run(&mut s, "recolor.apply", json!({"map": [], "group": "Brand", "groupColors": [null, "#123456"]})); + assert_eq!(group(&s), [(names[1].clone(), None), (names[2].clone(), Some("#123456".into()))]); + assert_eq!(gradient_at(&s, 0), fade); +} + +/// The paint of the swatch at place `i` of the group "Brand". +fn gradient_at(s: &Session, i: usize) -> vectorcraft_color::Paint { + s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Brand").unwrap().swatches[i].paint.clone() +} + /// A row whose new color was removed keeps its art's colors: art in it linked to another swatch of /// the group, which the rewrite gives another color, loses the link instead of following it. #[test] diff --git a/crates/engine/src/tests/script_include.rs b/crates/engine/src/tests/script_include.rs index 1ad659cfdd..cc6756c332 100644 --- a/crates/engine/src/tests/script_include.rs +++ b/crates/engine/src/tests/script_include.rs @@ -77,6 +77,31 @@ fn script_missing_include_reports_origin() { assert!(report["message"].as_str().unwrap().contains("include file not found: nope.jsxinc"), "{report}"); assert_eq!(report["log"], json!([]), "nothing ran before the include was read"); assert!(report.get("file").is_none(), "the line is the script's own"); + assert_eq!(report["messageOrigin"], "built-in"); + let _ = std::fs::remove_dir_all(base); +} + +/// An error in an included file keeps where its message came from: a value the file threw is the +/// script's own text, and an error the app raised for it, or for a file `$.evalFile` could not run, is not. +#[test] +fn script_include_errors_keep_their_message_origin() { + let base = folder("origin"); + write(&base.join("main/lib.jsxinc"), "var a = 1;\n throw new RangeError('invalid array length');"); + write(&base.join("main/native.jsxinc"), "var a = 1;\n new Array(-1);"); + for (text, message, origin) in [ + ("#include \"lib.jsxinc\"", "RangeError: invalid array length", "script"), + ("#include \"native.jsxinc\"", "RangeError: invalid array length", "built-in"), + ("try {\n#include \"native.jsxinc\"\n} catch (e) { throw e; }", "RangeError: invalid array length", "built-in"), + ("try {\n#include \"native.jsxinc\"\n} catch (e) { throw e.message; }", "invalid array length", "script"), + ] { + let report = failed(&base, text); + assert_eq!((report["message"].as_str(), report["messageOrigin"].as_str()), (Some(message), Some(origin)), "{text}: {report}"); + } + let report = failed(&base, "#include \"lib.jsxinc\""); + let file = report["file"].as_str().map(|f| Path::new(f).ends_with("lib.jsxinc")); + assert_eq!((file, report["line"].as_u64(), report["column"].as_u64()), (Some(true), Some(2), Some(3)), "{report}"); + let report = failed(&base, "$.evalFile('nope.jsx');"); + assert_eq!(report["messageOrigin"], "built-in", "{report}"); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 50828e855c..bf8154f9a7 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -170,6 +170,58 @@ fn an_error_names_the_script_its_place_and_kind() { assert_eq!(s.script_report().unwrap()["line"], 1); } +/// A failed run's report keeps its message and kind and says where the message came from: text the +/// script supplied, or one of the app's own errors. The status text and the console line read the +/// same either way, and only the app's own errors get advice about other applications' objects. +#[test] +fn failed_script_report_keeps_message_and_adds_origin() { + let mut s = two_docs(); + for (source, kind, message, origin) in [ + ("throw new Error('invalid array length');", "thrown", "Error: invalid array length", "script"), + ("throw new RangeError('invalid array length');", "thrown", "RangeError: invalid array length", "script"), + ("throw 'invalid array length';", "thrown", "invalid array length", "script"), + ("throw 'ReferenceError: app is not defined';", "thrown", "ReferenceError: app is not defined", "script"), + ("try { new Array(-1); } catch (e) { throw new Error(e.message); }", "thrown", "Error: invalid array length", "script"), + ("new Array(-1);", "thrown", "RangeError: invalid array length", "built-in"), + ("try { new Array(-1); } catch (e) { throw e; }", "thrown", "RangeError: invalid array length", "built-in"), + ("vc.run();", "thrown", "TypeError: vc.run: give a command id, as a string", "built-in"), + ] { + let e = run(&mut s, source).unwrap_err().to_string(); + let report = s.script_report().unwrap().clone(); + assert_eq!( + (report["kind"].as_str(), report["message"].as_str(), report["messageOrigin"].as_str()), + (Some(kind), Some(message), Some(origin)), + "{source}" + ); + let (line, column) = (&report["line"], &report["column"]); + let before = format!("t.js: line {line}, column {column}: "); + assert_eq!(e, format!("{before}{message} ({kind})"), "{source}"); + assert_eq!(s.script_failure_text().as_deref(), Some(e.as_str())); + let authored = s.script_authored_failure(); + assert_eq!(authored, (origin == "script").then(|| (before.clone(), message, format!(" ({kind})"))), "{source}"); + let console = s.execute("script.console", &json!({})).unwrap(); + let error = console["lines"].as_array().unwrap().iter().rev().find(|l| l["kind"] == "error").map(|l| l["text"].clone()); + assert_eq!(error, Some(json!(format!("t.js:{line}:{column}: {message}"))), "{source}"); + } + // The app's own reference error names the `vc` object; the same text a script threw does not. + run(&mut s, "app.activeDocument;").unwrap_err(); + assert!(s.script_report().unwrap()["message"].as_str().unwrap().contains("`vc`")); + assert_eq!(s.script_report().unwrap()["messageOrigin"], "built-in"); + // An error in code `eval` compiled keeps where its message came from. + let e = run(&mut s, "eval(\"throw new Error('invalid array length')\");").unwrap_err().to_string(); + assert_eq!(e, "t.js: Error: invalid array length (thrown)"); + assert_eq!(s.script_authored_failure(), Some(("t.js: ".to_string(), "Error: invalid array length", " (thrown)".to_string()))); + // Syntax errors and limits are the app's own. + run(&mut s, "var = 1;").unwrap_err(); + assert_eq!((s.script_report().unwrap()["kind"].as_str(), s.script_authored_failure()), (Some("syntax"), None)); + s.execute("script.run", &json!({"source": "while (true) {}", "name": "t.js", "maxFuel": 100_000})).unwrap_err(); + assert_eq!((s.script_report().unwrap()["messageOrigin"].as_str(), s.script_authored_failure()), (Some("built-in"), None)); + // A run that completes has no failure to split. + run(&mut s, "throw 'x';").unwrap_err(); + run(&mut s, "1").unwrap(); + assert_eq!(s.script_authored_failure(), None); +} + /// An error raised where the run has no place for it, such as in code `eval` compiled, is named /// with the script and its kind alone, with one colon after the script's name. #[test] diff --git a/crates/engine/src/tests/stylelib.rs b/crates/engine/src/tests/stylelib.rs index e8623900fd..8f7c410edf 100644 --- a/crates/engine/src/tests/stylelib.rs +++ b/crates/engine/src/tests/stylelib.rs @@ -46,6 +46,7 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects() assert!(libs.iter().any(|l| l["id"] == "status-effects" && l["name"] == "Status Effects"), "{libs:?}"); assert!(libs.iter().any(|l| l["id"] == "textures" && l["name"] == "Textures" && l["count"] == 8), "{libs:?}"); assert!(libs.iter().any(|l| l["id"] == "neon-glow" && l["name"] == "Neon & Glow" && l["count"] == 6), "{libs:?}"); + assert!(libs.iter().any(|l| l["id"] == "paper-cutouts" && l["name"] == "Paper Cutouts" && l["count"] == 6), "{libs:?}"); for l in libs { let id = l["id"].as_str().unwrap(); let g = run(&mut s, "graphicStyle.library", json!({"library": id})); @@ -91,6 +92,24 @@ fn builtin_libraries_are_listed_with_original_styles_using_catalogued_effects() assert!(s.execute("graphicStyle.library", &json!({"library": "nope"})).is_err()); } +#[test] +fn paper_cutout_style_applies_to_an_object_and_undoes_together() { + let mut s = session(); + let id = rect(&mut s, 10.0, 20.0, 40.0, 30.0); + let before = doc(&s).node(id).unwrap().appearance.clone(); + let undo_before = undo_len(&s); + let result = + run(&mut s, "graphicStyle.addFromLibrary", json!({"library": "paper-cutouts", "name": "Coral Layers", "apply": true, "ids": [id.0]})); + assert_eq!((names(&result["added"]), result["applied"].as_str()), (vec!["Coral Layers"], Some("Coral Layers"))); + assert_eq!(undo_len(&s), undo_before + 1); + let applied = &doc(&s).node(id).unwrap().appearance; + assert_eq!(applied.items.len(), 3); + assert_eq!(applied.effects[0].id, "stylize.dropShadow"); + assert_eq!(applied.effects[0].params["blur"], 0.0); + run(&mut s, "edit.undo", json!({})); + assert_eq!(doc(&s).node(id).unwrap().appearance, before); +} + #[test] fn painted_and_sketched_styles_set_every_effect_setting_and_reopen_applied() { let mut s = session(); diff --git a/crates/engine/src/tests/swatchcmds.rs b/crates/engine/src/tests/swatchcmds.rs index 306d6b71ad..1b87639ef9 100644 --- a/crates/engine/src/tests/swatchcmds.rs +++ b/crates/engine/src/tests/swatchcmds.rs @@ -569,6 +569,72 @@ fn ungroup_and_sort_by_kind_are_one_undo_step_each() { assert_eq!(n[n.iter().position(|x| x == "Orange").unwrap() + 1], "Ocean", "the spot colour comes after the process ones, then the gradients"); } +/// Color Group Options renames a color group alone, as one undo step: its swatches, their colors +/// and the art linked to them stay as they are. A name another group or a swatch has, an empty +/// name and a parameter that is missing or not a string are errors that change nothing, and the +/// group's own name records no undo step. +#[test] +fn rename_group_renames_only_the_group_in_one_undo_step() { + let mut s = session(); + run(&mut s, "swatch.edit", json!({"name": "Bright Red", "global": true})); + let a = rect_filled(&mut s, json!({"swatch": "Bright Red"})); + let linked = fill(&s, a); + let members = names(&s, Some("Brights")); + let before = doc(&s).clone(); + let undo = undo_len(&s); + assert_eq!(run(&mut s, "swatch.renameGroup", json!({"group": "Brights", "name": " Vivid Colors "}))["name"], "Vivid Colors"); + assert!(doc(&s).swatch_groups.iter().all(|g| g.name != "Brights")); + assert_eq!(names(&s, Some("Vivid Colors")), members); + assert_eq!(fill(&s, a), linked, "linked art keeps its swatch and color"); + assert_eq!(undo_len(&s), undo + 1); + run(&mut s, "edit.undo", json!({})); + assert_eq!(*doc(&s), before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(names(&s, Some("Vivid Colors")), members); + let renamed = doc(&s).clone(); + // The group's own name, trimmed, changes nothing. + assert_eq!(run(&mut s, "swatch.renameGroup", json!({"group": "Vivid Colors", "name": " Vivid Colors"}))["name"], "Vivid Colors"); + assert_eq!(undo_len(&s), undo + 1); + let refused = [ + json!({"group": "Vivid Colors", "name": "Grays"}), + json!({"group": "Vivid Colors", "name": "White"}), + json!({"group": "Vivid Colors", "name": "[None]"}), + json!({"group": "Vivid Colors", "name": "[Registration]"}), + json!({"group": "Vivid Colors", "name": ""}), + json!({"group": "Vivid Colors", "name": " "}), + json!({"group": "Vivid Colors"}), + json!({"group": "Vivid Colors", "name": null}), + json!({"group": "Vivid Colors", "name": 5}), + json!({"name": "Bold"}), + json!({"group": 5, "name": "Bold"}), + json!({"group": "Nope", "name": "Bold"}), + json!({"group": "White", "name": "Bold"}), + ]; + for p in refused { + assert!(s.execute("swatch.renameGroup", &p).is_err(), "{p}"); + assert_eq!(*doc(&s), renamed, "{p}"); + assert_eq!(undo_len(&s), undo + 1, "{p}"); + } +} + +/// A color group renamed while a drag is still in progress keeps its new name when the drag is +/// canceled: the drag becomes a step of its own first, and the rename is the next step. +#[test] +fn rename_group_during_a_drag_is_a_step_of_its_own() { + let mut s = session(); + rect_filled(&mut s, json!({"swatch": "Bright Red"})); + let undo = undo_len(&s); + s.begin_interaction("Move").unwrap(); + s.preview("object.move", &json!({"dx": 7, "dy": 0})).unwrap(); + run(&mut s, "swatch.renameGroup", json!({"group": "Brights", "name": "Vivid"})); + s.cancel_interaction().ok(); + assert!(doc(&s).swatch_groups.iter().any(|g| g.name == "Vivid"), "canceling the drag keeps the rename"); + assert_eq!(undo_len(&s), undo + 2, "the drag and the rename are two steps"); + run(&mut s, "edit.undo", json!({})); + assert!(doc(&s).swatch_groups.iter().any(|g| g.name == "Brights"), "Undo takes back the rename alone"); + assert_eq!(undo_len(&s), undo + 1); +} + #[test] fn a_cmyk_document_starts_with_cmyk_swatches_and_stores_new_colours_as_cmyk() { use vectorcraft_color::Color; diff --git a/crates/engine/src/tests/symbolism_options.rs b/crates/engine/src/tests/symbolism_options.rs new file mode 100644 index 0000000000..b8cb29f213 --- /dev/null +++ b/crates/engine/src/tests/symbolism_options.rs @@ -0,0 +1,789 @@ +//! The Symbolism Tools Options the commands take: Method and pen pressure in `symbol.adjust`, the +//! Symbol Sizer's two options, the Symbol Sprayer's `attributes`, and `symbol.setDensity`. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeKind}; +use vectorcraft_geom::{Affine, Point, Rect}; + +use crate::*; + +/// A document with the 20 pt square symbol "Dot" (its first instance is at 10, 10) and nothing +/// selected. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + s.execute("symbol.new", &json!({"name": "Dot"})).unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + s +} + +/// An instance of Dot centered on (`x`, `y`), not selected. +fn dot(s: &mut Session, x: f64, y: f64) -> NodeId { + let id = NodeId(s.execute("symbol.place", &json!({"name": "Dot", "x": x, "y": y})).unwrap()["id"].as_u64().unwrap()); + s.select(|_, sel| sel.clear()).unwrap(); + id +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).cloned().unwrap() +} + +fn bounds(s: &Session, id: NodeId) -> Rect { + node(s, id).geometric_bounds().unwrap() +} + +fn xf(s: &Session, id: NodeId) -> Affine { + match node(s, id).kind { + NodeKind::SymbolInstance { xf, .. } => xf, + other => panic!("not an instance: {other:?}"), + } +} + +fn center(s: &Session, id: NodeId) -> Point { + xf(s, id) * Point::ZERO +} + +/// The instance's rotation in radians. +fn angle(s: &Session, id: NodeId) -> f64 { + let c = xf(s, id).as_coeffs(); + c[1].atan2(c[0]) +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn state(s: &Session) -> (Document, usize) { + ((*s.doc().unwrap().doc).clone(), undo_len(s)) +} + +fn adjust(s: &mut Session, p: Value) -> Value { + s.execute("symbol.adjust", &p).unwrap() +} + +/// `cmd` with `p` fails with the bad-parameter message `want` and leaves the document and the +/// undo history as they were. +fn refused(s: &mut Session, cmd: &str, p: Value, want: &str) { + let before = state(s); + let r = s.execute(cmd, &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == want), "{cmd} {p}: {r:?}"); + assert!(state(s) == before, "{cmd} {p} changed the document"); +} + +/// The children of symbol set `set`. +fn members(s: &Session, set: NodeId) -> Vec { + node(s, set).children().unwrap().iter().map(|c| c.id).collect() +} + +/// Method Average brings the sizes, rotations and opacities of the instances under the brush +/// toward their mean, whichever way Alt is; User Defined changes each one by the same amount. +#[test] +fn average_brings_the_instances_under_the_brush_toward_their_mean() { + // Two instances 20 pt apart, the first grown, turned and faded alone. + let pair = || { + let mut s = session(); + let (a, b) = (dot(&mut s, 200.0, 150.0), dot(&mut s, 220.0, 150.0)); + let only_a = json!([[200, 150], [200, 150], [200, 150], [200, 150]]); + for tool in ["size", "spin", "screen"] { + adjust(&mut s, json!({"tool": tool, "points": only_a, "radius": 5, "intensity": 10})); + } + (s, a, b) + }; + let (mut s, a, b) = pair(); + let (wa, wb) = (bounds(&s, a).width(), bounds(&s, b).width()); + let (ra, oa) = (angle(&s, a), node(&s, a).opacity); + assert!(wa > wb + 1.0 && ra.abs() > 0.1 && oa < 0.9, "{wa} {wb} {ra} {oa}"); + assert_eq!((angle(&s, b), node(&s, b).opacity), (0.0, 1.0)); + // User Defined grows both by the same factor: they stay as far apart in size. + let between = json!([[210, 150], [210, 150], [210, 150]]); + let (mut user, ..) = pair(); + adjust(&mut user, json!({"tool": "size", "points": between, "radius": 40, "intensity": 10})); + let ratio = |s: &Session| xf(s, a).determinant() / xf(s, b).determinant(); + assert!((ratio(&user) - ratio(&s)).abs() < 1e-9); + // Average: the two sizes meet at their geometric mean. + let before = ratio(&s); + let product = xf(&s, a).determinant() * xf(&s, b).determinant(); + let (mut alt, ..) = pair(); + adjust(&mut s, json!({"tool": "size", "points": between, "radius": 40, "intensity": 10, "method": "average"})); + assert!((ratio(&s) - 1.0).abs() < (before - 1.0).abs() / 2.0, "{} from {before}", ratio(&s)); + assert!((xf(&s, a).determinant() * xf(&s, b).determinant() / product - 1.0).abs() < 1e-9); + adjust(&mut alt, json!({"tool": "size", "points": between, "radius": 40, "intensity": 10, "method": "average", "alt": true})); + assert_eq!([xf(&alt, a), xf(&alt, b)], [xf(&s, a), xf(&s, b)], "Alt does not reverse an average"); + // The rotations and the opacities meet too. + adjust(&mut s, json!({"tool": "spin", "points": between, "radius": 40, "intensity": 10, "method": "average"})); + let (na, nb) = (angle(&s, a), angle(&s, b)); + assert!((na - nb).abs() < ra.abs() / 2.0 && nb.abs() > 1e-3, "{na} {nb} from {ra}"); + adjust(&mut s, json!({"tool": "screen", "points": between, "radius": 40, "intensity": 10, "method": "average"})); + let (pa, pb) = (node(&s, a).opacity, node(&s, b).opacity); + assert!(pa > oa && pb < 1.0 && (pa - pb).abs() < (1.0 - oa) / 2.0, "{pa} {pb} from {oa}"); +} + +/// `tool.setOption` refuses a Method, a Symbol Sprayer option or a checkbox value the Symbolism Tools +/// Options do not have, and sets none of the values given with it. +#[test] +fn bad_symbolism_tool_options_are_refused() { + let mut s = session(); + let before = s.tool_options_of("symbolSizer"); + for (values, want) in [ + (json!({"proportional": false, "method": "smooth"}), "`method` must be one of userDefined, average, random"), + (json!({"sprayScrunch": "random"}), "`sprayScrunch` must be one of average, userDefined"), + (json!({"method": "average", "usePressure": 1}), "`usePressure` must be true or false"), + (json!({"affectsDensity": "yes"}), "`affectsDensity` must be true or false"), + ] { + let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": values})); + assert_eq!(r, Err(want.to_string()), "{values}"); + assert_eq!(s.tool_options_of("symbolSizer"), before, "{values}"); + } + s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "key": "method", "value": "random"})).unwrap(); + assert_eq!(s.tool_options_of("symbolSizer")["method"], json!("random")); +} + +/// Average opacities below the Symbol Screener's least opacity (5%) stay below it: with the Screener +/// the instances meet at their mean, and a sprayed instance takes the mean of those under the brush. +#[test] +fn average_keeps_opacities_below_the_screeners_least() { + let mut s = session(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[200, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let a = members(&s, set)[0]; + let b = dot(&mut s, 220.0, 150.0); + for (id, opacity) in [(a, 0), (b, 2)] { + s.select(|_, sel| sel.set([id])).unwrap(); + s.execute("transparency.set", &json!({"opacity": opacity})).unwrap(); + } + s.select(|_, sel| sel.set([set])).unwrap(); + // A new instance beside the invisible one takes its opacity. + s.execute("symbol.spray", &json!({"name": "Dot", "points": [[185, 150]], "radius": 20})).unwrap(); + let sprayed = *members(&s, set).last().unwrap(); + assert_eq!(node(&s, sprayed).opacity, 0.0); + // The Screener with Average brings 0% and 2% toward 1%, not up to 5%. + s.select(|_, sel| sel.clear()).unwrap(); + adjust(&mut s, json!({"tool": "screen", "points": [[210, 150]], "radius": 40, "intensity": 10, "method": "average"})); + let (pa, pb) = (node(&s, a).opacity, node(&s, b).opacity); + assert!(pa > 0.0 && pa < 0.02 && pb < 0.02 && pb > 0.0, "{pa} {pb}"); +} + +/// Average over instances that already have the mean, or a stroke over no instance, changes +/// nothing and adds no undo step. +#[test] +fn average_at_the_mean_adds_no_undo_step() { + let mut s = session(); + dot(&mut s, 200.0, 150.0); + let before = state(&s); + for tool in ["scrunch", "size", "spin", "stain", "screen", "style"] { + let r = adjust(&mut s, json!({"tool": tool, "points": [[200, 150], [202, 150]], "radius": 30, "intensity": 10, "method": "average"})); + assert_eq!(r["count"], 0, "{tool}"); + assert!(state(&s) == before, "{tool} changed the document"); + } + let r = adjust(&mut s, json!({"tool": "size", "points": [[50, 50]], "radius": 10})); + assert_eq!(r["count"], 0); + assert!(state(&s) == before); +} + +/// Average evens out the Symbol Stainer's amount and the Symbol Scruncher's spacing. +#[test] +fn average_evens_out_the_stain_and_the_spacing() { + let mut s = session(); + let (a, b, c) = (dot(&mut s, 180.0, 150.0), dot(&mut s, 200.0, 150.0), dot(&mut s, 260.0, 150.0)); + adjust(&mut s, json!({"tool": "stain", "points": [[180, 150], [180, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"})); + let amount = |s: &Session, id| node(s, id).appearance.fill().map_or(0.0, |f| f.opacity); + let stained = amount(&s, a); + assert!(stained > 0.2 && amount(&s, b) == 0.0); + adjust( + &mut s, + json!({"tool": "stain", "points": [[190, 150], [190, 150]], "radius": 30, "intensity": 10, "method": "average", "color": "#0000ff"}), + ); + assert!(amount(&s, a) < stained && amount(&s, b) > 0.0, "{} {}", amount(&s, a), amount(&s, b)); + // The stained instance keeps its red, and the other takes the red of the stained one. + for id in [a, b] { + assert_eq!(node(&s, id).appearance.fill().and_then(|f| f.paint.color()).map(|c| c.to_hex()).as_deref(), Some("#ff0000")); + } + // Scrunch: the three are 20 and 60 apart; their distances from their middle even out. + let reach = |s: &Session| { + let xs = [a, b, c].map(|id| center(s, id).x); + let middle = xs.iter().sum::() / 3.0; + xs.map(|x| (x - middle).abs()) + }; + let spread = |r: [f64; 3]| r.iter().cloned().fold(0.0, f64::max) - r.iter().cloned().fold(f64::INFINITY, f64::min); + let before = spread(reach(&s)); + adjust(&mut s, json!({"tool": "scrunch", "points": [[213, 150], [213, 150]], "radius": 120, "intensity": 10, "method": "average"})); + assert!(spread(reach(&s)) < before * 0.8, "{} from {before}", spread(reach(&s))); +} + +/// Method Random gives each instance its own share of the change, the same for a stroke however +/// often it is applied; User Defined changes instances at the same distance alike. +#[test] +fn random_changes_each_instance_by_its_own_share() { + let grown = |method: Option<&str>| { + let mut s = session(); + let ids = [(180.0, 150.0), (220.0, 150.0), (200.0, 130.0), (200.0, 170.0)].map(|(x, y)| dot(&mut s, x, y)); + let mut p = json!({"tool": "size", "points": [[200, 150], [200, 150]], "radius": 60, "intensity": 10}); + if let Some(m) = method { + p["method"] = json!(m); + } + adjust(&mut s, p); + ids.map(|id| bounds(&s, id).width()) + }; + let user = grown(None); + assert!(user.iter().all(|w| (w - user[0]).abs() < 1e-9 && *w > 20.5), "{user:?}"); + assert_eq!(grown(Some("userDefined")), user); + let random = grown(Some("random")); + assert!(random.iter().any(|w| (w - random[0]).abs() > 0.05), "{random:?}"); + // From none of the User Defined change to twice it. + let twice = user[0] * user[0] / 20.0; + assert!(random.iter().all(|w| *w >= 20.0 - 1e-9 && *w <= twice + 1e-9), "{random:?} within 20..{twice}"); + assert_eq!(grown(Some("random")), random); +} + +/// With Method Random the Symbol Styler gives each instance its share of the style scaled by the +/// brush strength: at Intensity 1 a tenth of what it gives at Intensity 10. +#[test] +fn random_style_follows_the_brush_strength() { + let styled = |intensity: u32| { + let mut s = session(); + let ids = [(200.0, 150.0), (201.0, 150.0), (200.0, 151.0), (199.0, 150.0), (200.0, 149.0)].map(|(x, y)| dot(&mut s, x, y)); + let p = json!({"tool": "style", "points": [[200, 150]], "radius": 1000, "intensity": intensity, "method": "random", "color": "#ff0000"}); + adjust(&mut s, p); + ids.map(|id| f64::from(node(&s, id).appearance.fill().map_or(0.0, |f| f.opacity))) + }; + let (full, low) = (styled(10), styled(1)); + assert!(full.iter().any(|o| *o > 0.05), "{full:?}"); + for (f, l) in full.iter().zip(&low) { + assert!((l - f * 0.1).abs() < 1e-3, "{low:?} against {full:?}"); + } +} + +/// A `method` that is none of the three is an error and changes nothing; the Symbol Shifter takes +/// one and shifts as it does without. +#[test] +fn an_unknown_method_is_refused() { + let mut s = session(); + let a = dot(&mut s, 200.0, 150.0); + for (bad, shown) in [(json!("smooth"), "\"smooth\""), (json!(3), "3"), (json!(true), "true"), (json!("Average"), "\"Average\"")] { + for tool in ["size", "shift"] { + let want = format!("`method` must be userDefined, average or random, not {shown}"); + refused(&mut s, "symbol.adjust", json!({"tool": tool, "points": [[200, 150]], "method": bad}), &want); + } + } + let shifted = |method: Value| { + let mut s = session(); + let a = dot(&mut s, 200.0, 150.0); + adjust(&mut s, json!({"tool": "shift", "points": [[200, 150], [215, 150]], "intensity": 10, "method": method})); + center(&s, a) + }; + let moved = shifted(Value::Null); + assert!(moved.x > 205.0); + for method in ["average", "random", "userDefined"] { + assert_eq!(shifted(json!(method)), moved, "{method}"); + } + assert_eq!(center(&s, a), Point::new(200.0, 150.0)); +} + +/// With `usePressure` each point's pen pressure is the intensity there; without it the pressure is +/// not used. A pressure that isn't a number is an error. +#[test] +fn pen_pressure_is_the_intensity_with_use_pressure() { + let width = |points: Value, use_pressure: Option, intensity: f64| { + let mut s = session(); + let a = dot(&mut s, 200.0, 150.0); + let mut p = json!({"tool": "size", "points": points, "radius": 40, "intensity": intensity}); + if let Some(on) = use_pressure { + p["usePressure"] = json!(on); + } + let count = adjust(&mut s, p)["count"].as_u64().unwrap(); + (bounds(&s, a).width(), count) + }; + let (light, _) = width(json!([[200, 150, 0.25]]), Some(true), 5.0); + let (hard, _) = width(json!([[200, 150, 1.0]]), Some(true), 5.0); + assert!(20.0 < light && light < hard, "{light} {hard}"); + // Full pressure is intensity 10, whatever `intensity` says; a point without a pressure has 1. + assert_eq!(width(json!([[200, 150]]), None, 10.0).0, hard); + assert_eq!(width(json!([[200, 150]]), Some(true), 1.0).0, hard); + assert_eq!(width(json!([[200, 150, null]]), Some(true), 1.0).0, hard); + // No pressure: the instance stays as it is. + assert_eq!(width(json!([[200, 150, 0]]), Some(true), 5.0), (20.0, 0)); + // A pressure outside 0..1 is kept within it. + assert_eq!(width(json!([[200, 150, 7]]), Some(true), 5.0).0, hard); + // Without Use Pressure Pen the pressure is not used. + assert_eq!(width(json!([[200, 150, 0.25]]), None, 10.0).0, hard); + assert_eq!(width(json!([[200, 150, 0.25]]), Some(false), 10.0).0, hard); + let mut s = session(); + dot(&mut s, 200.0, 150.0); + for tool in ["size", "shift"] { + refused( + &mut s, + "symbol.adjust", + json!({"tool": tool, "points": [[200, 150, "hard"]], "usePressure": true}), + "a point's pressure must be a number, not \"hard\"", + ); + } + for key in ["usePressure", "proportional", "affectsDensity"] { + let mut p = json!({"tool": "size", "points": [[200, 150]]}); + p[key] = json!("yes"); + refused(&mut s, "symbol.adjust", p, &format!("`{key}` must be true or false")); + } +} + +/// The Symbol Sizer without Proportional Resizing resizes along the drag: a level drag the width, +/// an upright one the height, a click both. +#[test] +fn the_sizer_without_proportional_resizing_resizes_along_the_drag() { + let size = |points: Value, proportional: Option| { + let mut s = session(); + let a = dot(&mut s, 200.0, 150.0); + let mut p = json!({"tool": "size", "points": points, "radius": 60, "intensity": 10}); + if let Some(on) = proportional { + p["proportional"] = json!(on); + } + adjust(&mut s, p); + (bounds(&s, a).width(), bounds(&s, a).height()) + }; + let level = json!([[195, 150], [205, 150]]); + let (w, h) = size(level.clone(), Some(false)); + assert!(w > 21.0 && (h - 20.0).abs() < 1e-9, "{w} x {h}"); + let (w, h) = size(json!([[200, 145], [200, 155]]), Some(false)); + assert!(h > 21.0 && (w - 20.0).abs() < 1e-9, "{w} x {h}"); + let (w, h) = size(json!([[200, 150]]), Some(false)); + assert!(w > 20.5 && (w - h).abs() < 1e-9, "{w} x {h}"); + // Proportional Resizing (the default) keeps the shape for any drag, at the same area. + let (pw, ph) = size(level.clone(), None); + assert!(pw > 20.5 && (pw - ph).abs() < 1e-9, "{pw} x {ph}"); + assert_eq!(size(level.clone(), Some(true)), (pw, ph)); + let (w, h) = size(level, Some(false)); + assert!((w * h - pw * ph).abs() < 1e-6, "{w} x {h} against {pw} x {ph}"); +} + +/// With Resizing Affects Density an instance moves away from the brush's center as it grows and +/// toward it as it shrinks; without, it stays where it is. +#[test] +fn resizing_affects_density_moves_instances_from_the_brush_center() { + let at = |affects: Option, alt: bool| { + let mut s = session(); + let a = dot(&mut s, 220.0, 150.0); + let mut p = json!({"tool": "size", "points": [[200, 150], [200, 150]], "radius": 60, "intensity": 10, "alt": alt}); + if let Some(on) = affects { + p["affectsDensity"] = json!(on); + } + adjust(&mut s, p); + (center(&s, a), bounds(&s, a).width()) + }; + let (stays, grown) = at(None, false); + assert!((stays.x - 220.0).abs() < 1e-9 && grown > 20.5); + assert_eq!(at(Some(false), false), (stays, grown)); + let (away, width) = at(Some(true), false); + assert!(away.x > 220.5 && (away.y - 150.0).abs() < 1e-9 && width > 20.5, "{away:?}"); + let (toward, width) = at(Some(true), true); + assert!(toward.x < 219.5 && width < 19.5, "{toward:?}"); +} + +/// A new instance of the Symbol Sprayer takes the mean of the selected set's instances under the +/// brush for each attribute that is `average`, and the plain value for each that is `userDefined`. +#[test] +fn the_sprayer_gives_new_instances_the_average_or_the_user_defined_values() { + let mut s = session(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[200, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let first = members(&s, set)[0]; + // In an area without instances an average is the plain value. + assert!(node(&s, first).opacity == 1.0 && node(&s, first).appearance.fill().is_none() && angle(&s, first) == 0.0); + // Grow, fade and stain the set's one instance. + let on_it = json!([[200, 150], [200, 150], [200, 150], [200, 150], [200, 150], [200, 150]]); + for tool in ["size", "screen", "stain"] { + adjust(&mut s, json!({"tool": tool, "points": on_it, "radius": 40, "intensity": 10, "color": "#ff0000"})); + } + let look = |s: &Session, id: NodeId| { + let n = node(s, id); + (bounds(s, id).width(), n.opacity, n.appearance.fill().map(|f| (f.paint.color().map(|c| c.to_hex()), f.opacity))) + }; + let (width, opacity, stain) = look(&s, first); + assert!(width > 24.0 && opacity < 0.7 && stain.as_ref().is_some_and(|(_, amount)| *amount > 0.5), "{width} {opacity} {stain:?}"); + let spray = |s: &mut Session, at: Value, extra: Value| { + let mut p = json!({"name": "Dot", "points": at, "radius": 30}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + s.execute("symbol.spray", &p).unwrap(); + *members(s, set).last().unwrap() + }; + // Average (the default): the new instance, sprayed beside it, looks like it, at its size. + let near = spray(&mut s, json!([[215, 150]]), json!({})); + let (w, o, f) = look(&s, near); + assert!((w / width - 1.0).abs() < 1e-9, "{w} of {width}"); + assert_eq!((o, f), (opacity, stain.clone())); + // The averages of two instances that look alike are theirs. + let third = spray(&mut s, json!([[208, 165]]), json!({"attributes": {"size": "average", "screen": null}})); + assert_eq!(look(&s, third).1, opacity); + // Style: Average replaces a User Defined stain with the fill of the instances under the brush. + let mixed = spray(&mut s, json!([[205, 160]]), json!({"attributes": {"stain": "userDefined"}, "color": "#0000ff"})); + assert_eq!(look(&s, mixed).2.map(|(c, _)| c), stain.clone().map(|(c, _)| c)); + // Outside the brush's radius of every instance, the plain values: the symbol's own size. + let far = spray(&mut s, json!([[330, 250]]), json!({})); + let (w, o, f) = look(&s, far); + assert!((w / 20.0 - 1.0).abs() < 1e-9 && o == 1.0 && f.is_none(), "{w} {o} {f:?}"); + // User Defined: the symbol's size and opaque; Style: Average still gives the fill under the brush. + let user = json!({"size": "userDefined", "screen": "userDefined", "stain": "userDefined", "spin": "userDefined"}); + let plain = spray(&mut s, json!([[212, 140]]), json!({"attributes": user, "color": "#0000ff"})); + let (w, o, f) = look(&s, plain); + assert!((w / 20.0 - 1.0).abs() < 0.11 && o == 1.0, "{w} {o}"); + assert_eq!(f.map(|(c, _)| c), stain.clone().map(|(c, _)| c)); + assert_eq!(angle(&s, plain), 0.0, "one point has no direction"); + // With no fill under the brush, Stain: User Defined is the fill color in full, and a User Defined + // style without a fill (the document has only the default style) leaves it. + let blue = spray(&mut s, json!([[330, 40]]), json!({"attributes": user, "color": "#0000ff"})); + assert_eq!(look(&s, blue).2, Some((Some("#0000ff".to_string()), 1.0))); + let styled = json!({"stain": "userDefined", "style": "userDefined"}); + let blue = spray(&mut s, json!([[330, 100]]), json!({"attributes": styled, "color": "#0000ff"})); + assert_eq!(look(&s, blue).2, Some((Some("#0000ff".to_string()), 1.0))); + // Spin: User Defined turns the instances the way the stroke runs (here: down the page). + let down = spray(&mut s, json!([[100, 40], [100, 140]]), json!({"attributes": {"spin": "userDefined"}})); + assert!((angle(&s, down) - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "{}", angle(&s, down)); + let level = spray(&mut s, json!([[40, 260], [140, 260]]), json!({})); + assert_eq!(angle(&s, level), 0.0, "Average, with no instance under the brush"); +} + +/// Size: Average is a size on the page, the same measure for every symbol: a 20 pt symbol sprayed +/// beside an 80 pt one is 80 pt, and the Sizer brings the two to 40 pt. With no instance under the +/// brush a sprayed instance has its symbol's own size, whatever `scale` is. +#[test] +fn average_sizes_are_sizes_on_the_page_for_every_symbol() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 200, "width": 80, "height": 80})).unwrap(); + s.execute("symbol.new", &json!({"name": "Big"})).unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Big", "points": [[200, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let big = members(&s, set)[0]; + assert!((bounds(&s, big).width() - 80.0).abs() < 1e-9); + let spray = |s: &mut Session, at: Value| { + s.execute("symbol.spray", &json!({"name": "Dot", "points": at, "radius": 30, "scale": 2})).unwrap(); + *members(s, set).last().unwrap() + }; + let near = spray(&mut s, json!([[215, 150]])); + assert!((bounds(&s, near).width() - 80.0).abs() < 1e-9, "{}", bounds(&s, near).width()); + let far = spray(&mut s, json!([[350, 40]])); + assert!((bounds(&s, far).width() - 20.0).abs() < 1e-9, "{}", bounds(&s, far).width()); + // The Sizer: an unscaled Dot and an unscaled Big meet at the geometric mean of 20 and 80. + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 200, "width": 80, "height": 80})).unwrap(); + s.execute("symbol.new", &json!({"name": "Big"})).unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + let small = dot(&mut s, 200.0, 150.0); + let big = NodeId(s.execute("symbol.place", &json!({"name": "Big", "x": 220, "y": 150})).unwrap()["id"].as_u64().unwrap()); + s.select(|_, sel| sel.clear()).unwrap(); + let between = json!([[210, 150], [210, 150], [210, 150], [210, 150], [210, 150], [210, 150]]); + adjust(&mut s, json!({"tool": "size", "points": between, "radius": 30, "intensity": 10, "method": "average"})); + let (ws, wb) = (bounds(&s, small).width(), bounds(&s, big).width()); + assert!(ws > 30.0 && wb < 55.0 && (ws * wb / 1600.0 - 1.0).abs() < 1e-9, "{ws} {wb}"); + // A symbol without a recorded size is measured by its art: here 80 pt art drawn at its own size. + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 200, "width": 20, "height": 20})).unwrap(); + s.execute("symbol.new", &json!({"name": "Loose"})).unwrap(); + s.edit("Forget size", |d, _| { + if let Some(m) = d.unknown.get_mut(vectorcraft_doc::SYMBOL_SIZES).and_then(Value::as_object_mut) { + m.remove("Loose"); + } + for sym in d.symbols.iter_mut().filter(|sym| sym.name == "Loose") { + std::sync::Arc::make_mut(&mut sym.art).transform(Affine::scale(4.0), false); + } + Ok(()) + }) + .unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + let small = dot(&mut s, 200.0, 150.0); + let loose = NodeId(s.execute("symbol.place", &json!({"name": "Loose", "x": 220, "y": 150})).unwrap()["id"].as_u64().unwrap()); + s.select(|_, sel| sel.clear()).unwrap(); + // Its width as drawn, measured by its symbol's art. + let drawn = |s: &Session| { + let d = &s.doc().unwrap().doc; + node(s, loose).geometric_bounds_with(&d.symbol_boxes()).unwrap().width() + }; + assert!((drawn(&s) - 80.0).abs() < 1e-9, "{}", drawn(&s)); + adjust(&mut s, json!({"tool": "size", "points": between, "radius": 30, "intensity": 10, "method": "average"})); + let (ws, wl) = (bounds(&s, small).width(), drawn(&s)); + assert!(ws > 30.0 && wl < 55.0, "{ws} {wl}"); + // A new set sprayed with Size: Average is spaced by the size it is placed at, not by `scale`. + s.select(|_, sel| sel.clear()).unwrap(); + let stroke: Vec = (0..50).map(|i| json!([100.0 + 4.0 * f64::from(i), 20.0])).collect(); + let r = s.execute("symbol.spray", &json!({"name": "Dot", "points": stroke, "radius": 2, "scale": 100})).unwrap(); + assert!(r["count"].as_u64().unwrap() > 5, "{r}"); + // The 80 pt art of a symbol without a recorded size spaces new instances by its own size. + s.select(|_, sel| sel.clear()).unwrap(); + let stroke: Vec = (0..50).map(|i| json!([100.0 + 4.0 * f64::from(i), 280.0])).collect(); + let r = s.execute("symbol.spray", &json!({"name": "Loose", "points": stroke, "radius": 2})).unwrap(); + assert!(r["count"].as_u64().unwrap() <= 5, "{r}"); +} + +/// Spin: Average turns a new instance to the mean direction of the instances under the brush, and +/// Scrunch: Average spaces new instances as those under the brush are spaced. +#[test] +fn the_sprayer_averages_rotation_and_spacing() { + // A set of six instances 30 pt apart, turned by a drag of the Symbol Spinner; then a stroke + // along the row, 4 pt between its points, with Scrunch as given. Returns the rotations of the + // six, how many instances the stroke added and the rotation of the last one. + let sprayed = |scrunch: &str| { + let mut s = session(); + let row: Vec = (0..6).map(|i| json!([100.0 + 30.0 * f64::from(i), 100.0])).collect(); + let p = json!({"name": "Dot", "points": row, "radius": 2, "density": 10}); + let set = NodeId(s.execute("symbol.spray", &p).unwrap()["id"].as_u64().unwrap()); + assert_eq!(members(&s, set).len(), 6); + adjust(&mut s, json!({"tool": "spin", "points": [[175, 60], [176, 60], [177, 60], [178, 60]], "radius": 200, "intensity": 10})); + let turned: Vec = members(&s, set).iter().map(|id| angle(&s, *id)).collect(); + let stroke: Vec = (0..40).map(|i| json!([100.0 + 4.0 * f64::from(i), 100.0])).collect(); + let p = json!({"name": "Dot", "points": stroke, "radius": 40, "density": 10, "attributes": {"scrunch": scrunch}}); + let n = s.execute("symbol.spray", &p).unwrap()["count"].as_u64().unwrap(); + let new = *members(&s, set).last().unwrap(); + (turned, n, angle(&s, new)) + }; + let (turned, plain, _) = sprayed("userDefined"); + assert!(turned.iter().all(|a| a.abs() > 0.05 && a.signum() == turned[0].signum()), "{turned:?}"); + // User Defined keeps new instances 3 pt apart (20 pt × 0.15 at density 10); Average keeps them + // as far apart as the instances under the brush are, about 30 pt. + let (_, spaced, new_angle) = sprayed("average"); + assert!(spaced < plain, "{spaced} spaced like the row against {plain}"); + assert!(new_angle.signum() == turned[0].signum() && new_angle.abs() > 0.05, "{new_angle} against {turned:?}"); +} + +/// The Symbol Sprayer's `attributes` must be an object of the six keys, each `average` or +/// `userDefined`; anything else is an error and sprays nothing. +#[test] +fn bad_sprayer_attributes_are_refused() { + let mut s = session(); + let calls = [ + (json!("average"), "`attributes` must be an object, not \"average\"".to_string()), + (json!(["size"]), "`attributes` must be an object, not [\"size\"]".to_string()), + (json!({"density": "average"}), "unknown attribute `density`".to_string()), + (json!({"size": "big"}), "attribute `size` must be average or userDefined, not \"big\"".to_string()), + (json!({"spin": true}), "attribute `spin` must be average or userDefined, not true".to_string()), + (json!({"style": "Average"}), "attribute `style` must be average or userDefined, not \"Average\"".to_string()), + ]; + for (attributes, want) in calls { + refused(&mut s, "symbol.spray", json!({"name": "Dot", "points": [[200, 150]], "attributes": attributes}), &want); + } + refused(&mut s, "symbol.spray", json!({"name": "Dot", "points": [[200, 150]], "keepModel": "yes"}), "`keepModel` must be true or false"); + refused(&mut s, "symbol.spray", json!({"name": "Dot", "points": [[200, 150, "x"]]}), "a point's pressure must be a number, not \"x\""); + // Style: User Defined with a style the document does not have; Average does not use it. + let user = json!({"name": "Dot", "points": [[200, 150]], "attributes": {"style": "userDefined"}, "style": "Nope"}); + refused(&mut s, "symbol.spray", user, "unknown graphic style `Nope`"); + let number = json!({"name": "Dot", "points": [[200, 150]], "attributes": {"style": "userDefined"}, "style": 3}); + refused(&mut s, "symbol.spray", number, "`style` must be a graphic style's name, not 3"); + let average = json!({"name": "Dot", "points": [[200, 150]], "style": "Nope"}); + assert_eq!(s.execute("symbol.spray", &average).unwrap()["count"], 1); + let all = json!({"scrunch": "average", "size": "userDefined", "spin": null, "screen": "average", "stain": "average", "style": "average"}); + assert_eq!(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[200, 150]], "attributes": all})).unwrap()["count"], 1); +} + +/// `symbol.setDensity` spaces a symbol set's instances from its middle as the new density packs +/// them, as one undo step, and adds none when no instance moves. +#[test] +fn set_density_spaces_the_instances_of_a_symbol_set() { + let mut s = session(); + let row: Vec = (0..8).map(|i| json!([40.0 + 40.0 * f64::from(i), 150.0])).collect(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": row, "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let ids = members(&s, set); + assert_eq!(ids.len(), 8); + let centers = |s: &Session| ids.iter().map(|id| center(s, *id)).collect::>(); + let middle = |c: &[Point]| Point::new(c.iter().map(|p| p.x).sum::() / 8.0, c.iter().map(|p| p.y).sum::() / 8.0); + let (was, steps) = (centers(&s), undo_len(&s)); + // From 5 to 9: 0.25 / 0.65 of each distance from the middle, which stays where it is. + let r = s.execute("symbol.setDensity", &json!({"from": 5, "to": 9})).unwrap(); + assert_eq!(r, json!({"ids": [set.0], "count": 8})); + assert_eq!(undo_len(&s), steps + 1); + let now = centers(&s); + let (m, ratio) = (middle(&was), 0.25 / 0.65); + assert!(middle(&now).distance(m) < 1e-9); + for (before, after) in was.iter().zip(&now) { + assert!(after.distance(m + (*before - m) * ratio) < 1e-9, "{before:?} -> {after:?}"); + } + // Back from 9 to 5: where they were, once for a set named twice. + let r = s.execute("symbol.setDensity", &json!({"from": 9, "to": 5, "ids": [set.0, set.0]})).unwrap(); + assert_eq!(r, json!({"ids": [set.0], "count": 8})); + assert!(centers(&s).iter().zip(&was).all(|(a, b)| a.distance(*b) < 1e-9)); + // The density the set has (5, a `from` of 7 notwithstanding): no instance moves and no undo + // step is added. + let steps = undo_len(&s); + assert_eq!(s.execute("symbol.setDensity", &json!({"from": 7, "to": 5})).unwrap(), json!({"ids": [], "count": 0})); + assert_eq!(undo_len(&s), steps); + // Undo puts a spaced set back. + s.execute("symbol.setDensity", &json!({"from": 5, "to": 1, "id": set.0})).unwrap(); + assert!(centers(&s)[0].distance(was[0]) > 1.0); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(centers(&s).iter().zip(&was).all(|(a, b)| a.distance(*b) < 1e-9)); +} + +/// A set packs from the density it was created at, whatever `from` says and whatever density more +/// instances were sprayed into it at; a set without a recorded density packs from `from`. +#[test] +fn set_density_starts_from_the_density_a_set_was_sprayed_at() { + let mut s = session(); + let row: Vec = (0..4).map(|i| json!([60.0 + 60.0 * f64::from(i), 150.0])).collect(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": row, "radius": 4, "density": 2})).unwrap()["id"].as_u64().unwrap()); + let ids = members(&s, set); + let xs = |s: &Session| ids.iter().map(|id| center(s, *id).x).collect::>(); + let was = xs(&s); + let middle = was.iter().sum::() / 4.0; + s.execute("symbol.setDensity", &json!({"from": 5, "to": 9})).unwrap(); + let ratio = 0.25 / 0.95; + for (before, after) in was.iter().zip(xs(&s)) { + assert!((after - (middle + (before - middle) * ratio)).abs() < 1e-9, "{before} -> {after}"); + } + // Given density 2, the set stays at 2 when more instances are sprayed into it at 9. + s.execute("symbol.setDensity", &json!({"from": 5, "to": 2, "ids": [set.0]})).unwrap(); + s.execute("symbol.spray", &json!({"name": "Dot", "points": [[300, 200]], "radius": 4, "density": 9})).unwrap(); + assert_eq!(s.execute("symbol.setDensity", &json!({"from": 9, "to": 2, "ids": [set.0]})).unwrap()["count"], 0); + // Without the record (a set grouped by hand), `from` is the starting density. + let mut s = session(); + let (a, b) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 200.0, 150.0)); + s.select(|_, sel| sel.set([a, b])).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Name", |d, _| { + if let Some(n) = d.node_mut(group) { + n.name = Some("Symbol Set".into()); + } + Ok(()) + }) + .unwrap(); + s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [group.0]})).unwrap(); + assert!((center(&s, a).x - (150.0 - 50.0 * 0.25 / 0.65)).abs() < 1e-9, "{:?}", center(&s, a)); +} + +/// A set of one instance takes the new density without moving, as one undo step, so a later change +/// packs it from that density; setting the density it already has adds no undo step. +#[test] +fn set_density_gives_a_set_of_one_instance_the_new_density() { + let mut s = session(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[100, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let steps = undo_len(&s); + assert_eq!(s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [set.0]})).unwrap(), json!({"ids": [set.0], "count": 0})); + assert_eq!(undo_len(&s), steps + 1); + assert_eq!(s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [set.0]})).unwrap(), json!({"ids": [], "count": 0})); + assert_eq!(undo_len(&s), steps + 1); + // A second instance, then from the set's 9 to 5: 0.65 / 0.25 of each distance from the middle. + s.select(|_, sel| sel.set([set])).unwrap(); + s.execute("symbol.spray", &json!({"name": "Dot", "points": [[200, 150]], "radius": 4, "density": 9})).unwrap(); + let ids = members(&s, set); + assert_eq!(ids.len(), 2); + let was: Vec = ids.iter().map(|id| center(&s, *id)).collect(); + let middle = Point::new((was[0].x + was[1].x) / 2.0, (was[0].y + was[1].y) / 2.0); + s.execute("symbol.setDensity", &json!({"from": 5, "to": 5, "ids": [set.0]})).unwrap(); + for (id, before) in ids.iter().zip(&was) { + let want = middle + (*before - middle) * (0.65 / 0.25); + assert!(center(&s, *id).distance(want) < 1e-9, "{before:?} -> {:?}", center(&s, *id)); + } +} + +/// A locked instance of the set stays where it is, and the others move. +#[test] +fn set_density_leaves_a_locked_instance_in_place() { + let mut s = session(); + let row: Vec = (0..3).map(|i| json!([100.0 + 80.0 * f64::from(i), 150.0])).collect(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": row, "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let ids = members(&s, set); + s.edit("Lock", |d, _| { + if let Some(n) = d.node_mut(ids[0]) { + n.locked = true; + } + Ok(()) + }) + .unwrap(); + let was: Vec = ids.iter().map(|id| center(&s, *id)).collect(); + let r = s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [set.0]})).unwrap(); + assert!(r["count"].as_u64().is_some_and(|n| (1..=2).contains(&n)), "{r}"); + assert_eq!(center(&s, ids[0]), was[0]); + assert!(center(&s, ids[2]).distance(was[2]) > 1.0); +} + +/// `symbol.setDensity` refuses a density left out, not a number or outside 1..10, an id naming no +/// object, and objects with no symbol set among them. +#[test] +fn set_density_refuses_bad_densities_and_objects_without_a_set() { + let mut s = session(); + let set = + NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[100, 150], [200, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap()); + for (p, want) in [ + (json!({"to": 5}), "missing `from`".to_string()), + (json!({"from": 5}), "missing `to`".to_string()), + (json!({"from": "5", "to": 6}), "`from` must be a number from 1 to 10, not \"5\"".to_string()), + (json!({"from": 5, "to": 11}), "`to` must be a number from 1 to 10, not 11".to_string()), + (json!({"from": 0, "to": 5}), "`from` must be a number from 1 to 10, not 0".to_string()), + (json!({"from": null, "to": 5}), "`from` must be a number from 1 to 10, not null".to_string()), + ] { + refused(&mut s, "symbol.setDensity", p, &want); + } + let before = state(&s); + assert!(s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [987_654]})).is_err()); + assert!(s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": "all"})).is_err()); + // An instance is not a set, and neither is nothing selected. + let member = members(&s, set)[0]; + assert!(s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [member.0]})).is_err()); + s.select(|_, sel| sel.clear()).unwrap(); + let r = s.execute("symbol.setDensity", &json!({"from": 5, "to": 9})); + assert!(matches!(&r, Err(EngineError::Other(msg)) if msg == "no symbol set selected"), "{r:?}"); + assert!(state(&s) == before); +} + +/// An instance with no size is shifted and screened as before; only Average, which needs its size, +/// leaves it as it is. +#[test] +fn an_instance_without_a_size_is_changed_by_every_method_but_average() { + // A Dot at 200, 150 whose size is 0, and Dots at the other centers. + let flat = |others: &[(f64, f64)]| { + let mut s = session(); + let a = dot(&mut s, 200.0, 150.0); + for (x, y) in others { + dot(&mut s, *x, *y); + } + s.edit("Flatten", |d, _| { + if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(a).map(|n| &mut n.kind) { + *xf = Affine::new([0.0, 0.0, 0.0, 0.0, 200.0, 150.0]); + } + Ok(()) + }) + .unwrap(); + (s, a) + }; + let (mut s, a) = flat(&[(210.0, 150.0)]); + let r = adjust(&mut s, json!({"tool": "shift", "points": [[200, 150], [205, 150]], "radius": 40, "intensity": 10})); + assert_eq!(r["count"], 2); + assert!(center(&s, a).x > 200.5, "{:?}", center(&s, a)); + let r = adjust(&mut s, json!({"tool": "screen", "points": [[205, 150]], "radius": 40, "intensity": 10})); + assert_eq!(r["count"], 2); + assert!(node(&s, a).opacity < 1.0); + // Average brings the other two toward their mean and leaves the one without a size as it is. + let (mut s, a) = flat(&[(190.0, 150.0), (210.0, 150.0)]); + adjust(&mut s, json!({"tool": "screen", "points": [[190, 150]], "radius": 2, "intensity": 10})); + let r = adjust(&mut s, json!({"tool": "screen", "points": [[200, 150]], "radius": 40, "intensity": 10, "method": "average"})); + assert_eq!(r["count"], 2); + assert_eq!(node(&s, a).opacity, 1.0); + // With only it under the brush there is no mean, and Average changes nothing. + let before = state(&s); + let r = adjust(&mut s, json!({"tool": "screen", "points": [[200, 150]], "radius": 5, "intensity": 10, "method": "average"})); + assert_eq!(r["count"], 0); + assert!(state(&s) == before); +} + +/// A stroke that leaves every instance under the brush as it is (each already at full stain, or +/// at the least opacity) counts none and adds no undo step. +#[test] +fn a_stroke_that_changes_no_instance_adds_no_undo_step() { + let mut s = session(); + dot(&mut s, 200.0, 150.0); + let full = json!(vec![[200, 150]; 12]); + for tool in ["stain", "screen"] { + adjust(&mut s, json!({"tool": tool, "points": full, "radius": 40, "intensity": 10, "color": "#ff0000"})); + let before = state(&s); + let r = adjust(&mut s, json!({"tool": tool, "points": [[200, 150]], "radius": 40, "intensity": 10, "color": "#ff0000"})); + assert_eq!(r["count"], 0, "{tool}"); + assert!(state(&s) == before, "{tool} changed the document"); + } +} + +/// An instance a stroke moves away and back to where it was is not counted, and the stroke adds +/// no undo step: the Shifter's drag out and back moves it 8 pt right, then 8 pt left. +#[test] +fn an_instance_moved_away_and_back_is_not_counted() { + let mut s = session(); + let id = dot(&mut s, 200.0, 150.0); + let before = state(&s); + let r = adjust(&mut s, json!({"tool": "shift", "points": [[196, 166], [212, 166], [196, 166]], "radius": 40, "intensity": 10})); + assert_eq!(bounds(&s, id).center(), Point::new(200.0, 150.0)); + assert_eq!(r["count"], 0); + assert!(state(&s) == before, "the stroke added an undo step"); +} diff --git a/crates/engine/src/tests/symbollib.rs b/crates/engine/src/tests/symbollib.rs index 02e45a7153..0992c1567a 100644 --- a/crates/engine/src/tests/symbollib.rs +++ b/crates/engine/src/tests/symbollib.rs @@ -84,7 +84,7 @@ fn the_builtin_library_is_original_art_generated_in_code() { let mut s = Session::new(); let list = run(&mut s, "symbol.libraries", json!({})); let libs = list["libraries"].as_array().unwrap(); - assert_eq!(libs.len(), 6, "{libs:?}"); + assert_eq!(libs.len(), 7, "{libs:?}"); assert_eq!((libs[0]["id"].as_str(), libs[0]["category"].as_str()), (Some("basic-shapes"), Some("builtIn"))); assert_eq!( (libs[1]["id"].as_str(), libs[1]["name"].as_str(), libs[1]["category"].as_str()), @@ -106,6 +106,10 @@ fn the_builtin_library_is_original_art_generated_in_code() { (libs[5]["id"].as_str(), libs[5]["name"].as_str(), libs[5]["category"].as_str()), (Some("weather-icons"), Some("Weather Icons"), Some("builtIn")) ); + assert_eq!( + (libs[6]["id"].as_str(), libs[6]["name"].as_str(), libs[6]["category"].as_str()), + (Some("media-controls"), Some("Media Controls"), Some("builtIn")) + ); let lib = run(&mut s, "symbol.library", json!({"library": "basic shapes"})); let names: Vec<&str> = lib["symbols"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect(); assert_eq!(names, ["Circle", "Square", "Rounded Square", "Triangle", "Diamond", "Hexagon", "Star", "Burst", "Arrow"]); @@ -245,6 +249,42 @@ fn weather_icons_library_lists_and_places() { } } +#[test] +fn media_controls_library_lists_and_places() { + let mut s = session(); + let lib = run(&mut s, "symbol.library", json!({"library": "media-controls"})); + let symbols = lib["symbols"].as_array().unwrap(); + assert_eq!(symbols.len(), 6, "media-controls must load with exactly 6 symbols"); + let names: Vec<&str> = symbols.iter().map(|x| x["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["Play", "Pause", "Stop", "Skip Next", "Shuffle", "Repeat"]); + let mut placed = Vec::new(); + for (i, name) in names.iter().enumerate() { + let r = run( + &mut s, + "symbol.addFromLibrary", + json!({"library": "media-controls", "name": name, "place": true, "x": 100.0 + 80.0 * i as f64, "y": 100.0}), + ); + assert_eq!(r["added"], json!([name])); + placed.push(r["placed"].as_u64().unwrap()); + } + let d = doc(&s); + for (i, name) in names.iter().enumerate() { + assert_eq!(d.symbol_nine_slice(name), None, "{name} should not carry 9-slice guides"); + assert!(matches!( + d.node(NodeId(placed[i])).map(|n| &n.kind), + Some(NodeKind::SymbolInstance { symbol, .. }) if symbol == *name + )); + let sym = d.symbols.iter().find(|s| s.name == *name).expect("symbol exists in document"); + assert!(matches!(sym.art.kind, NodeKind::Path { .. }), "{name} art should be a path"); + if let NodeKind::Path { path, .. } = &sym.art.kind { + assert!(!path.subpaths.is_empty(), "{name} path data must have subpaths"); + for sp in &path.subpaths { + assert!(!sp.anchors.is_empty(), "{name} subpath must contain anchor points"); + } + } + } +} + #[test] fn a_saved_library_reopens_and_its_symbols_join_another_document_in_one_step() { let dir = folder("user"); diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index 58f98237a6..8857378855 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -4129,3 +4129,34 @@ fn new_type_takes_the_normal_character_style_fill_not_the_current_fill() { let made = s.execute("text.create", &json!({"x": 100, "y": 400, "text": "Green", "color": "#00ff00"})).unwrap(); assert_eq!(obj(&s, NodeId(made["id"].as_u64().unwrap())).runs[0].style.fill, Paint::solid(Color::rgb(0.0, 1.0, 0.0))); } + +/// A client answers the question a Type tool click asks about type in a missing font through +/// `tool.setOption {key: "missingFontEdit", value: {token, ok}}`: OK starts the edit at the next poll. +#[test] +fn tool_set_option_answers_the_missing_font_question() { + let mut s = session(); + let r = s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Hello", "size": 20, "font": "Missing Test Family 8408"})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("type", v).unwrap(); + let t = obj(&s, id); + let (a, b) = vectorcraft_text::caret_position(&vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t), 2); + let at = t.xf * a.midpoint(b); + let mut asked = vec![]; + for k in [PointerKind::Down, PointerKind::Up] { + asked.extend(s.pointer(&PointerEvent::new(k, at.x + 0.1, at.y), v).unwrap()); + } + let token = asked + .iter() + .find_map(|r| match r { + UiRequest::Dialog(k, p) if k == "missingFontEdit" => p["token"].as_u64(), + _ => None, + }) + .unwrap_or_else(|| panic!("the missing-font question: {asked:?}")); + assert!(!s.tool_wants_text()); + s.set_tool_option_cmd(&json!({"key": "missingFontEdit", "value": {"token": token, "ok": true}})).unwrap(); + s.tool_poll(v, false).unwrap(); + assert!(s.tool_wants_text()); + assert_eq!(s.tool_options()["editing"], json!(id.0)); +} diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index 21ae0796d3..fe3deecbef 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -539,6 +539,196 @@ fn colour_table_delete_maps_pixels_to_the_nearest_color_left() { assert_eq!(sources(&preview(&mut s, json!({"preset": "No near red"}))), ["#0000ff", "#ff0000"]); } +/// The colors of a fixed palette mapped to transparent take one slot of Colors together with the +/// transparent pixels, so the opaque colors after them still fit: their pixels stay opaque, and the +/// pixels of the colors mapped to transparent become transparent. +#[test] +fn colour_table_fixed_palette_keeps_an_opaque_color() { + // 40×10: red, a near red and blue, and 10 px with nothing (transparent). + let mut s = session(40.0, 10.0); + rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#ff0000"); + rect(&mut s, [10.0, 0.0, 10.0, 10.0], "#ee1100"); + rect(&mut s, [20.0, 0.0, 10.0, 10.0], "#0000ff"); + for table in [ + json!({"customPalette": ["#ff0000", "#ee1100", "#0000ff"], "deleted": ["#ee1100"], "transparent": ["#ff0000"]}), + json!({"customPalette": ["#ff0000", "#0000ff"], "transparent": ["#ff0000"]}), + ] { + let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": table}); + let v = run(&mut s, "document.exportForWeb.preview", p.clone()); + let opaque: Vec<&Value> = v["colors"].as_array().unwrap().iter().filter(|c| c["transparent"] == false).map(|c| &c["source"]).collect(); + assert_eq!((opaque, v["colors"].as_array().unwrap().len()), (vec![&json!("#0000ff")], 2), "{p}"); + let img = pixels(&one(&mut s, p.clone())); + let alpha = |x: u32| img.get_pixel(x, 5).0[3]; + assert_eq!((alpha(5), alpha(15), img.get_pixel(25, 5).0, alpha(35)), (0, 0, [0, 0, 255, 255], 0), "{p}"); + } + // A color mapped to transparent that no pixel takes leaves its slot to an opaque color. + let mut u = session(20.0, 10.0); + rect(&mut u, [0.0, 0.0, 10.0, 10.0], "#0000ff"); + rect(&mut u, [10.0, 0.0, 10.0, 10.0], "#00ff00"); + let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": {"customPalette": ["#0000ff", "#00ff00", "#ff0000"], "transparent": ["#ff0000"]}}); + let img = pixels(&one(&mut u, p)); + assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(15, 5).0), ([0, 0, 255, 255], [0, 255, 0, 255])); + // At 256 colors a color mapped to transparent after 255 opaque ones still keeps an entry. + let full: Vec = + std::iter::once("#0000ff".to_string()).chain((1..255).map(|i| format!("#00{i:02x}00"))).chain(["#ff0000".to_string()]).collect(); + let p = json!({"format": "png8", "dither": "none", "colors": 256, "colorTable": {"customPalette": full, "transparent": ["#ff0000"]}}); + let img = pixels(&one(&mut s, p)); + assert_eq!((img.get_pixel(5, 5).0[3], img.get_pixel(25, 5).0, img.get_pixel(35, 5).0[3]), (0, [0, 0, 255, 255], 0)); + // With one opaque color and 255 mapped to transparent, the last of those does not fit, and its + // pixels still become transparent rather than taking the opaque color nearest them. + let mut d = session(30.0, 10.0); + rect(&mut d, [0.0, 0.0, 10.0, 10.0], "#0000ff"); + rect(&mut d, [10.0, 0.0, 10.0, 10.0], "#0000ee"); + let clear: Vec = (1..255).map(|i| format!("#00{i:02x}00")).chain(["#0000ee".to_string()]).collect(); + let palette: Vec = std::iter::once("#0000ff".to_string()).chain(clear.iter().cloned()).collect(); + let p = json!({"format": "png8", "dither": "none", "colors": 256, "colorTable": {"customPalette": palette, "transparent": clear}}); + let img = pixels(&one(&mut d, p)); + assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(15, 5).0[3], img.get_pixel(25, 5).0[3]), ([0, 0, 255, 255], 0, 0)); + // Without transparent pixels the colors mapped to transparent still take one slot together. + let mut t = session(30.0, 10.0); + rect(&mut t, [0.0, 0.0, 10.0, 10.0], "#ff0000"); + rect(&mut t, [10.0, 0.0, 10.0, 10.0], "#ee1100"); + rect(&mut t, [20.0, 0.0, 10.0, 10.0], "#0000ff"); + let p = json!({"format": "png8", "dither": "none", "colors": 2, "colorTable": { + "customPalette": ["#ff0000", "#ee1100", "#0000ff", "#00ff00"], "transparent": ["#ff0000", "#ee1100"], + }}); + let v = run(&mut t, "document.exportForWeb.preview", p.clone()); + assert_eq!(v["colors"].as_array().unwrap().len(), 2, "{v}"); + let img = pixels(&one(&mut t, p)); + assert_eq!((img.get_pixel(5, 5).0[3], img.get_pixel(15, 5).0[3], img.get_pixel(25, 5).0), (0, 0, [0, 0, 255, 255])); +} + +/// A color shifted by hand (`colorTable.shifted`) is written as the color picked wherever it is in +/// the image, the other colors stay, the table shows it as shifted and locked, and the preview is +/// the file. +#[test] +fn colour_table_shift_writes_the_picked_color_wherever_the_source_is() { + let mut s = session(30.0, 10.0); + rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#ff0000"); + rect(&mut s, [10.0, 0.0, 10.0, 10.0], "#0000ff"); + rect(&mut s, [20.0, 0.0, 10.0, 10.0], "#00ff00"); + let preview = |s: &mut Session, p: Value| run(s, "document.exportForWeb.preview", p); + let entry = |v: &Value, source: &str| v["colors"].as_array().unwrap().iter().find(|c| c["source"] == source).cloned().unwrap_or(Value::Null); + for format in ["gif", "png8"] { + let p = json!({"format": format, "dither": "none", "colorTable": {"shifted": {"#0000FF": "#FF8800"}}}); + let v = preview(&mut s, p.clone()); + let c = entry(&v, "#0000ff"); + assert_eq!( + (c["color"].as_str(), c["shifted"].as_bool(), c["locked"].as_bool(), c["webShifted"].as_bool()), + (Some("#ff8800"), Some(true), Some(true), Some(false)), + "{format}: {v}" + ); + assert_eq!((entry(&v, "#ff0000")["shifted"].as_bool(), entry(&v, "#ff0000")["color"].as_str()), (Some(false), Some("#ff0000"))); + let file = one(&mut s, p); + assert_eq!(v["bytes"].as_u64(), Some(file.len() as u64), "{format}: the preview is the file"); + let img = pixels(&file); + assert_eq!( + (img.get_pixel(5, 5).0, img.get_pixel(12, 2).0, img.get_pixel(18, 8).0, img.get_pixel(25, 5).0), + ([255, 0, 0, 255], [255, 136, 0, 255], [255, 136, 0, 255], [0, 255, 0, 255]), + "{format}" + ); + assert_eq!(distinct(&img), 3, "{format}"); + } + // A shifted color is kept when the colors are reduced, as a locked one is. + let two = preview(&mut s, json!({"colors": 2, "dither": "none", "colorTable": {"shifted": {"#00ff00": "#123456"}}})); + assert_eq!(entry(&two, "#00ff00")["color"], "#123456", "{two}"); + // With one slot to keep, the shifted color takes it before a locked one. + let p = json!({"colors": 2, "dither": "none", "colorTable": {"locked": ["#ff0000"], "shifted": {"#0000ff": "#123456"}}}); + let first = preview(&mut s, p); + assert_eq!(entry(&first, "#0000ff")["color"], "#123456", "{first}"); + // A source the table does not hold shifts nothing, and the shift stays with the settings. + let base = preview(&mut s, json!({"dither": "none"})); + let absent = preview(&mut s, json!({"dither": "none", "colorTable": {"shifted": {"#123456": "#000000"}}})); + assert_eq!(absent["colors"], base["colors"]); + // Two colors may be shifted to one color and keep their own sources. + let same = preview(&mut s, json!({"dither": "none", "colorTable": {"shifted": {"#ff0000": "#123456", "#0000ff": "#123456"}}})); + assert_eq!((entry(&same, "#ff0000")["color"].as_str(), entry(&same, "#0000ff")["color"].as_str()), (Some("#123456"), Some("#123456"))); + assert_eq!(entry(&same, "#00ff00")["shifted"], false); + // A shift by hand wins over web shift, web snap and a lock; transparency wins over it. + let p = + json!({"dither": "none", "webSnap": 100, "colorTable": {"shifted": {"#0000ff": "#fe0101"}, "webShift": ["#0000ff"], "locked": ["#0000ff"]}}); + let c = entry(&preview(&mut s, p), "#0000ff"); + assert_eq!((c["color"].as_str(), c["webShifted"].as_bool(), c["locked"].as_bool()), (Some("#fe0101"), Some(false), Some(true))); + let clear = json!({"dither": "none", "colorTable": {"shifted": {"#0000ff": "#fe0101"}, "transparent": ["#0000ff"]}}); + let v = preview(&mut s, clear.clone()); + assert!(v["colors"].as_array().unwrap().iter().all(|c| c["shifted"] == false), "{v}"); + assert_eq!(pixels(&one(&mut s, clear)).get_pixel(15, 5).0[3], 0); + // The settings keep the shifts in lowercase, drop a color shifted to itself, a deleted one and + // the web shift of a color shifted by hand. + let table = json!({"shifted": {"#0000FF": "#FE0101", "#FF0000": "#ff0000", "#00ff00": "#000000"}, "webShift": ["#0000ff", "#00ff00"], "deleted": ["#00ff00"]}); + let r = run(&mut s, "webExport.settings", json!({ "colorTable": table })); + let t = &r["settings"]["colorTable"]; + assert_eq!((&t["shifted"], &t["webShift"]), (&json!({"#0000ff": "#fe0101"}), &json!([]))); + // Another reduction keeps the shifts; a saved preset keeps them. + let r = run(&mut s, "webExport.settings", json!({"reduction": "adaptive"})); + assert_eq!(r["settings"]["colorTable"]["shifted"], json!({"#0000ff": "#fe0101"})); + run(&mut s, "webExport.presets.save", json!({"name": "Blue to red", "dither": "none", "colorTable": {"shifted": {"#0000ff": "#fe0101"}}})); + assert_eq!(entry(&preview(&mut s, json!({"preset": "Blue to red"})), "#0000ff")["color"], "#fe0101"); + // Bad shifts are refused and change nothing. + let many: serde_json::Map = (0..257).map(|i| (format!("#{i:06x}"), json!("#000000"))).collect(); + for bad in [ + json!({"nope": "#000000"}), + json!({"#ff0000": "nope"}), + json!({"#ff0000": "#ff000080"}), + json!({"#ff000080": "#000000"}), + json!({"#ff0000": "#000000", "#FF0000": "#ffffff"}), + json!({"#f00": "#000000", "#ff0000": "#ffffff"}), + Value::Object(many), + ] { + let p = json!({"colorTable": {"shifted": bad}}); + assert!(s.execute("document.exportForWeb", &p).is_err(), "{p}"); + assert!(s.execute("document.exportForWeb.preview", &p).is_err(), "{p}"); + assert!(s.execute("webExport.settings", &p).is_err(), "{p}"); + } + assert_eq!(run(&mut s, "webExport.settings", json!({}))["settings"]["colorTable"]["shifted"], json!({"#0000ff": "#fe0101"})); + // Settings saved before shifts existed still read. + let old: cmd::webexport::WebSettings = serde_json::from_value(json!({"colorTable": {"locked": ["#ff0000"]}})).unwrap(); + assert!(old.color_table.shifted.is_empty()); +} + +/// Lossy GIF compression leaves the pixels of a color shifted by hand alone, so a color shifted near +/// another one does not take in that color's pixels. +#[test] +fn lossy_does_not_spread_a_shifted_color_into_another() { + let mut s = session(30.0, 10.0); + rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#0000ff"); + rect(&mut s, [10.0, 0.0, 20.0, 10.0], "#c80000"); + let p = json!({"format": "gif", "dither": "none", "lossy": 100, "colorTable": {"shifted": {"#0000ff": "#be0000"}}}); + let img = pixels(&one(&mut s, p)); + assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(20, 5).0, img.get_pixel(29, 5).0), ([190, 0, 0, 255], [200, 0, 0, 255], [200, 0, 0, 255])); +} + +/// Lossy GIF compression moves no pixel into or out of a color shifted by hand: the colors next to +/// a shifted one keep their own pixels, and the shifted color keeps all of its pixels. +#[test] +fn lossy_moves_no_pixel_into_or_out_of_a_shifted_color() { + let mut s = session(30.0, 10.0); + rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#1414e6"); + rect(&mut s, [10.0, 0.0, 20.0, 10.0], "#0000ff"); + rect(&mut s, [20.0, 0.0, 30.0, 10.0], "#1414e6"); + let p = json!({"format": "gif", "dither": "none", "lossy": 100, "colorTable": {"shifted": {"#0000ff": "#ff0000"}}}); + let img = pixels(&one(&mut s, p)); + let near_blue = [20, 20, 230, 255]; + for x in 0..30 { + let want = if (10..20).contains(&x) { [255, 0, 0, 255] } else { near_blue }; + assert_eq!(img.get_pixel(x, 5).0, want, "x = {x}"); + } +} + +/// Lossy GIF compression compares the pixels with the colors web snap writes, so a pixel does not +/// take a color that snaps far from it. +#[test] +fn lossy_compares_pixels_with_the_snapped_colors() { + let mut s = session(20.0, 10.0); + rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#1a1a1a"); + rect(&mut s, [10.0, 0.0, 20.0, 10.0], "#000000"); + let img = pixels(&one(&mut s, json!({"format": "gif", "dither": "none", "webSnap": 100, "lossy": 50}))); + for x in 0..20 { + let want = if x < 10 { [51, 51, 51, 255] } else { [0, 0, 0, 255] }; + assert_eq!(img.get_pixel(x, 5).0, want, "x = {x}"); + } +} + #[test] fn presets_and_remembered_settings() { let mut s = two_colours(); diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index a3470617a7..3aea7f3041 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -480,6 +480,41 @@ fn reflect_and_shear_tools() { assert!((b.width() - 150.0).abs() < 1e-6, "{b:?}"); } +/// Two clicks with the Reflect tool reflect the selection across the line through both points as +/// one undo step; with Alt on the second click, a copy is reflected and Undo removes it. +#[test] +fn two_reflect_clicks_reflect_across_their_line_as_one_undo_step() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0); + s.select_tool("reflect", ViewInfo::default()).unwrap(); + let click = |s: &mut Session, x: f64, y: f64, alt: bool| { + drag_at(s, PointerKind::Down, (x, y), alt); + drag_at(s, PointerKind::Up, (x, y), alt); + }; + let n = undo_len(&s); + click(&mut s, 300.0, 50.0, false); + assert_eq!(undo_len(&s), n); + assert!(close(bounds(&s, a), Rect::new(100.0, 100.0, 200.0, 150.0))); + click(&mut s, 300.0, 250.0, false); + assert!(close(bounds(&s, a), Rect::new(400.0, 100.0, 500.0, 150.0)), "{:?}", bounds(&s, a)); + assert_eq!(undo_len(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(close(bounds(&s, a), Rect::new(100.0, 100.0, 200.0, 150.0))); + + let children = |s: &Session| s.doc().unwrap().doc.layers[0].children().unwrap().len(); + click(&mut s, 50.0, 300.0, false); + click(&mut s, 350.0, 300.0, true); + assert_eq!(children(&s), 2); + assert!(close(bounds(&s, a), Rect::new(100.0, 100.0, 200.0, 150.0))); + // The copy is selected and reflected across y = 300. + let copy = s.doc().unwrap().selection.objects.clone(); + assert!(copy.len() == 1 && copy[0] != a, "{copy:?}"); + assert!(close(bounds(&s, copy[0]), Rect::new(100.0, 450.0, 200.0, 500.0)), "{:?}", bounds(&s, copy[0])); + assert_eq!(undo_len(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(children(&s), 1); +} + /// Reflect and Shear return an error for an `axis` they don't take, naming it (both also take an /// angle, Shear's from -359° to 359°): nothing moves and no undo step is recorded. A null `axis` counts as not given: Reflect /// then reflects across the vertical axis and Shear shears along the horizontal one. diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 794cc7a2a3..5f36c5a98e 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -35,6 +35,9 @@ pub struct ViewInfo { pub snap_to_glyph: bool, /// View → Show Corner Widget. pub corner_widgets: bool, + /// The Control bar's Show Shape Widgets: selected live shapes show their corner, pie and side + /// widgets to the Selection tool and the shape tools. + pub shape_widgets: bool, /// The document window (none headless): screen-fixed widgets sit in it. pub screen: Option, /// The view's active artboard (an index): artboard rulers measure from it. @@ -55,6 +58,7 @@ impl Default for ViewInfo { snap_to_point: true, snap_to_glyph: false, corner_widgets: true, + shape_widgets: true, screen: None, artboard: 0, } @@ -188,8 +192,7 @@ impl Session { .then(|| self.tool.options().get("meshPoints").cloned()) .flatten() .filter(|v| v.as_array().is_some_and(|a| !a.is_empty())); - let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx)); - self.apply_actions(acts)?; + self.deactivate_tool(view)?; self.keep_tool_settings(); self.tool = self.make_tool(id); if let Some(selection) = text_selection { @@ -205,6 +208,18 @@ impl Session { Ok(()) } + /// Deactivate the tool and apply the actions it returns. In a batch, a Cancel is left out: the + /// batch settled the tool's drag when it began, and the open interaction holds the batch's + /// steps, which the batch keeps or rolls back as a whole. + pub(crate) fn deactivate_tool(&mut self, view: ViewInfo) -> Result<()> { + let mut acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx)); + if self.batch_stash.is_some() { + acts.retain(|a| !matches!(a, Action::Cancel)); + } + self.apply_actions(acts)?; + Ok(()) + } + /// The selection tools other than Direct Selection pick whole objects: with one of them chosen, /// an object selected in a symbol instance's art gives way to the instance. The revision /// changes with it, so panels that cache by revision show the instance. @@ -297,8 +312,7 @@ impl Session { // them all (#8090). Group Selection picks no mesh points, so the Eyedropper keeps its own. let mesh_points = (lender.id() == "eyedropper" && self.tool.id() != "groupSelection").then(|| self.tool.options().get("meshPoints").cloned()).flatten(); - let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx)); - let r = self.apply_actions(acts); + let r = self.deactivate_tool(view); self.keep_tool_settings(); self.tool = lender; if let Some(points) = mesh_points { @@ -311,7 +325,7 @@ impl Session { self.lent_selection = left; } self.after_command(None); - r.map(drop) + r } /// A fresh `id` tool with the options it keeps ([`settings`]): its last values, from this @@ -410,6 +424,7 @@ impl Session { snap_to_glyph: view.snap_to_glyph && smart_guides && !view.snap_to_grid, glyph_snap: self.prefs.glyph_snap, corner_widgets: view.corner_widgets, + shape_widgets: view.shape_widgets, fill_active: self.fill_active, gradient_stop: self.selected_stop(), appearance_item: self.appearance_item(), @@ -466,6 +481,7 @@ impl Session { plane_targets: self.prefs.perspective_widget.targets(), precise_cursors: self.precise_cursors(), global_edit: st.global_edit.as_ref().map_or(&[], |g| g.members.as_slice()), + interaction_doc: st.interaction.as_ref().map(|it| &*it.doc), }; let tool = &mut self.tool; match crate::guard::catch_panic(|| f(tool.as_mut(), &cx)) { @@ -1403,6 +1419,7 @@ impl Session { } // Every value is checked before any is set, so an invalid one changes nothing. vectorcraft_tools::builder::check_builder_options(id, &values)?; + vectorcraft_tools::symbolism::check_options(id, &values)?; if id == vectorcraft_tools::cropimage::ID { use vectorcraft_tools::cropimage as crop; // The most the selected image can be cropped to, when one is selected. diff --git a/crates/engine/tests/blend_render_consistency.rs b/crates/engine/tests/blend_render_consistency.rs new file mode 100644 index 0000000000..fdc2fb3b93 --- /dev/null +++ b/crates/engine/tests/blend_render_consistency.rs @@ -0,0 +1,200 @@ +//! Blend edits invalidate every pixel they change, including keys aligned to a curved spine. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::sync::Arc; + +use serde_json::json; +use vectorcraft_doc::{Document, NodeId, NodeKind}; +use vectorcraft_engine::Session; +use vectorcraft_geom::Affine; +use vectorcraft_render::{Changed, RenderOptions, Rendered, Renderer, view_pixels}; + +const WIDTH: u32 = 720; +const HEIGHT: u32 = 480; + +type Retained = (Renderer, Option<(Arc, Vec)>); + +fn live(s: &Session, blend: NodeId, keys: [NodeId; 2], curved: bool) { + let doc = &s.doc().unwrap().doc; + let NodeKind::Blend { children, spec } = &doc.node(blend).unwrap().kind else { + panic!("INPUT: the fixture must remain a live blend"); + }; + assert_eq!(children.iter().map(|n| n.id).collect::>(), keys.to_vec()); + assert_eq!(serde_json::to_value(spec).unwrap()["spacing"], json!({"steps": 3})); + for key in keys { + assert_eq!(doc.parent_of(key), Some(blend), "INPUT: key identity/parent changed"); + } + if curved { + let bounds = spec.spine.as_ref().expect("INPUT: Replace Spine did not set a spine").bounds().unwrap(); + assert!(!spec.no_spine && bounds.height() > 40.0 && bounds.width() > 250.0, "INPUT: a real curved spine is required"); + } +} + +fn fixture() -> (Session, NodeId, [NodeId; 2]) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": WIDTH, "height": HEIGHT})).unwrap(); + let mut rectangle = |x: f64, color: &str| { + let id = NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 120.0, "width": 64.0, "height": 48.0})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"color": color})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + id + }; + let keys = [rectangle(90.0, "#d52c38"), rectangle(430.0, "#25b453")]; + let blend = NodeId( + s.execute("object.blend.make", &json!({"ids": [keys[0].0, keys[1].0], "steps": 3, "orientation": "path"})).unwrap()["id"].as_u64().unwrap(), + ); + assert_eq!(s.doc().unwrap().selection.objects, vec![blend]); + live(&s, blend, keys, false); + (s, blend, keys) +} + +fn cpu() -> Renderer { + let mut renderer = Renderer::new(); + renderer.threads = 0; + renderer +} + +fn same_pixels(actual: &Rendered, expected: &Rendered) { + assert_eq!((actual.width, actual.height), (WIDTH, HEIGHT)); + assert_eq!((expected.width, expected.height), (WIDTH, HEIGHT)); + assert_eq!(actual.pixels.len(), (WIDTH * HEIGHT * 4) as usize); + assert!(actual.pixels == expected.pixels, "complete RGBA frames differ"); +} + +fn damage_pixels(stage: &str, changed: Changed, before: &[u8], current: &[u8]) { + let region = match changed { + Changed::Everything => return, + Changed::Nothing => None, + Changed::Area(area) => view_pixels(area, Affine::IDENTITY, WIDTH, HEIGHT), + }; + assert_eq!(before.len(), current.len()); + for (i, (old, new)) in before.as_chunks::<4>().0.iter().zip(current.as_chunks::<4>().0.iter()).enumerate() { + let (x, y) = (i as u32 % WIDTH, i as u32 / WIDTH); + if !region.is_some_and(|[x0, y0, x1, y1]| x >= x0 && x < x1 && y >= y0 && y < y1) { + assert_eq!(old, new, "{stage}: pixel ({x}, {y}) changed outside {changed:?}, view pixels {region:?}"); + } + } +} + +fn frame(s: &Session, retained: &mut Retained, stage: &str) -> Rendered { + let doc = &s.doc().unwrap().doc; + let opts = RenderOptions { background: Some([255, 255, 255, 255]), artboards: false, ..Default::default() }; + // Ask for the edit's advertised damage before rendering the new full frame on this renderer. + let changed = retained.1.as_ref().map(|(old, _)| retained.0.changed(old.as_ref(), doc.as_ref(), &opts)); + let actual = retained.0.render(doc.as_ref(), WIDTH, HEIGHT, Affine::IDENTITY, &opts); + let expected = cpu().render(doc.as_ref(), WIDTH, HEIGHT, Affine::IDENTITY, &opts); + same_pixels(&actual, &expected); + let red = expected.pixels.as_chunks::<4>().0.iter().filter(|p| p[0] > 150 && p[1] < 100 && p[2] < 120 && p[3] == 255).count(); + let green = expected.pixels.as_chunks::<4>().0.iter().filter(|p| p[0] < 100 && p[1] > 120 && p[2] < 150 && p[3] == 255).count(); + assert!(red > 100 && green > 100, "INPUT: both original colored keys must really draw: red={red}, green={green}"); + if let (Some((_, previous)), Some(changed)) = (&retained.1, changed) { + damage_pixels(stage, changed, previous, &expected.pixels); + } + retained.1 = Some((doc.clone(), expected.pixels)); + actual +} + +fn move_and_undo(s: &mut Session, retained: &mut Retained, blend: NodeId, keys: [NodeId; 2], curved: bool, before_frame: &Rendered) { + assert_eq!(s.doc().unwrap().selection.objects, vec![blend]); + let before = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(); + s.execute("object.transform", &json!({"matrix": [1.0, 0.0, 0.0, 1.0, 37.0, 29.0]})).unwrap(); + live(s, blend, keys, curved); + assert_eq!(s.doc().unwrap().selection.objects, vec![blend]); + let moved = frame(s, retained, "moved"); + assert!(moved.pixels != before_frame.pixels, "INPUT: the fresh rendered fixture must actually move"); + s.execute("edit.undo", &json!({})).unwrap(); + live(s, blend, keys, curved); + assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), before); + assert_eq!(s.doc().unwrap().selection.objects, vec![blend]); + let restored = frame(s, retained, "undo-move"); + same_pixels(&restored, before_frame); +} + +#[test] +fn blend_5179_straight_move_undo_matches_fresh_cpu() { + let (mut s, blend, keys) = fixture(); + let mut retained = (cpu(), None); + let warm = frame(&s, &mut retained, "warm"); + move_and_undo(&mut s, &mut retained, blend, keys, false, &warm); +} + +#[test] +fn blend_5179_replace_spine_move_undo_matches_fresh_cpu() { + let (mut s, blend, keys) = fixture(); + let path = NodeId(s.execute("path.create", &json!({"d": "M122 144 C166 330 402 288 462 144"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [blend.0, path.0]})).unwrap(); + let before = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(); + let nodes = s.doc().unwrap().doc.node_count(); + let mut retained = (cpu(), None); + let warm = frame(&s, &mut retained, "before-replace"); + s.execute("object.blend.replaceSpine", &json!({})).unwrap(); + live(&s, blend, keys, true); + assert!(s.doc().unwrap().doc.node(path).is_none(), "Replace Spine consumes the original standalone path"); + assert_eq!(s.doc().unwrap().doc.node_count(), nodes - 1); + assert_eq!(s.doc().unwrap().selection.objects, vec![blend]); + let replaced = frame(&s, &mut retained, "replaced"); + assert!(replaced.pixels != warm.pixels, "INPUT: replacing the spine must visibly change the drawn fixture"); + move_and_undo(&mut s, &mut retained, blend, keys, true, &replaced); + s.execute("edit.undo", &json!({})).unwrap(); + live(&s, blend, keys, false); + assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), before); + let restored = frame(&s, &mut retained, "undo-replace"); + same_pixels(&restored, &warm); +} + +// A fixed ordinary anisotropic Transform, evaluated after Align to Path turns the key. +// 200% is the legitimate control; 400% is the single source-derived witness. +fn rotated_transform_damage(scale_h: f64) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": WIDTH, "height": HEIGHT})).unwrap(); + let mut rectangle = |x: f64, color: &str| { + let id = NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 200.0, "width": 8.0, "height": 80.0})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"color": color})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"scaleH": scale_h, "scaleV": 100.0, "reference": 4}})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + let b = n.geometric_bounds().unwrap(); + assert!((b.width() - 8.0).abs() < 1e-8 && (b.height() - 80.0).abs() < 1e-8, "INPUT: the Transform must remain live on the narrow key"); + assert_eq!(n.appearance.effects.len(), 1); + assert_eq!(n.appearance.effects[0].params["scaleH"], json!(scale_h)); + id + }; + let keys = [rectangle(260.0, "#d52c38"), rectangle(460.0, "#25b453")]; + let blend = NodeId( + s.execute("object.blend.make", &json!({"ids": [keys[0].0, keys[1].0], "steps": 3, "orientation": "path"})).unwrap()["id"].as_u64().unwrap(), + ); + live(&s, blend, keys, false); + let path = NodeId(s.execute("path.create", &json!({"d": "M264 160 L264 320"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [blend.0, path.0]})).unwrap(); + let before = serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(); + let mut retained = (cpu(), None); + let warm = frame(&s, &mut retained, "anisotropic-before-replace"); + s.execute("object.blend.replaceSpine", &json!({})).unwrap(); + live(&s, blend, keys, false); + assert!(s.doc().unwrap().doc.node(path).is_none()); + assert_eq!(s.doc().unwrap().selection.objects, vec![blend]); + let n = s.doc().unwrap().doc.node(blend).unwrap(); + let NodeKind::Blend { spec, .. } = &n.kind else { panic!("INPUT: the fixture must remain a live blend") }; + let spine = spec.spine.as_ref().unwrap().bounds().unwrap(); + assert!(spine.width().abs() < 1e-8 && (spine.height() - 160.0).abs() < 1e-8, "INPUT: this is the fixed vertical rail"); + let expanded = vectorcraft_render::expand_live(n); + let placed = expanded.iter().find(|n| n.id == keys[0]).unwrap(); + let b = placed.geometric_bounds().unwrap(); + assert!((b.width() - 80.0).abs() < 1e-8 && (b.height() - 8.0).abs() < 1e-8, "INPUT: Align to Path must really turn the key by 90 degrees"); + assert_eq!(placed.appearance.effects.len(), 1); + assert_eq!(placed.appearance.effects[0].params["scaleH"], json!(scale_h)); + let replaced = frame(&s, &mut retained, &format!("rotated-transform-{scale_h}-replace")); + assert!(replaced.pixels != warm.pixels, "INPUT: the replacement must really change the painted frame"); + move_and_undo(&mut s, &mut retained, blend, keys, false, &replaced); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(s.doc().unwrap().doc.as_ref()).unwrap(), before); + let restored = frame(&s, &mut retained, "anisotropic-undo-replace"); + same_pixels(&restored, &warm); +} + +#[test] +fn blend_5179_rotated_transform_damage_contains_painted_pixels() { + // The control completes every render, move and history check before the witness runs. + rotated_transform_damage(200.0); + rotated_transform_damage(400.0); +} diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index a7d516f8eb..7c0aef252e 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -8,7 +8,7 @@ use std::sync::{Mutex, MutexGuard}; use serde_json::json; use vectorcraft_color::cms; use vectorcraft_engine::Session; -use vectorcraft_engine::cmd::colormgmt::{PROFILES_KEY, doc_profiles}; +use vectorcraft_engine::cmd::colormgmt::{PROFILES_KEY, ProfileChoice, ProfileIssue, doc_profiles}; use vectorcraft_engine::store::MAX_PRESET_FILE; use vectorcraft_geom::Affine; use vectorcraft_render::{RenderOptions, Renderer}; @@ -1082,3 +1082,615 @@ fn color_management_policies_are_checked_and_kept() { next.attach_color_settings(file); assert_eq!(cms::active_settings(), cms::ColorSettings::default()); } + +/// The Ask boxes of Edit › Color Settings are checked, come back in the reply and are kept in +/// `Color Settings.json`. +#[test] +fn ask_boxes_are_checked_and_kept() { + let _g = settings(); + let dir = fresh_dir("ask-kept"); + let _reset = ColorSettingsReset { profile: None, paths: vec![dir.clone()] }; + let file = dir.join("Color Settings.json"); + let mut s = session(); + s.attach_color_settings(file.clone()); + let r = exec(&mut s, "edit.colorSettings", json!({})); + assert_eq!( + (r["askMismatchOpen"].as_bool(), r["askMismatchPaste"].as_bool(), r["askMissingOpen"].as_bool()), + (Some(false), Some(false), Some(false)) + ); + for bad in [json!({"askMismatchOpen": "yes"}), json!({"askMismatchPaste": 1}), json!({"askMissingOpen": []})] { + assert!(s.execute("edit.colorSettings", &bad).is_err(), "{bad}"); + } + assert!(!file.exists(), "a refused change keeps nothing"); + let r = exec(&mut s, "edit.colorSettings", json!({"askMismatchOpen": true, "askMissingOpen": true})); + assert_eq!( + (r["askMismatchOpen"].as_bool(), r["askMismatchPaste"].as_bool(), r["askMissingOpen"].as_bool()), + (Some(true), Some(false), Some(true)) + ); + let saved: cms::ColorSettings = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + assert!(saved.ask_mismatch_open && !saved.ask_mismatch_paste && saved.ask_missing_open); +} + +/// Two saved documents with a blue rectangle (`blue`, filled `blue0`): `tagged`, assigned Wide +/// Gamut RGB, and `plain`, untagged. The files go when it drops, and the Color Settings go back to +/// the defaults. +struct ProfileFiles { + _reset: ColorSettingsReset, + _dir: vectorcraft_testkit::TempDir, + tagged: std::path::PathBuf, + plain: std::path::PathBuf, + blue: vectorcraft_doc::NodeId, + blue0: vectorcraft_color::Color, +} + +#[allow(clippy::unwrap_used, reason = "a test helper: a file that can't be written fails the test")] +fn profile_files(tag: &str) -> ProfileFiles { + let dir = fresh_dir(tag); + let reset = ColorSettingsReset { profile: None, paths: vec![dir.clone()] }; + std::fs::create_dir_all(&dir).unwrap(); + let (tagged, plain) = (dir.join("tagged.vectorcraft"), dir.join("plain.vectorcraft")); + let mut s = session(); + let blue = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [blue.0], "color": "#3366cc"})); + exec(&mut s, "file.saveAs", json!({"path": plain.to_str().unwrap()})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + exec(&mut s, "file.saveAs", json!({"path": tagged.to_str().unwrap()})); + let blue0 = fill_of(&s, blue); + ProfileFiles { _reset: reset, _dir: dir, tagged, plain, blue, blue0 } +} + +/// The fill color of object `id` in the active document. +#[allow(clippy::unwrap_used, reason = "a test helper: a missing object or fill fails the test")] +fn fill_of(s: &Session, id: vectorcraft_doc::NodeId) -> vectorcraft_color::Color { + s.doc().unwrap().doc.node(id).and_then(|n| n.appearance.fill()).and_then(|f| f.paint.color()).unwrap() +} + +/// `document.open` of `path` with the params `extra` in a new session → the reply, and the session. +#[allow(clippy::unwrap_used, reason = "a test helper: params that are not an object fail the test")] +fn open_with(path: &std::path::Path, extra: serde_json::Value) -> (Result, Session) { + let mut s = session(); + let mut p = json!({"path": path.to_str().unwrap()}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + let r = s.execute("document.open", &p).map_err(|e| e.to_string()); + (r, s) +} + +/// `document.open`'s `profileChoice` answers what Color Settings' Profile Mismatches box asks: for +/// a document tagged with another profile than the working space of its color mode it keeps the +/// profile, converts the colors or discards the profile in place of the policy. A missing choice +/// for it is not used. +#[test] +fn profile_choice_answers_a_mismatch() { + let _g = settings(); + let ProfileFiles { tagged, blue, blue0, .. } = &profile_files("profile-mismatch"); + let (tagged, blue, blue0) = (tagged.as_path(), *blue, *blue0); + let fill = |s: &Session| fill_of(s, blue); + let open = open_with; + let mut s = session(); + + // Each choice in place of the policy (Preserve Embedded Profiles). + let (r, kept) = open(tagged, json!({"profileChoice": "useEmbedded"})); + let r = r.unwrap(); + assert_eq!(r["profileChoice"], json!({"issue": "mismatch", "model": "rgb", "choice": "useEmbedded"})); + assert_eq!((doc_profiles(&kept.doc().unwrap().doc).0, fill(&kept)), (Some(cms::WIDE_GAMUT_RGB.into()), blue0)); + let (r, discarded) = open(tagged, json!({"profileChoice": "discard"})); + let r = r.unwrap(); + assert_eq!((doc_profiles(&discarded.doc().unwrap().doc).0, fill(&discarded)), (None, blue0), "the numbers stay"); + assert!(discarded.doc().unwrap().is_dirty()); + assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("as chosen when it was opened")), "{r}"); + let (r, converted) = open(tagged, json!({"profileChoice": "convert"})); + assert_eq!(r.unwrap()["profileChoice"]["choice"], "convert"); + let source = cms::for_document(Some(cms::WIDE_GAMUT_RGB), None); + let blue1 = fill(&converted); + assert_eq!(doc_profiles(&converted.doc().unwrap().doc).0, None); + assert!(blue1 != blue0 && cms::delta_e2000(source.lab(&blue0), cms::working().lab(&blue1)) < 1.0, "{blue0:?} → {blue1:?}"); + // Under policy Off, Use Embedded keeps the profile. + exec(&mut s, "edit.colorSettings", json!({"rgbPolicy": "off"})); + let (_, kept) = open(tagged, json!({"profileChoice": "useEmbedded"})); + assert_eq!(doc_profiles(&kept.doc().unwrap().doc).0, Some(cms::WIDE_GAMUT_RGB.into())); + // A missing choice for a mismatched document is not used: the policy applies. + let (r, off) = open(tagged, json!({"profileChoice": "leave"})); + assert!(r.unwrap().get("profileChoice").is_none()); + assert_eq!(doc_profiles(&off.doc().unwrap().doc).0, None); +} + +/// `document.open`'s `profileChoice` answers what the Missing Profiles box asks: an untagged +/// document is left, assigned the working space or assigned a profile, its numbers kept. A +/// mismatch choice for it is not used, and wrong choices are refused. +#[test] +fn profile_choice_answers_a_missing_profile() { + let _g = settings(); + let ProfileFiles { tagged, plain, blue, blue0, .. } = &profile_files("profile-missing"); + let (tagged, plain, blue, blue0) = (tagged.as_path(), plain.as_path(), *blue, *blue0); + let fill = |s: &Session| fill_of(s, blue); + let open = open_with; + let (r, left) = open(plain, json!({"profileChoice": "leave"})); + assert_eq!(r.unwrap()["profileChoice"], json!({"issue": "missing", "model": "rgb", "choice": "leave"})); + assert_eq!(doc_profiles(&left.doc().unwrap().doc).0, None); + assert!(!left.doc().unwrap().is_dirty()); + let (_, working) = open(plain, json!({"profileChoice": "assignWorking"})); + assert_eq!(doc_profiles(&working.doc().unwrap().doc).0.as_deref(), Some(cms::canonical_name(cms::SRGB))); + assert!(working.doc().unwrap().is_dirty()); + let (_, p3) = open(plain, json!({"profileChoice": "assign", "assignProfile": cms::DISPLAY_P3})); + assert_eq!((doc_profiles(&p3.doc().unwrap().doc).0, fill(&p3)), (Some(cms::DISPLAY_P3.into()), blue0), "assigning keeps the numbers"); + // A mismatch choice for an untagged document is not used. + let (r, plain_kept) = open(plain, json!({"profileChoice": "convert"})); + assert!(r.unwrap().get("profileChoice").is_none()); + assert_eq!(doc_profiles(&plain_kept.doc().unwrap().doc).0, None); + + for bad in [ + json!({"profileChoice": "bogus"}), + json!({"profileChoice": "assign"}), + json!({"profileChoice": "discard", "assignProfile": cms::DISPLAY_P3}), + json!({"assignProfile": cms::DISPLAY_P3}), + json!({"profileChoice": 3}), + ] { + assert!(open(tagged, bad.clone()).0.is_err(), "{bad}"); + } + let (r, none) = open(plain, json!({"profileChoice": "assign", "assignProfile": cms::DEVICE_CMYK})); + assert!(r.unwrap_err().contains("unknown rgb profile"), "a CMYK profile can't tag an RGB document"); + assert_eq!(none.documents().len(), 1, "nothing opened"); +} + +/// The app's half of the open prompts: a file read with asking stops at the question when its box +/// is on (never without asking), and opens as answered, or as the policy says when it opens +/// unanswered. A refused answer leaves it waiting. +#[test] +fn a_read_waits_for_the_profile_answer() { + let _g = settings(); + let ProfileFiles { tagged, plain, blue, blue0, .. } = &profile_files("profile-wait"); + let (blue, blue0) = (*blue, *blue0); + let fill = |s: &Session| fill_of(s, blue); + let mut s = session(); + let source = cms::for_document(Some(cms::WIDE_GAMUT_RGB), None); + let blue1 = source.convert_into(&cms::working(), &blue0, cms::working().settings().intent); + let bytes = std::fs::read(tagged).unwrap(); + let name = tagged.to_str().unwrap(); + let read = + |ask: bool| vectorcraft_engine::cmd::fileio::read_for_open_asking(name, &bytes, Some(name.into()), &json!({}), false, false, ask).unwrap(); + assert!(read(true).question().is_none(), "the box is off"); + exec(&mut s, "edit.colorSettings", json!({"askMismatchOpen": true, "rgbPolicy": "convert"})); + assert!(read(false).question().is_none(), "document.open never asks"); + let mut waiting = read(true); + let q = waiting.question().unwrap(); + assert_eq!((q.issue, q.profile.as_deref(), q.default.id()), (ProfileIssue::Mismatch, Some(cms::WIDE_GAMUT_RGB), "convert")); + assert_eq!(waiting.name(), "tagged.vectorcraft"); + waiting.answer(ProfileChoice::Discard).unwrap(); + assert!(waiting.question().is_none(), "answered"); + let mut opened = session(); + let r = vectorcraft_engine::cmd::fileio::open_read(&mut opened, waiting).unwrap(); + assert_eq!(r["profileChoice"]["choice"], "discard"); + assert_eq!((doc_profiles(&opened.doc().unwrap().doc).0, fill(&opened)), (None, blue0)); + // Unanswered, it opens as the policy (Convert to Working Space) says. + let mut opened = session(); + vectorcraft_engine::cmd::fileio::open_read(&mut opened, read(true)).unwrap(); + assert_eq!((doc_profiles(&opened.doc().unwrap().doc).0, fill(&opened)), (None, blue1)); + // A missing answer to a mismatch is not used: the policy decides. + let mut waiting = read(true); + waiting.answer(ProfileChoice::Leave).unwrap(); + let mut opened = session(); + let r = vectorcraft_engine::cmd::fileio::open_read(&mut opened, waiting).unwrap(); + assert!(r.get("profileChoice").is_none()); + assert_eq!(fill(&opened), blue1); + // Missing Profiles: Ask When Opening, starting on assigning the working space under Convert. + exec(&mut s, "edit.colorSettings", json!({"askMismatchOpen": false, "askMissingOpen": true})); + assert!(read(true).question().is_none(), "the mismatch box is off now"); + let plain_bytes = std::fs::read(plain).unwrap(); + let mut waiting = + vectorcraft_engine::cmd::fileio::read_for_open_asking("plain.vectorcraft", &plain_bytes, None, &json!({}), false, false, true).unwrap(); + let q = waiting.question().unwrap(); + assert_eq!((q.issue, q.profile.as_deref(), q.default.id()), (ProfileIssue::Missing, None, "assignWorking")); + assert!(waiting.answer(ProfileChoice::Assign(cms::DEVICE_CMYK.into())).is_err(), "not an RGB profile"); + assert!(waiting.question().is_some(), "still waiting after a refused answer"); + waiting.answer(ProfileChoice::Assign(cms::DISPLAY_P3.into())).unwrap(); + let mut opened = session(); + vectorcraft_engine::cmd::fileio::open_read(&mut opened, waiting).unwrap(); + assert_eq!(doc_profiles(&opened.doc().unwrap().doc).0, Some(cms::DISPLAY_P3.into())); +} + +/// An answer is taken only while the question it answers stands: once Color Settings change the +/// working space so that the question goes away or names another working space, the answer is +/// refused and the file keeps waiting. Asked again, it takes the answer to the question it asks now. +#[test] +fn a_profile_answer_waits_for_the_question_it_answers() { + let _g = settings(); + let ProfileFiles { tagged, blue, blue0, .. } = &profile_files("profile-changed"); + let (blue, blue0) = (*blue, *blue0); + let mut s = session(); + exec(&mut s, "edit.colorSettings", json!({"askMismatchOpen": true})); + let bytes = std::fs::read(tagged).unwrap(); + let name = tagged.to_str().unwrap(); + let mut waiting = vectorcraft_engine::cmd::fileio::read_for_open_asking(name, &bytes, Some(name.into()), &json!({}), false, false, true).unwrap(); + assert_eq!(waiting.question().unwrap().working, cms::canonical_name(cms::SRGB)); + // The working space becomes the file's profile: the question is gone. + exec(&mut s, "edit.colorSettings", json!({"rgb": cms::WIDE_GAMUT_RGB})); + assert!(waiting.answer(ProfileChoice::Discard).is_err(), "the question it answers is gone"); + // Another working space: the question names it. + exec(&mut s, "edit.colorSettings", json!({"rgb": cms::DISPLAY_P3})); + let err = waiting.answer(ProfileChoice::Discard).unwrap_err().to_string(); + assert!(err.contains("the profile question changed since it was asked"), "{err}"); + assert_eq!(waiting.ask().unwrap().working, cms::canonical_name(cms::DISPLAY_P3)); + waiting.answer(ProfileChoice::Discard).unwrap(); + let mut opened = session(); + let r = vectorcraft_engine::cmd::fileio::open_read(&mut opened, waiting).unwrap(); + assert_eq!(r["profileChoice"]["choice"], "discard"); + assert_eq!((doc_profiles(&opened.doc().unwrap().doc).0, fill_of(&opened, blue)), (None, blue0)); +} + +/// Swatch conflicts are checked against the colors as the paste brings them: a global swatch whose +/// name and color match the destination's conflicts once the paste converts it, and pasting back +/// into its own document with conversion compares its swatches too. +#[test] +fn swatch_conflicts_follow_the_profile_conversion() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + exec(&mut s, "swatch.new", json!({"name": "Brand", "color": "#3366cc", "global": true})); + let r = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [r.0], "swatch": "Brand"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + select(&mut s, &[r]); + exec(&mut s, "edit.copy", json!({})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + exec(&mut s, "swatch.new", json!({"name": "Brand", "color": "#3366cc", "global": true})); + let conflicts = |s: &mut Session, p: serde_json::Value| exec(s, "clipboard.conflicts", p)["swatches"].as_array().unwrap().len(); + assert_eq!(conflicts(&mut s, json!({})), 0, "the numbers are kept: the same color"); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert"})), 1, "converted, it differs"); + assert!(s.execute("clipboard.conflicts", &json!({"profileMismatch": "keep"})).is_err()); + // Back in the first document, under another working space, a converting paste compares too. + exec(&mut s, "document.activate", json!({"index": 0})); + exec(&mut s, "edit.assignProfile", json!({"rgb": null})); + assert_eq!(conflicts(&mut s, json!({})), 0); + assert_eq!(conflicts(&mut s, json!({"profileMismatch": "convert"})), 1); +} + +/// A paste is a mismatch only for the models the copied colors use: CMYK art from a document with +/// other RGB and CMYK profiles is a CMYK mismatch alone, and so is an artboard copied without art +/// whose background is CMYK. +#[test] +fn a_paste_mismatches_only_the_models_its_colors_use() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + let ink = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [ink.0], "color": {"c": 20, "m": 40, "y": 60, "k": 10}})); + exec(&mut s, "paint.setStroke", json!({"ids": [ink.0], "none": true})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB, "cmyk": cms::DEVICE_CMYK})); + select(&mut s, &[ink]); + exec(&mut s, "edit.copy", json!({})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + let models = |s: &mut Session| -> Vec { + let r = exec(s, "clipboard.profileMismatch", json!({})); + r["mismatches"].as_array().unwrap().iter().map(|m| m["model"].as_str().unwrap().to_string()).collect() + }; + assert_eq!(models(&mut s), ["cmyk"]); + exec(&mut s, "document.activate", json!({"index": 0})); + exec(&mut s, "artboard.setProps", json!({"index": 0, "color": {"c": 0, "m": 100, "y": 0, "k": 0}})); + exec(&mut s, "artboard.copy", json!({"index": 0})); + exec(&mut s, "document.activate", json!({"index": 1})); + assert_eq!(models(&mut s), ["cmyk"]); +} + +/// An artboard copied without art from a document with another profile is a mismatch through its +/// background color, which converts with a paste that converts. +#[test] +fn a_pasted_artboard_background_converts() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + exec(&mut s, "artboard.setProps", json!({"index": 0, "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + exec(&mut s, "artboard.copy", json!({"index": 0})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + assert_eq!(exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"][0]["model"], "rgb"); + let r = exec(&mut s, "edit.paste", json!({"profileMismatch": "convert"})); + let i = r["artboards"][0].as_u64().unwrap() as usize; + let paper = s.doc().unwrap().doc.artboards[i].color.unwrap(); + let blue0 = vectorcraft_color::Color::from_hex("#3366cc").unwrap(); + let source = cms::for_document(Some(cms::WIDE_GAMUT_RGB), None); + assert!(paper != blue0 && cms::delta_e2000(source.lab(&blue0), cms::working().lab(&paper)) < 1.0, "{blue0:?} → {paper:?}"); +} + +/// Paste compares the profiles the copied colors showed through with the destination's: a model +/// whose profile differs and whose colors the objects use is a mismatch (clipboard.profileMismatch). +/// Its colors keep their numbers or convert, as `profileMismatch` says, else as the policy says; +/// the reply lists what was done. +#[test] +fn paste_keeps_or_converts_colors_from_another_profile() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + let blue = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [blue.0], "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB, "cmyk": cms::DEVICE_CMYK})); + select(&mut s, &[blue]); + exec(&mut s, "edit.copy", json!({})); + let blue0 = vectorcraft_color::Color::from_hex("#3366cc").unwrap(); + // Back in the same document: nothing to compare. + assert_eq!(exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"], json!([])); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + let r = exec(&mut s, "clipboard.profileMismatch", json!({})); + // Only RGB: the objects use no CMYK color. + let srgb = cms::canonical_name(cms::SRGB); + assert_eq!( + r["mismatches"], + json!([{"model": "rgb", "clipboard": cms::WIDE_GAMUT_RGB, "document": srgb, "default": "preserveNumbers", "convertible": true}]) + ); + let pasted = |s: &mut Session, p: serde_json::Value| { + let r = exec(s, "edit.paste", p); + let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap()); + let c = s.doc().unwrap().doc.node(id).and_then(|n| n.appearance.fill()).and_then(|f| f.paint.color()).unwrap(); + (r, c) + }; + let (r, kept) = pasted(&mut s, json!({})); + assert_eq!(kept, blue0, "the policy (Preserve Embedded Profiles) keeps the numbers"); + assert_eq!(r["profileMismatch"][0]["choice"], "preserveNumbers"); + let (r, moved) = pasted(&mut s, json!({"profileMismatch": "convert"})); + assert_eq!(r["profileMismatch"][0]["choice"], "convert"); + let source = cms::for_document(Some(cms::WIDE_GAMUT_RGB), None); + assert!(moved != blue0 && cms::delta_e2000(source.lab(&blue0), cms::working().lab(&moved)) < 1.0, "{blue0:?} → {moved:?}"); + exec(&mut s, "edit.colorSettings", json!({"rgbPolicy": "convert"})); + assert_eq!(exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"][0]["default"], "convert"); + let (_, by_policy) = pasted(&mut s, json!({})); + assert_eq!(by_policy, moved, "Convert to Working Space converts"); + let (_, numbers) = pasted(&mut s, json!({"profileMismatch": "preserveNumbers"})); + assert_eq!(numbers, blue0); + for bad in [json!({"profileMismatch": "keep"}), json!({"profileMismatch": true})] { + assert!(s.execute("edit.paste", &bad).is_err(), "{bad}"); + } + // A drag from the first document follows the policy too. + let source = s.documents()[0].uid; + let r = exec(&mut s, "edit.dropSelection", json!({"sourceDocument": source, "ids": [blue.0], "grab": [5, 5], "at": [50, 50]})); + let dropped = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap()); + let c = s.doc().unwrap().doc.node(dropped).and_then(|n| n.appearance.fill()).and_then(|f| f.paint.color()).unwrap(); + assert_eq!(c, moved, "dropped colors convert under Convert to Working Space"); + // A destination assigned the source's profile has nothing to compare. + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + assert_eq!(exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"], json!([])); + let (r, same) = pasted(&mut s, json!({})); + assert!(r.get("profileMismatch").is_none()); + assert_eq!(same, blue0); +} + +/// A drag between documents is a paste for Profile Mismatches: clipboard.profileMismatch with +/// `sourceDocument` and `ids` lists what the drop brings, edit.dropSelection takes `profileMismatch` +/// and reports what it did, and a wrong choice drops nothing. +#[test] +fn a_drop_takes_the_profile_mismatch_choice() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + let blue = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [blue.0], "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + let source = s.documents()[0].uid; + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + let blue0 = vectorcraft_color::Color::from_hex("#3366cc").unwrap(); + assert_eq!(exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"], json!([]), "the clipboard is empty"); + let dragged = json!({"sourceDocument": source, "ids": [blue.0]}); + let srgb = cms::canonical_name(cms::SRGB); + assert_eq!( + exec(&mut s, "clipboard.profileMismatch", dragged.clone())["mismatches"], + json!([{"model": "rgb", "clipboard": cms::WIDE_GAMUT_RGB, "document": srgb, "default": "preserveNumbers", "convertible": true}]) + ); + for bad in [json!({"sourceDocument": source}), json!({"ids": [blue.0]}), json!({"sourceDocument": 999_999, "ids": [blue.0]})] { + assert!(s.execute("clipboard.profileMismatch", &bad).is_err(), "{bad}"); + } + let dropped = |s: &mut Session, choice: Option<&str>| { + let mut p = json!({"sourceDocument": source, "ids": [blue.0], "grab": [5, 5], "at": [50, 50]}); + if let Some(c) = choice { + p["profileMismatch"] = json!(c); + } + let r = exec(s, "edit.dropSelection", p); + let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap()); + (r, s.doc().unwrap().doc.node(id).and_then(|n| n.appearance.fill()).and_then(|f| f.paint.color()).unwrap()) + }; + let (r, kept) = dropped(&mut s, None); + assert_eq!((kept, &r["profileMismatch"][0]["choice"]), (blue0, &json!("preserveNumbers")), "the policy keeps the numbers"); + let (r, moved) = dropped(&mut s, Some("convert")); + assert_eq!(r["profileMismatch"][0]["choice"], "convert"); + let from = cms::for_document(Some(cms::WIDE_GAMUT_RGB), None); + assert!(moved != blue0 && cms::delta_e2000(from.lab(&blue0), cms::working().lab(&moved)) < 1.0, "{blue0:?} → {moved:?}"); + let objects = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + let before = objects(&s); + let bad = json!({"sourceDocument": source, "ids": [blue.0], "grab": [5, 5], "at": [50, 50], "profileMismatch": "keep"}); + assert!(s.execute("edit.dropSelection", &bad).is_err()); + assert_eq!(objects(&s), before, "a refused choice drops nothing"); +} + +/// `assignProfile` beside another choice than `assign` is refused with a message that says it goes +/// with `assign` only. +#[test] +fn assign_profile_goes_with_assign_only() { + let _g = settings(); + let ProfileFiles { tagged, .. } = &profile_files("profile-assign-only"); + let err = open_with(tagged, json!({"profileChoice": "discard", "assignProfile": cms::DISPLAY_P3})).0.unwrap_err(); + assert!(err.contains("`assignProfile` goes with `profileChoice`: \"assign\" only"), "{err}"); +} + +/// `profileMismatch: {rgb?, cmyk?}` gives each model its own choice, and a model left out follows +/// its policy; a key other than rgb and cmyk, or a value other than the two choices, is refused and +/// pastes nothing. +#[test] +fn paste_takes_a_choice_for_each_model() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + let both = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [both.0], "color": "#3366cc"})); + exec(&mut s, "paint.setStroke", json!({"ids": [both.0], "color": {"c": 20, "m": 40, "y": 60, "k": 10}})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB, "cmyk": cms::DEVICE_CMYK})); + let stroke_of = |s: &Session, id: vectorcraft_doc::NodeId| { + s.doc().unwrap().doc.node(id).and_then(|n| n.appearance.stroke()).and_then(|f| f.paint.color()).unwrap() + }; + let ink0 = stroke_of(&s, both); + select(&mut s, &[both]); + exec(&mut s, "edit.copy", json!({})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + exec(&mut s, "edit.colorSettings", json!({"cmykPolicy": "convert"})); + let blue0 = vectorcraft_color::Color::from_hex("#3366cc").unwrap(); + let pasted = |s: &mut Session, choice: serde_json::Value| { + let r = exec(s, "edit.paste", json!({ "profileMismatch": choice })); + let id = vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap()); + let fill = s.doc().unwrap().doc.node(id).and_then(|n| n.appearance.fill()).and_then(|f| f.paint.color()).unwrap(); + let picked = |model: &str| r["profileMismatch"].as_array().unwrap().iter().find(|m| m["model"] == model).map(|m| m["choice"].clone()); + (fill, stroke_of(s, id), picked("rgb"), picked("cmyk")) + }; + // The CMYK policy (Convert to Working Space) converts the stroke from Device CMYK into the + // working CMYK space, as a paste that leaves both models to their policies does. + let (_, ink, rgb_policy, cmyk_policy) = pasted(&mut s, serde_json::Value::Null); + assert_eq!((rgb_policy, &cmyk_policy), (Some(json!("preserveNumbers")), &Some(json!("convert")))); + let device = cms::for_document(None, Some(cms::DEVICE_CMYK)); + assert!(ink != ink0 && cms::delta_e2000(device.lab(&ink0), cms::working().lab(&ink)) < 2.0, "{ink0:?} → {ink:?}"); + let converted_ink = ink; + let (fill, ink, rgb, cmyk) = pasted(&mut s, json!({"rgb": "convert"})); + assert_eq!((rgb, &cmyk, ink), (Some(json!("convert")), &cmyk_policy, converted_ink), "CMYK follows its policy"); + let source = cms::for_document(Some(cms::WIDE_GAMUT_RGB), None); + assert!(fill != blue0 && cms::delta_e2000(source.lab(&blue0), cms::working().lab(&fill)) < 1.0, "{blue0:?} → {fill:?}"); + let (fill, ink, rgb, cmyk) = pasted(&mut s, json!({"cmyk": "preserveNumbers"})); + assert_eq!((fill, ink, rgb, cmyk), (blue0, ink0, Some(json!("preserveNumbers")), Some(json!("preserveNumbers"))), "the inks keep their values"); + let objects = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + let before = objects(&s); + for bad in [json!({"lab": "convert"}), json!({"rgb": "keep"}), json!({"rgb": 1}), json!([]), json!(true)] { + assert!(s.execute("edit.paste", &json!({ "profileMismatch": bad })).is_err(), "{bad}"); + assert!(s.execute("clipboard.conflicts", &json!({ "profileMismatch": bad })).is_err(), "{bad}"); + } + assert_eq!(objects(&s), before, "a refused choice pastes nothing"); +} + +/// The fill color of the first object a paste reply `r` names, in the active document. +#[allow(clippy::unwrap_used, reason = "a test helper: a reply without objects fails the test")] +fn pasted_fill(s: &Session, r: &serde_json::Value) -> vectorcraft_color::Color { + fill_of(s, vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())) +} + +/// A document assigned a profile that was removed since draws through the working space, and its +/// copied colors come from the working space too: pasted into a document with another profile, they +/// convert from it as `profileMismatch` says. +#[test] +fn a_removed_assigned_profile_pastes_as_the_working_space() { + const NAME: &str = "Removed Wide RGB"; + let _g = settings(); + let _reset = ColorSettingsReset { profile: Some(NAME), paths: vec![] }; + cms::register_icc(&cms::icc_bytes(cms::WIDE_GAMUT_RGB).unwrap(), Some(NAME.into())).unwrap(); + let mut s = session(); + let blue = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [blue.0], "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": NAME})); + exec(&mut s, "color.removeProfile", json!({"name": NAME})); + select(&mut s, &[blue]); + exec(&mut s, "edit.copy", json!({})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::DISPLAY_P3})); + let m = exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"][0].clone(); + assert_eq!((&m["clipboard"], &m["convertible"]), (&json!(cms::canonical_name(cms::SRGB)), &json!(true)), "{m}"); + let r = exec(&mut s, "edit.paste", json!({"profileMismatch": "convert"})); + assert_eq!(r["profileMismatch"][0]["choice"], "convert"); + let (blue0, moved) = (vectorcraft_color::Color::from_hex("#3366cc").unwrap(), pasted_fill(&s, &r)); + let p3 = cms::for_document(Some(cms::DISPLAY_P3), None); + assert!(moved != blue0 && cms::delta_e2000(cms::working().lab(&blue0), p3.lab(&moved)) < 1.0, "{blue0:?} → {moved:?}"); +} + +/// Colors copied from a document whose profile was removed after the copy can't convert: the +/// mismatch says so (convertible false, and default preserveNumbers under a converting policy), and +/// a paste that asks to convert keeps their numbers. +#[test] +fn colors_from_a_profile_removed_after_the_copy_keep_their_numbers() { + const NAME: &str = "Copied Wide RGB"; + let _g = settings(); + let _reset = ColorSettingsReset { profile: Some(NAME), paths: vec![] }; + cms::register_icc(&cms::icc_bytes(cms::WIDE_GAMUT_RGB).unwrap(), Some(NAME.into())).unwrap(); + let mut s = session(); + let blue = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [blue.0], "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": NAME})); + select(&mut s, &[blue]); + exec(&mut s, "edit.copy", json!({})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + exec(&mut s, "edit.colorSettings", json!({"rgbPolicy": "convert"})); + let m = exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"][0].clone(); + assert_eq!((&m["default"], &m["convertible"]), (&json!("convert"), &json!(true)), "both profiles are here: {m}"); + exec(&mut s, "color.removeProfile", json!({"name": NAME})); + let m = exec(&mut s, "clipboard.profileMismatch", json!({}))["mismatches"][0].clone(); + assert_eq!((&m["clipboard"], &m["default"], &m["convertible"]), (&json!(NAME), &json!("preserveNumbers"), &json!(false)), "{m}"); + let r = exec(&mut s, "edit.paste", json!({"profileMismatch": "convert"})); + assert_eq!(r["profileMismatch"][0]["choice"], "preserveNumbers"); + assert_eq!(pasted_fill(&s, &r), vectorcraft_color::Color::from_hex("#3366cc").unwrap()); +} + +/// Paste on All Artboards leaves copied artboards behind, so their backgrounds raise no mismatch for +/// it: clipboard.profileMismatch with allArtboards lists none, and the paste reports none. A plain +/// paste, which brings the artboard, still lists the background's model. +#[test] +fn paste_on_all_artboards_leaves_artboard_backgrounds_out() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + let ink = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [ink.0], "color": {"c": 20, "m": 40, "y": 60, "k": 10}})); + exec(&mut s, "paint.setStroke", json!({"ids": [ink.0], "none": true})); + exec(&mut s, "artboard.setProps", json!({"index": 0, "color": "#3366cc"})); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + exec(&mut s, "artboard.copy", json!({"index": 0})); + exec(&mut s, "file.new", json!({"width": 100, "height": 100})); + let models = |s: &mut Session, p: serde_json::Value| exec(s, "clipboard.profileMismatch", p)["mismatches"].as_array().unwrap().len(); + assert_eq!(models(&mut s, json!({})), 1, "a plain paste brings the RGB background"); + assert_eq!(models(&mut s, json!({"allArtboards": true})), 0); + assert!(s.execute("clipboard.profileMismatch", &json!({"allArtboards": "yes"})).is_err()); + let r = exec(&mut s, "edit.pasteOnAllArtboards", json!({"profileMismatch": "convert"})); + assert!(r.get("profileMismatch").is_none(), "{r}"); +} + +/// A converting paste back into the document the objects came from (its profile changed since the +/// copy) still takes its image blobs as the document's own: an image whose blob under its key +/// changed since keeps that key, and so shows the document's blob. +#[test] +fn a_converting_paste_into_its_own_document_keeps_its_image_keys() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let mut s = session(); + let blue = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [blue.0], "color": "#3366cc"})); + let blob = |b: u8| vectorcraft_doc::ImageBlob::png(vec![b; 8]); + let image = s + .edit("Place", |d, _| { + d.images.insert("pic".into(), blob(1)); + let id = d.alloc_id(); + let im = vectorcraft_doc::ImageObject { + key: "pic".into(), + width: 4, + height: 4, + xf: Affine::translate((20.0, 0.0)), + link: None, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, vectorcraft_doc::Node::new(id, vectorcraft_doc::NodeKind::Image(Box::new(im))))?; + Ok(id) + }) + .unwrap(); + select(&mut s, &[blue, image]); + exec(&mut s, "edit.copy", json!({})); + s.edit("Replace Image", |d, _| { + d.images.insert("pic".into(), blob(2)); + Ok(()) + }) + .unwrap(); + exec(&mut s, "edit.assignProfile", json!({"rgb": cms::WIDE_GAMUT_RGB})); + let r = exec(&mut s, "edit.paste", json!({"profileMismatch": "convert"})); + assert_eq!(r["profileMismatch"][0]["choice"], "convert"); + let doc = &s.doc().unwrap().doc; + let keys: Vec = r["ids"] + .as_array() + .unwrap() + .iter() + .filter_map(|id| match &doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap()))?.kind { + vectorcraft_doc::NodeKind::Image(im) => Some(im.key.clone()), + _ => None, + }) + .collect(); + assert_eq!(keys, ["pic"]); + assert_eq!(doc.images.len(), 1, "no copy of the old blob"); +} diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 4f49a25b03..b8114f705c 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -1012,6 +1012,8 @@ fn structured_junk() { ("addon.pathtools.bridge", json!({"radius": 1e-308, "keepOriginals": "x"})), ("addon.pathtools.bridge", json!({"radius": 1000, "keepOriginals": true, "ids": [0, 1, 2, 3, u64::MAX]})), ("addon.pathtools.bridge", json!({"radius": f64::MAX, "ids": [1, 1], "junk": [0]})), + ("addon.pathtools.bridge", json!({"gap": -1e308, "reach": f64::MAX, "ids": [0, 1, 2]})), + ("addon.pathtools.bridge", json!({"gap": 1000, "reach": 10000, "radius": null, "keepOriginals": true})), // Refused before anything is written: no format of that name, a time that is no time. ("addon.document.saveTimestampedCopy", json!({"format": "png", "folder": 7})), ("addon.document.saveTimestampedCopy", json!({"format": "svg", "time": [1e308], "folder": null})), diff --git a/crates/engine/tests/ellipse_drag_anchors.rs b/crates/engine/tests/ellipse_drag_anchors.rs new file mode 100644 index 0000000000..afce996136 --- /dev/null +++ b/crates/engine/tests/ellipse_drag_anchors.rs @@ -0,0 +1,197 @@ +//! Ellipse arrow keys edit the anchor count of the shape actually being dragged. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use serde_json::{Value, json}; +use vectorcraft_doc::{LiveShape, Node, NodeId}; +use vectorcraft_engine::{Session, ViewInfo}; +use vectorcraft_geom::{AnchorKind, Rect}; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + +fn run(s: &mut Session, command: &str, params: Value) -> Value { + s.execute(command, ¶ms).unwrap() +} + +fn view() -> ViewInfo { + ViewInfo { smart_guides: false, snap_to_point: false, snap_to_grid: false, snap_to_pixel: false, ..ViewInfo::default() } +} + +fn fixture() -> (Session, NodeId) { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 700, "height": 500})); + let other = NodeId(run(&mut s, "shape.rectangle", json!({"x": 400, "y": 300, "width": 30, "height": 20}))["id"].as_u64().unwrap()); + run(&mut s, "select.none", json!({})); + s.select_tool("ellipse", view()).unwrap(); + (s, other) +} + +fn pointer(s: &mut Session, view: ViewInfo, kind: PointerKind, x: f64, y: f64, mods: Mods) { + s.pointer(&PointerEvent::new(kind, x, y).with_mods(mods), view).unwrap(); +} + +fn begin(s: &mut Session, view: ViewInfo, mods: Mods) { + run(s, "select.none", json!({})); + pointer(s, view, PointerKind::Down, 100.0, 100.0, mods); + pointer(s, view, PointerKind::Drag, 220.0, 180.0, mods); +} + +fn key(s: &mut Session, view: ViewInfo, key: ToolKey) { + s.tool_key(key, Mods::default(), view).unwrap(); +} + +fn drawn(s: &Session) -> Node { + let st = s.doc().unwrap(); + assert_eq!(st.selection.objects.len(), 1, "one drawn ellipse is selected"); + st.doc.node(st.selection.objects[0]).unwrap().clone() +} + +fn count(s: &Session) -> usize { + drawn(s).path_data().unwrap().anchor_count() +} + +fn bounds_are(node: &Node, expected: Rect) { + let got = node.geometric_bounds().unwrap(); + for (a, b) in [(got.x0, expected.x0), (got.y0, expected.y0), (got.x1, expected.x1), (got.y1, expected.y1)] { + assert!((a - b).abs() < 1e-6, "bounds {got:?}, expected {expected:?}"); + } +} + +fn document(s: &Session) -> Value { + json!(s.doc().unwrap().doc) +} + +fn depth(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +#[test] +fn ellipse_drag_anchors_baseline_default_four_is_the_live_ellipse() { + let (mut s, _) = fixture(); + let before = depth(&s); + begin(&mut s, view(), Mods::default()); + let preview = drawn(&s); + assert_eq!(preview.path_data().unwrap().anchor_count(), 4); + assert!(matches!(preview.live_shape(), Some(LiveShape::Ellipse { .. }))); + bounds_are(&preview, Rect::new(100.0, 100.0, 220.0, 180.0)); + pointer(&mut s, view(), PointerKind::Up, 220.0, 180.0, Mods::default()); + assert_eq!(depth(&s), before + 1); + assert!(matches!(drawn(&s).live_shape(), Some(LiveShape::Ellipse { .. }))); +} + +#[test] +fn ellipse_drag_anchors_baseline_up_changes_preview_and_commits_once() { + let (mut s, other) = fixture(); + let before = document(&s); + let other_before = json!(s.doc().unwrap().doc.node(other)); + let history = depth(&s); + begin(&mut s, view(), Mods::default()); + assert_eq!(count(&s), 4, "normal drag before the key"); + key(&mut s, view(), ToolKey::Up); + assert_eq!(count(&s), 5, "Up changes the shape currently previewed"); + let preview = drawn(&s); + assert!(preview.live_shape().is_none(), "a non-four count is the existing plain path"); + assert!(preview.path_data().unwrap().subpaths.iter().all(|sp| sp.closed)); + assert!(preview.path_data().unwrap().subpaths.iter().flat_map(|sp| &sp.anchors).all(|a| a.kind == AnchorKind::Smooth)); + bounds_are(&preview, Rect::new(100.0, 100.0, 220.0, 180.0)); + pointer(&mut s, view(), PointerKind::Up, 220.0, 180.0, Mods::default()); + assert_eq!(count(&s), 5); + bounds_are(&drawn(&s), Rect::new(100.0, 100.0, 220.0, 180.0)); + assert_eq!(drawn(&s).appearance, preview.appearance); + assert_eq!(json!(s.doc().unwrap().doc.node(other)), other_before); + assert_eq!(depth(&s), history + 1, "keys update one preview, not separate edits"); + let after = document(&s); + run(&mut s, "edit.undo", json!({})); + assert_eq!(document(&s), before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(document(&s), after); + let idle = document(&s); + key(&mut s, view(), ToolKey::Up); + assert_eq!(document(&s), idle, "an idle tool key does not change existing art"); + assert_eq!(s.tool_options()["anchors"], 5); +} + +#[test] +fn ellipse_drag_anchors_limits_remembered_count_and_cancel_baseline() { + for (initial, pressed, expected) in [(2, ToolKey::Down, 2), (999, ToolKey::Up, 1000)] { + let (mut s, _) = fixture(); + s.set_tool_option("anchors", &json!(initial)); + begin(&mut s, view(), Mods::default()); + assert_eq!(count(&s), initial, "the remembered click count starts the drag"); + key(&mut s, view(), pressed); + key(&mut s, view(), pressed); + assert_eq!(count(&s), expected, "one step per key, clamped to the existing domain"); + bounds_are(&drawn(&s), Rect::new(100.0, 100.0, 220.0, 180.0)); + pointer(&mut s, view(), PointerKind::Up, 220.0, 180.0, Mods::default()); + s.select_tool("selection", view()).unwrap(); + s.select_tool("ellipse", view()).unwrap(); + assert_eq!(s.tool_options()["anchors"], expected); + } + let (mut s, _) = fixture(); + s.set_tool_option("anchors", &json!(6)); + let before = document(&s); + let history = depth(&s); + begin(&mut s, view(), Mods::default()); + key(&mut s, view(), ToolKey::Up); + assert_eq!(count(&s), 7); + key(&mut s, view(), ToolKey::Escape); + assert_eq!(document(&s), before); + assert_eq!(depth(&s), history); + assert_eq!(s.tool_options()["anchors"], 6, "Cancel restores the count before the drag"); + begin(&mut s, view(), Mods::default()); + key(&mut s, view(), ToolKey::Up); + s.set_tool_option("anchors", &json!(9)); + key(&mut s, view(), ToolKey::Up); + assert_eq!(count(&s), 10); + key(&mut s, view(), ToolKey::Escape); + assert_eq!(document(&s), before); + assert_eq!(depth(&s), history); + assert_eq!(s.tool_options()["anchors"], 9, "an explicit setting updates the Cancel baseline"); + s.select_tool("selection", view()).unwrap(); + s.select_tool("ellipse", view()).unwrap(); + assert_eq!(s.tool_options()["anchors"], 9, "the restored option survives switching tools"); +} + +#[test] +fn ellipse_drag_anchors_keys_keep_shift_alt_space_and_turned_axes() { + for angle in [0.0, 90.0] { + let (mut s, _) = fixture(); + s.prefs.constrain_angle = angle; + let mods = Mods { shift: true, alt: true, ..Mods::default() }; + pointer(&mut s, view(), PointerKind::Down, 100.0, 100.0, mods); + pointer(&mut s, view(), PointerKind::Drag, 180.0, 160.0, mods); + bounds_are(&drawn(&s), Rect::new(20.0, 20.0, 180.0, 180.0)); + key(&mut s, view(), ToolKey::Up); + assert_eq!(count(&s), 5); + bounds_are(&drawn(&s), Rect::new(20.0, 20.0, 180.0, 180.0)); + let moving = Mods { space: true, ..mods }; + pointer(&mut s, view(), PointerKind::Drag, 200.0, 180.0, moving); + bounds_are(&drawn(&s), Rect::new(40.0, 40.0, 200.0, 200.0)); + key(&mut s, view(), ToolKey::Up); + assert_eq!(count(&s), 6); + bounds_are(&drawn(&s), Rect::new(40.0, 40.0, 200.0, 200.0)); + pointer(&mut s, view(), PointerKind::Up, 200.0, 180.0, moving); + assert_eq!(count(&s), 6); + bounds_are(&drawn(&s), Rect::new(40.0, 40.0, 200.0, 200.0)); + } +} + +#[test] +fn ellipse_drag_anchors_key_keeps_the_tangent_snapped_box() { + let (mut s, _) = fixture(); + let line = NodeId(run(&mut s, "shape.line", json!({"x1": 40, "y1": 200, "x2": 260, "y2": 200}))["id"].as_u64().unwrap()); + let line_before = json!(s.doc().unwrap().doc.node(line)); + run(&mut s, "select.none", json!({})); + s.prefs.snap_tangent = true; + let snap = ViewInfo { smart_guides: true, snap_to_point: false, ..view() }; + let mods = Mods { shift: true, alt: true, ..Mods::default() }; + pointer(&mut s, snap, PointerKind::Down, 100.0, 100.0, mods); + pointer(&mut s, snap, PointerKind::Drag, 198.0, 130.0, mods); + // The pointer alone gives radius98; the horizontal line pulls the shown radius to100. + bounds_are(&drawn(&s), Rect::new(0.0, 0.0, 200.0, 200.0)); + key(&mut s, snap, ToolKey::Up); + assert_eq!(count(&s), 5); + bounds_are(&drawn(&s), Rect::new(0.0, 0.0, 200.0, 200.0)); + pointer(&mut s, snap, PointerKind::Up, 198.0, 130.0, mods); + assert_eq!(count(&s), 5); + bounds_are(&drawn(&s), Rect::new(0.0, 0.0, 200.0, 200.0)); + assert_eq!(json!(s.doc().unwrap().doc.node(line)), line_before); +} diff --git a/crates/engine/tests/eraser_open_fill.rs b/crates/engine/tests/eraser_open_fill.rs new file mode 100644 index 0000000000..a0ab760660 --- /dev/null +++ b/crates/engine/tests/eraser_open_fill.rs @@ -0,0 +1,2062 @@ +//! Fill-only open-path Eraser regressions through the public engine and CPU renderer. +// Integration tests may unwrap and panic on failure (AGENTS.md). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_engine::Session; +use vectorcraft_geom::{FillRule, PathData, Point}; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + s +} + +fn path(s: &Session, id: NodeId) -> &PathData { + match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Path { path, .. } => path, + _ => panic!("the fixture is a path"), + } +} + +fn paths(s: &Session) -> Vec { + let mut paths = vec![]; + s.doc().unwrap().doc.walk(|node| { + if let NodeKind::Path { path, .. } = &node.kind { + paths.push(path.clone()); + } + }); + paths +} + +// The varied setting necessarily selects erase_varied, while a circular nib keeps the +// same deterministic swept area as the fixed tip. No random input or device is involved. +fn erase(s: &mut Session, mut params: Value, varied: bool) -> Value { + if varied { + params["angleMode"] = json!("pressure"); + params["angleVariation"] = json!(30); + params["roundness"] = json!(100); + } + s.execute("path.eraseRegion", ¶ms).unwrap() +} + +fn eraser_preserves_the_fill_of_an_open_rectangle_case(varied: bool) { + let samples = [(110.0, 125.0), (190.0, 125.0), (110.0, 175.0), (190.0, 175.0)]; + let render = |s: &Session| { + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()) + }; + for closed in [true, false] { + let mut s = session(); + let id = NodeId( + s.execute( + "path.create", + &json!({"closed": closed, "anchors": [ + {"x": 100, "y": 100}, {"x": 200, "y": 100}, {"x": 200, "y": 200}, {"x": 100, "y": 200} + ]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(path(&s, id).is_closed(), closed); + let before = render(&s); + for (x, y) in samples.into_iter().chain([(150.0, 150.0)]) { + assert_eq!(before.pixel(x as u32, y as u32), [0, 0, 0, 255], "closed={closed}: original fill at ({x}, {y})"); + } + + // The explicit command fixes the tip at 10 pt; its round ends are outside the rectangle. + erase(&mut s, json!({"points": [[50, 150], [250, 150]], "size": 10}), varied); + let remaining: Vec = paths(&s); + let filled = + |x, y| remaining.iter().any(|path| vectorcraft_geom::hit::fill_contains(&path.to_bezpath(), FillRule::NonZero, Point::new(x, y))); + let after = render(&s); + for (x, y) in samples { + assert!(filled(x, y), "closed={closed}: retained fill missing at ({x}, {y})"); + assert_eq!(after.pixel(x as u32, y as u32), [0, 0, 0, 255], "closed={closed}: retained pixel at ({x}, {y})"); + } + assert!(!filled(150.0, 150.0), "closed={closed}: eraser band still filled"); + assert_eq!(after.pixel(150, 150)[3], 0, "closed={closed}: erased pixel"); + let area: f64 = remaining.iter().map(|path| vectorcraft_pathops::area(path, FillRule::NonZero)).sum(); + assert!((area - 9000.0).abs() < 1.0, "closed={closed}: retained area {area}"); + } +} + +#[test] +fn eraser_preserves_the_fill_of_an_open_rectangle() { + eraser_preserves_the_fill_of_an_open_rectangle_case(false); +} + +#[test] +fn eraser_preserves_the_fill_of_an_open_rectangle_varied_tip() { + eraser_preserves_the_fill_of_an_open_rectangle_case(true); +} + +fn eraser_keeps_open_compound_holes_with_both_fill_rules_case(varied: bool) { + for rule in ["nonZero", "evenOdd"] { + let mut s = session(); + let outer = NodeId( + s.execute( + "path.create", + &json!({"anchors": [ + {"x": 100, "y": 100}, {"x": 300, "y": 100}, {"x": 300, "y": 300}, {"x": 100, "y": 300} + ]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + let inner = NodeId( + s.execute( + "path.create", + &json!({"anchors": [ + {"x": 150, "y": 150}, {"x": 150, "y": 250}, {"x": 250, "y": 250}, {"x": 250, "y": 150} + ]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + for id in [outer, inner] { + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap(); + } + s.execute("select.set", &json!({"ids": [outer.0, inner.0]})).unwrap(); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("path.setFillRule", &json!({"rule": rule})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let members = match &s.doc().unwrap().doc.node(compound).unwrap().kind { + NodeKind::Compound { children, .. } => children, + other => panic!("expected compound path, got {other:?}"), + }; + assert!(members.iter().all(|member| !member.path_data().unwrap().is_closed()), "{rule}: both source contours remain open"); + let before = + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()); + assert!(before.pixel(120, 140)[3] > 240, "{rule}: ring fills before Eraser"); + assert_eq!(before.pixel(200, 200)[3], 0, "{rule}: the compound hole is empty before Eraser"); + let before_miss = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let miss_history = s.doc().unwrap().history.undo.len(); + let miss = erase(&mut s, json!({"points": [[200, 200]], "size": 10}), varied); + assert_eq!(miss["ids"], json!([]), "{rule}: a stroke wholly inside the hole misses"); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before_miss); + assert_eq!(s.doc().unwrap().history.undo.len(), miss_history, "{rule}: the hole miss adds no history"); + + erase(&mut s, json!({"points": [[80, 120], [320, 120]], "size": 10}), varied); + let after = + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()); + assert_eq!(after.pixel(120, 120)[3], 0, "{rule}: swept band is empty"); + assert!(after.pixel(120, 140)[3] > 240, "{rule}: retained ring is filled"); + assert_eq!(after.pixel(200, 200)[3], 0, "{rule}: compound hole remains empty"); + } +} + +#[test] +fn eraser_keeps_open_compound_holes_with_both_fill_rules() { + eraser_keeps_open_compound_holes_with_both_fill_rules_case(false); +} + +#[test] +fn eraser_keeps_open_compound_holes_with_both_fill_rules_varied_tip() { + eraser_keeps_open_compound_holes_with_both_fill_rules_case(true); +} + +fn eraser_removes_only_the_swept_strip_from_a_zero_signed_area_open_bowtie_case(varied: bool) { + let mut s = session(); + let id = NodeId( + s.execute( + "path.create", + &json!({"anchors": [ + {"x": 100, "y": 100}, {"x": 200, "y": 200}, {"x": 100, "y": 200}, {"x": 200, "y": 100} + ]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert!(!path(&s, id).is_closed(), "the bowtie is open"); + assert!(path(&s, id).subpaths.first().unwrap().signed_area().abs() < 1e-9, "the bowtie has zero signed area"); + let render = |s: &Session| { + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()) + }; + let before = render(&s); + let before_area: f64 = before.pixels.as_chunks::<4>().0.iter().map(|rgba| f64::from(rgba[3]) / 255.0).sum(); + assert!((before_area - 5000.0).abs() < 2.0, "the open bowtie fills both lobes: {before_area}"); + for y in [110, 140, 175] { + assert!(before.pixel(150, y)[3] > 240, "original lobe pixel y={y}"); + } + + erase(&mut s, json!({"points": [[50, 125], [250, 125]], "size": 10}), varied); + let after = render(&s); + let after_area: f64 = after.pixels.as_chunks::<4>().0.iter().map(|rgba| f64::from(rgba[3]) / 255.0).sum(); + assert!((after_area - 4500.0).abs() < 2.0, "only the 500 px² sweep strip is removed: {after_area}"); + assert!(after.pixel(150, 110)[3] > 240); + assert!(after.pixel(150, 140)[3] > 240); + assert!(after.pixel(150, 175)[3] > 240); + assert_eq!(after.pixel(150, 125)[3], 0, "the swept strip is empty"); + let area: f64 = paths(&s).iter().map(|path| vectorcraft_pathops::area(path, FillRule::NonZero)).sum(); + assert!((area - 4500.0).abs() < 1.0, "retained bowtie area {area}"); +} + +#[test] +fn eraser_removes_only_the_swept_strip_from_a_zero_signed_area_open_bowtie() { + eraser_removes_only_the_swept_strip_from_a_zero_signed_area_open_bowtie_case(false); +} + +#[test] +fn eraser_removes_only_the_swept_strip_from_a_zero_signed_area_open_bowtie_varied_tip() { + eraser_removes_only_the_swept_strip_from_a_zero_signed_area_open_bowtie_case(true); +} + +#[test] +fn eraser_keeps_painted_stroke_open_paths_on_the_outline_route() { + for varied in [false, true] { + let mut s = session(); + let id = NodeId( + s.execute( + "path.create", + &json!({"anchors": [ + {"x": 100, "y": 100}, {"x": 200, "y": 100}, + {"x": 200, "y": 200}, {"x": 100, "y": 200} + ]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [id.0], "weight": 4})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert!(!path(&s, id).is_closed()); + let appearance = &s.doc().unwrap().doc.node(id).unwrap().appearance; + assert_eq!(appearance.stroke_width(), 4.0); + assert!(!appearance.stroke_paint().is_none()); + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let history = s.doc().unwrap().history.undo.len(); + let selection = s.doc().unwrap().selection.clone(); + let before_image = + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()); + assert_eq!(before_image.pixel(150, 150), [0, 0, 0, 255], "the interior really has visible fill"); + assert!(before_image.pixel(150, 100)[3] > 240, "the open path has painted visible stroke"); + // This sweep lies inside the fill, at least 30 pt from any painted outline. + // Fill-only scope must not extend to this painted-stroke path or wrap it. + let miss = erase(&mut s, json!({"points": [[130, 150], [170, 150]], "size": 10}), varied); + assert_eq!(miss["ids"], json!([]), "varied={varied}: the existing outline route misses"); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before, "varied={varied}: no replacement or wrapper"); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + assert_eq!(s.doc().unwrap().selection, selection); + let after_image = + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()); + assert_eq!(after_image.pixels, before_image.pixels); + } +} + +// The Alt-drag marquee dispatches the same public Eraser command with `rect` instead of `points`. +fn marquee_rectangle(s: &mut Session, closed: bool, stroked: bool) -> NodeId { + let id = NodeId( + s.execute( + "path.create", + &json!({"closed": closed, "anchors": [ + {"x": 100, "y": 100}, {"x": 200, "y": 100}, + {"x": 200, "y": 200}, {"x": 100, "y": 200} + ]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#000000"})).unwrap(); + if stroked { + s.execute("paint.setStroke", &json!({"ids": [id.0], "color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [id.0], "weight": 4})).unwrap(); + } else { + s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap(); + } + id +} + +#[test] +fn eraser_marquee_preserves_open_fill_like_closed_and_undo() { + for closed in [true, false] { + let mut s = session(); + let id = marquee_rectangle(&mut s, closed, false); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + assert_eq!(path(&s, id).is_closed(), closed); + let render = |s: &Session| { + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()) + }; + let before_image = render(&s); + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + let retained = [(110, 125), (190, 125), (110, 175), (190, 175)]; + for (x, y) in retained.into_iter().chain([(150, 150)]) { + assert_eq!(before_image.pixel(x, y), [0, 0, 0, 255], "closed={closed}: original fill at ({x}, {y})"); + } + s.execute("path.eraseRegion", &json!({"rect": [50, 145, 200, 10]})).unwrap(); + let after_image = render(&s); + for (x, y) in retained { + assert_eq!(after_image.pixel(x, y), [0, 0, 0, 255], "closed={closed}: marquee lost retained fill at ({x}, {y})"); + } + assert_eq!(after_image.pixel(150, 150)[3], 0, "closed={closed}: marquee band is empty"); + let remaining = paths(&s); + let area: f64 = remaining.iter().map(|p| vectorcraft_pathops::area(p, FillRule::NonZero)).sum(); + assert!((area - 9000.0).abs() < 1.0, "closed={closed}: marquee retained area {area}"); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1, "one marquee is one edit"); + let after = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let after_selection = s.doc().unwrap().selection.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before, "closed={closed}: Undo restores the original document"); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), after); + assert_eq!(s.doc().unwrap().selection, after_selection); + } +} + +#[test] +fn eraser_marquee_keeps_compound_holes_and_outline_controls() { + for rule in ["nonZero", "evenOdd"] { + let mut s = session(); + let mut ids = vec![]; + for anchors in [ + json!([{"x": 100, "y": 100}, {"x": 300, "y": 100}, {"x": 300, "y": 300}, {"x": 100, "y": 300}]), + json!([{"x": 150, "y": 150}, {"x": 150, "y": 250}, {"x": 250, "y": 250}, {"x": 250, "y": 150}]), + ] { + let id = s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"ids": [id], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id], "none": true})).unwrap(); + ids.push(id); + } + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("path.setFillRule", &json!({"rule": rule})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let members = match &s.doc().unwrap().doc.node(compound).unwrap().kind { + NodeKind::Compound { children, .. } => children, + other => panic!("expected compound, got {other:?}"), + }; + assert!(members.iter().all(|n| !n.path_data().unwrap().is_closed())); + let render = |s: &Session| { + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()) + }; + let before_image = render(&s); + assert!(before_image.pixel(120, 120)[3] > 240, "{rule}: original ring is filled"); + assert_eq!(before_image.pixel(200, 200)[3], 0, "{rule}: original hole is empty"); + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + let miss = s.execute("path.eraseRegion", &json!({"rect": [180, 180, 40, 40]})).unwrap(); + assert_eq!(miss["ids"], json!([]), "{rule}: a marquee wholly inside the hole misses"); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + let result = s.execute("path.eraseRegion", &json!({"rect": [80, 115, 240, 10]})).unwrap(); + assert!(!result["ids"].as_array().unwrap().is_empty()); + for id in result["ids"].as_array().unwrap() { + assert!( + matches!(s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().kind, NodeKind::Compound { .. }), + "{rule}: no wrapper replaces the compound pieces" + ); + } + let after_image = render(&s); + assert_eq!(after_image.pixel(120, 120)[3], 0, "{rule}: marquee band is empty"); + assert!(after_image.pixel(120, 140)[3] > 240, "{rule}: ring outside the marquee remains filled"); + assert_eq!(after_image.pixel(200, 200)[3], 0, "{rule}: compound hole stays empty"); + let area: f64 = after_image.pixels.as_chunks::<4>().0.iter().map(|rgba| f64::from(rgba[3]) / 255.0).sum(); + assert!((area - 28000.0).abs() < 2.0, "{rule}: marquee removes only its 2000 px² strip: {area}"); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().selection, selection); + } + + // Filled AND painted-stroke open art keeps the existing outline route, so an interior + // marquee that touches none of its three painted edges is a genuine no-op. + let mut s = session(); + let id = marquee_rectangle(&mut s, false, true); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + let miss = s.execute("path.eraseRegion", &json!({"rect": [130, 145, 40, 10]})).unwrap(); + assert_eq!(miss["ids"], json!([])); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + + // Knife's target collection must not inherit the Eraser-only open-fill area extension. + let mut s = session(); + let id = marquee_rectangle(&mut s, false, false); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + let miss = s.execute("path.knife", &json!({"points": [[50, 150], [250, 150]]})).unwrap(); + assert_eq!(miss["ids"], json!([])); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); +} + +// A mask is a role of one first child, not a collection of ordinary sibling pieces. +struct ClipMaskFixture { + group: NodeId, + mask: NodeId, + art: NodeId, + compound: bool, + rule: FillRule, + appearance: Value, + art_json: Value, +} + +fn blue_clip_art(s: &mut Session) -> NodeId { + let art = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 300, "height": 300})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [art.0], "color": "#0000ff"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [art.0], "none": true})).unwrap(); + art +} + +fn painted_clip(s: &mut Session, art: NodeId, mask: NodeId, compound: bool) -> ClipMaskFixture { + s.execute("select.set", &json!({"ids": [art.0, mask.0]})).unwrap(); + let group = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + assert!(s.doc().unwrap().doc.node(mask).unwrap().appearance.fill_paint().is_none(), "Make clears the clipping path's paint"); + // The reported area route requires visible fill on the mask AFTER Make, which clears it. + s.execute("paint.setFill", &json!({"ids": [mask.0], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [mask.0], "none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [mask.0]})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, vec![mask], "only the mask is an Eraser target"); + let node = s.doc().unwrap().doc.node(mask).unwrap(); + assert!(!node.appearance.fill_paint().is_none(), "the restored visible fill admits the area route"); + assert!(node.appearance.stroke_paint().is_none(), "no painted stroke admits an outline fallback"); + let rule = match &node.kind { + NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. } => *rule, + other => panic!("expected a path or compound mask, got {other:?}"), + }; + let fixture = ClipMaskFixture { + group, + mask, + art, + compound, + rule, + appearance: serde_json::to_value(&node.appearance).unwrap(), + art_json: serde_json::to_value(s.doc().unwrap().doc.node(art).unwrap()).unwrap(), + }; + assert_clip_identity(s, &fixture); + fixture +} + +fn assert_clip_identity(s: &Session, c: &ClipMaskFixture) { + let d = &s.doc().unwrap().doc; + let children = match &d.node(c.group).unwrap().kind { + NodeKind::Group { children, clip: true } => children, + other => panic!("expected the original clip group, got {other:?}"), + }; + assert_eq!(children.iter().map(|n| n.id).collect::>(), [c.mask, c.art], "the one mask stays first; no painted siblings or promoted art"); + let mask = d.node(c.mask).unwrap(); + let rule = match (&mask.kind, c.compound) { + (NodeKind::Path { rule, clipping: true, .. }, false) | (NodeKind::Compound { rule, .. }, true) => *rule, + (other, _) => panic!("the original mask kind/role changed: {other:?}"), + }; + assert_eq!(rule, c.rule); + assert_eq!(serde_json::to_value(&mask.appearance).unwrap(), c.appearance); + assert_eq!(serde_json::to_value(d.node(c.art).unwrap()).unwrap(), c.art_json, "the clipped art itself is untouched"); +} + +fn assert_clip_pixels(s: &Session, blue: &[(u32, u32)], clear: &[(u32, u32)]) { + let image = vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()); + for &(x, y) in blue { + assert_eq!(image.pixel(x, y), [0, 0, 255, 255], "clipped blue art at ({x}, {y}), not a painted mask sibling"); + } + for &(x, y) in clear { + assert_eq!(image.pixel(x, y)[3], 0, "transparent clip region at ({x}, {y})"); + } +} + +fn clip_eraser(s: &mut Session, mode: &str, full: bool) -> Value { + if mode == "rect" { + let rect = if full { json!([50, 50, 300, 300]) } else { json!([50, 145, 200, 10]) }; + s.execute("path.eraseRegion", &json!({"rect": rect})).unwrap() + } else { + assert!(matches!(mode, "fixed" | "varied")); + let params = if full { json!({"points": [[150, 150]], "size": 300}) } else { json!({"points": [[50, 150], [250, 150]], "size": 10}) }; + erase(s, params, mode == "varied") + } +} + +fn fully_erase_clip_and_restore(s: &mut Session, c: &ClipMaskFixture, mode: &str) { + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + clip_eraser(s, mode, true); + let image = vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()); + assert!(image.pixels.as_chunks::<4>().0.iter().all(|pixel| pixel[3] == 0), "empty geometry must hide all clipped art, not promote it"); + assert_clip_identity(s, c); + match &s.doc().unwrap().doc.node(c.mask).unwrap().kind { + NodeKind::Path { path, .. } => assert!(path.is_empty()), + NodeKind::Compound { children, .. } => assert!(children.is_empty()), + other => panic!("empty mask retains its kind: {other:?}"), + } + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + let empty = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let empty_selection = s.doc().unwrap().selection.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), empty); + assert_eq!(s.doc().unwrap().selection, empty_selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + assert_clip_identity(s, c); +} + +#[test] +fn eraser_clipping_split_and_empty_masks_keep_their_single_role() { + for closed in [false, true] { + for mode in ["fixed", "varied", "rect"] { + let mut s = session(); + let art = blue_clip_art(&mut s); + let mask = marquee_rectangle(&mut s, closed, false); + let c = painted_clip(&mut s, art, mask, false); + assert_eq!(path(&s, mask).is_closed(), closed, "the original mask's open/closed state is real"); + assert_clip_pixels(&s, &[(110, 125), (190, 125), (110, 175), (190, 175), (150, 150)], &[(90, 150)]); + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + clip_eraser(&mut s, mode, false); + assert_clip_pixels(&s, &[(110, 125), (190, 125), (110, 175), (190, 175)], &[(150, 150), (90, 150)]); + assert_clip_identity(&s, &c); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1, "closed={closed}, mode={mode}: one erase edit"); + let split = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let split_selection = s.doc().unwrap().selection.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), split); + assert_eq!(s.doc().unwrap().selection, split_selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + fully_erase_clip_and_restore(&mut s, &c, mode); + } + } +} + +#[test] +fn eraser_clipping_compound_holes_and_empty_masks_keep_their_rule() { + for rule in ["nonZero", "evenOdd"] { + let mut s = session(); + let art = blue_clip_art(&mut s); + let mut ids = vec![]; + for anchors in [ + json!([{"x": 100, "y": 100}, {"x": 300, "y": 100}, {"x": 300, "y": 300}, {"x": 100, "y": 300}]), + json!([{"x": 150, "y": 150}, {"x": 150, "y": 250}, {"x": 250, "y": 250}, {"x": 250, "y": 150}]), + ] { + let id = s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"ids": [id], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id], "none": true})).unwrap(); + ids.push(id); + } + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let mask = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("path.setFillRule", &json!({"rule": rule})).unwrap(); + let c = painted_clip(&mut s, art, mask, true); + assert_eq!(c.rule, if rule == "evenOdd" { FillRule::EvenOdd } else { FillRule::NonZero }); + let members = match &s.doc().unwrap().doc.node(mask).unwrap().kind { + NodeKind::Compound { children, .. } => children, + other => panic!("expected compound, got {other:?}"), + }; + assert!(members.iter().all(|member| !member.path_data().unwrap().is_closed()), "the source contours are open"); + assert_clip_pixels(&s, &[(120, 110), (120, 120), (120, 140)], &[(200, 200), (90, 110)]); + // First witness the independent zero-mask promotion defect in actual pixels. + let original = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let original_selection = s.doc().unwrap().selection.clone(); + let original_history = s.doc().unwrap().history.undo.len(); + fully_erase_clip_and_restore(&mut s, &c, "rect"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), original); + assert_eq!(s.doc().unwrap().selection, original_selection); + assert_eq!(s.doc().unwrap().history.undo.len(), original_history); + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + s.execute("path.eraseRegion", &json!({"rect": [80, 115, 240, 10]})).unwrap(); + assert_clip_identity(&s, &c); + assert_clip_pixels(&s, &[(120, 110), (120, 140)], &[(120, 120), (200, 200), (90, 110)]); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + let split = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let split_selection = s.doc().unwrap().selection.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), split); + assert_eq!(s.doc().unwrap().selection, split_selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + // Member IDs may be rebuilt by set_geometry; only the compound mask's own role is stable. + } +} + +#[test] +fn eraser_clipping_path_eraser_keeps_mask_but_removes_ordinary_art() { + let mut s = session(); + let art = blue_clip_art(&mut s); + let mask = marquee_rectangle(&mut s, false, false); + let c = painted_clip(&mut s, art, mask, false); + assert!(!path(&s, mask).is_closed()); + assert_clip_pixels(&s, &[(190, 110), (190, 150), (190, 190)], &[(90, 150)]); + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + s.execute("path.eraseSegments", &json!({"points": [[50, 150], [250, 150]], "width": 10})).unwrap(); + // The two open outline pieces close as triangles for clipping, not as an area subtraction. + assert_clip_pixels(&s, &[(190, 110), (190, 190)], &[(190, 150), (90, 150)]); + assert_clip_identity(&s, &c); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + let split = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let split_selection = s.doc().unwrap().selection.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), split); + assert_eq!(s.doc().unwrap().selection, split_selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + + // The same shared apply_plan must still REMOVE wholly erased ordinary art. + let mut s = session(); + let ordinary = marquee_rectangle(&mut s, false, false); + s.execute("select.set", &json!({"ids": [ordinary.0]})).unwrap(); + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + s.execute("path.eraseSegments", &json!({"points": [[50, 150], [250, 150]], "width": 300})).unwrap(); + assert!(s.doc().unwrap().doc.node(ordinary).is_none(), "ordinary art does not retain an empty mask node"); + assert!(s.doc().unwrap().selection.is_empty()); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(ordinary).is_none()); + assert!(s.doc().unwrap().selection.is_empty()); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); +} + +// Bounds-fitted fill gradients are page-space paints, not Along-stroke gradients. +fn eraser_gradient_fill(s: &mut Session, id: NodeId, placed: bool) -> Value { + let mut gradient = json!({"kind": "linear", "angle": 90, "dither": false, "stops": [ + {"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"} + ]}); + if placed { + gradient["start"] = json!([150, 200]); + gradient["end"] = json!([150, 100]); + } + s.execute("paint.setFill", &json!({"ids": [id.0], "gradient": gradient})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let vectorcraft_doc::color::Paint::Gradient(g) = s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint() else { + panic!("the public paint command must install a gradient fill"); + }; + assert_eq!(g.geom.is_some(), placed, "the fixture distinguishes fitted and explicitly placed gradients"); + assert!(!g.gradient.dither, "exact retained-pixel comparisons do not use noise"); + serde_json::to_value(g.geom).unwrap() +} + +fn eraser_gradient_image(s: &Session) -> vectorcraft_render::Rendered { + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()) +} + +fn eraser_gradient_region(s: &mut Session, mode: &str, trim: bool, miss: bool) -> Value { + if mode == "rect" { + let rect = if miss { + json!([10, 10, 10, 10]) + } else if trim { + json!([50, 90, 200, 20]) + } else { + json!([50, 145, 200, 10]) + }; + s.execute("path.eraseRegion", &json!({"rect": rect})).unwrap() + } else { + assert!(matches!(mode, "fixed" | "varied")); + let params = if miss { + json!({"points": [[20, 20]], "size": 10}) + } else if trim { + json!({"points": [[50, 100], [250, 100]], "size": 20}) + } else { + json!({"points": [[50, 150], [250, 150]], "size": 10}) + }; + erase(s, params, mode == "varied") + } +} + +fn eraser_gradient_rectangle_case(closed: bool, mode: &str, trim: bool, placed: bool) { + let mut s = session(); + let id = marquee_rectangle(&mut s, closed, false); + let placed_geom = eraser_gradient_fill(&mut s, id, placed); + assert_eq!(path(&s, id).is_closed(), closed); + let before_image = eraser_gradient_image(&s); + let before = s.doc().unwrap().doc.clone(); + let before_json = serde_json::to_value(&before).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + for y in [125, 175] { + assert_eq!(before_image.pixel(150, y)[3], 255, "the retained sample is inside the original fill"); + } + assert_ne!(before_image.pixel(150, 125), before_image.pixel(150, 175), "the original ramp varies vertically"); + let erased_y = if trim { 105 } else { 150 }; + assert_eq!(before_image.pixel(150, erased_y)[3], 255); + + let miss = eraser_gradient_region(&mut s, mode, trim, true); + assert_eq!(miss["ids"], json!([])); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &before), "a miss must not pin or replace the document"); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before_json); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + + let result = eraser_gradient_region(&mut s, mode, trim, false); + let ids = result["ids"].as_array().unwrap(); + assert_eq!(ids.len(), if trim { 1 } else { 2 }, "closed={closed}, mode={mode}, trim={trim}: actual piece count"); + let after_image = eraser_gradient_image(&s); + assert_eq!(after_image.pixel(150, erased_y)[3], 0, "the erase operation really removes the intended band"); + for y in [125, 175] { + assert_eq!( + after_image.pixel(150, y), + before_image.pixel(150, y), + "closed={closed}, mode={mode}, trim={trim}, placed={placed}: retained gradient color at (150, {y})" + ); + } + if placed { + for id in ids { + let node = s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap(); + let vectorcraft_doc::color::Paint::Gradient(g) = node.appearance.fill_paint() else { panic!("the placed fill remains a gradient") }; + assert_eq!(serde_json::to_value(g.geom).unwrap(), placed_geom, "an explicit vector is not refitted"); + } + } + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1, "one erase is one edit"); + let after = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let after_selection = s.doc().unwrap().selection.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before_json); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), after); + assert_eq!(s.doc().unwrap().selection, after_selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + assert_eq!(eraser_gradient_image(&s).pixels, after_image.pixels, "Redo restores the exact rendered result"); +} + +#[test] +fn eraser_gradient_retains_page_colors_for_split_trim_and_placed_fill() { + // A legal already-placed vector is the positive control for the shared pinning seam. + eraser_gradient_rectangle_case(false, "fixed", false, true); + for closed in [false, true] { + for mode in ["fixed", "varied", "rect"] { + for trim in [false, true] { + eraser_gradient_rectangle_case(closed, mode, trim, false); + } + } + } +} + +fn eraser_gradient_compound_fixture(s: &mut Session, rule: &str) -> (NodeId, NodeId, NodeId) { + let mut ids = vec![]; + for anchors in [ + json!([{"x": 100, "y": 100}, {"x": 200, "y": 100}, {"x": 200, "y": 200}, {"x": 100, "y": 200}]), + json!([{"x": 140, "y": 140}, {"x": 140, "y": 160}, {"x": 160, "y": 160}, {"x": 160, "y": 140}]), + ] { + let id = s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"ids": [id], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id], "none": true})).unwrap(); + ids.push(id); + } + let outer = NodeId(*ids.first().unwrap()); + let inner = NodeId(*ids.get(1).unwrap()); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("path.setFillRule", &json!({"rule": rule})).unwrap(); + eraser_gradient_fill(s, compound, false); + let owner = s.doc().unwrap().doc.node(compound).unwrap(); + let members = match &owner.kind { + NodeKind::Compound { children, .. } => children, + other => panic!("expected a compound, got {other:?}"), + }; + assert_eq!(members.len(), 2); + for member in members { + assert!(!member.path_data().unwrap().is_closed(), "the compound's source contours are genuinely open"); + assert!(member.appearance.fill_paint().is_none() && member.appearance.stroke_paint().is_none(), "the parent alone owns the paint"); + } + let bounds = owner.geometric_bounds().unwrap(); + assert_eq!(bounds, vectorcraft_geom::Rect::new(100.0, 100.0, 200.0, 200.0)); + (outer, inner, compound) +} + +fn eraser_gradient_compound_case(outline: bool, rule: &str) { + let mut s = session(); + let (outer, inner, compound) = eraser_gradient_compound_fixture(&mut s, rule); + let before_image = eraser_gradient_image(&s); + let retained = if outline { vec![(190, 175)] } else { vec![(150, 125), (150, 175)] }; + for &(x, y) in &retained { + assert_eq!(before_image.pixel(x, y)[3], 255, "{rule}: retained source interior"); + } + assert_ne!(before_image.pixel(190, 125), before_image.pixel(190, 175), "the parent paint is a nonconstant vertical ramp"); + assert_eq!(before_image.pixel(155, 155)[3], 0, "the source hole is empty"); + let before = s.doc().unwrap().doc.clone(); + let before_json = serde_json::to_value(&before).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + let inner_before = serde_json::to_value(s.doc().unwrap().doc.node(inner).unwrap()).unwrap(); + let miss = if outline { + s.execute("path.eraseSegments", &json!({"points": [[20, 20]], "width": 20})).unwrap() + } else { + s.execute("path.eraseRegion", &json!({"rect": [145, 145, 10, 10]})).unwrap() + }; + assert_eq!(miss["ids"], json!([])); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &before), "{rule}: no-op must not pin the owner"); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + assert_eq!(s.doc().unwrap().selection, selection); + + if outline { + // Path Eraser plans the outer leaf, but its Compound parent supplies the gradient. + s.execute("path.eraseSegments", &json!({"points": [[50, 100], [250, 100]], "width": 20})).unwrap(); + let after_bounds = s.doc().unwrap().doc.node(compound).unwrap().geometric_bounds().unwrap(); + assert!((after_bounds.y0 - 110.0).abs() < 1e-5, "the edited extremal outline shrinks the parent fit: {after_bounds:?}"); + assert_eq!(serde_json::to_value(s.doc().unwrap().doc.node(inner).unwrap()).unwrap(), inner_before, "the inner member itself was not edited"); + let hole = Point::new(155.0, 155.0); + assert!( + vectorcraft_geom::hit::fill_contains(&path(&s, outer).to_bezpath(), FillRule::NonZero, hole), + "the sample remains inside the outer fill" + ); + assert!( + vectorcraft_geom::hit::fill_contains(&path(&s, inner).to_bezpath(), FillRule::NonZero, hole), + "the unchanged inner contour still makes a hole there" + ); + } else { + s.execute("path.eraseRegion", &json!({"rect": [50, 145, 200, 10]})).unwrap(); + } + let after_image = eraser_gradient_image(&s); + assert_eq!(after_image.pixel(155, 155)[3], 0, "{rule}: the un-erased part of the hole stays empty"); + if !outline { + assert_eq!(after_image.pixel(190, 150)[3], 0, "the marquee actually removes filled art across the ring"); + assert_eq!(after_image.pixel(150, 142)[3], 0, "the hole above the erased band remains empty"); + } + for &(x, y) in &retained { + assert_eq!( + after_image.pixel(x, y), + before_image.pixel(x, y), + "{rule}, outline={outline}: parent-owned gradient must keep its original color at ({x}, {y})" + ); + } + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + let after = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let after_selection = s.doc().unwrap().selection.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before_json); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), after); + assert_eq!(s.doc().unwrap().selection, after_selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + assert_eq!(eraser_gradient_image(&s).pixels, after_image.pixels); +} + +#[test] +fn eraser_gradient_compound_owner_keeps_page_colors_and_holes() { + for outline in [true, false] { + for rule in ["nonZero", "evenOdd"] { + eraser_gradient_compound_case(outline, rule); + } + } +} + +fn eraser_container_gradient_fixture(s: &mut Session, placed: bool, nested: bool) -> (NodeId, NodeId, NodeId, Value) { + let mut ids = vec![]; + for anchors in [ + json!([{"x": 100, "y": 100}, {"x": 150, "y": 100}, {"x": 150, "y": 140}, {"x": 100, "y": 140}]), + json!([{"x": 170, "y": 160}, {"x": 220, "y": 160}, {"x": 220, "y": 200}, {"x": 170, "y": 200}]), + ] { + let id = s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"ids": [id], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id], "none": true})).unwrap(); + ids.push(id); + } + let edited = NodeId(ids[0]); + let sibling = NodeId(ids[1]); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let inner = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let owner = if nested { NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()) } else { inner }; + s.execute("appearance.addFill", &json!({"ids": [owner.0], "target": "object"})).unwrap(); + let mut gradient = json!({"kind": "linear", "angle": 90, "dither": false, "stops": [ + {"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"} + ]}); + if placed { + gradient["start"] = json!([160, 200]); + gradient["end"] = json!([160, 100]); + } + s.execute("appearance.setItem", &json!({"ids": [owner.0], "target": "object", "index": 0, "gradient": gradient})).unwrap(); + let d = &s.doc().unwrap().doc; + let n = d.node(owner).unwrap(); + assert!(matches!(n.kind, NodeKind::Group { clip: false, .. })); + assert_eq!(n.appearance.items.len(), 1, "the Group owns one fill row"); + assert_eq!(n.appearance.contents_at(), 0, "the own fill paints above the children's black fills"); + let vectorcraft_doc::color::Paint::Gradient(g) = n.appearance.fill_paint() else { panic!("the Group itself owns the gradient") }; + assert_eq!(g.geom.is_some(), placed); + assert!(!g.gradient.dither); + let geom = serde_json::to_value(g.geom).unwrap(); + assert_eq!(n.geometric_bounds().unwrap(), vectorcraft_geom::Rect::new(100.0, 100.0, 220.0, 200.0)); + for id in [edited, sibling] { + assert!(!d.node(id).unwrap().appearance.has_unplaced_gradient(), "the gradient is not on a leaf"); + } + assert_eq!(d.parent_of(edited), Some(inner)); + if nested { + assert_eq!(d.parent_of(inner), Some(owner)); + assert!(d.node(inner).unwrap().appearance.items.is_empty(), "the intervening Group has no own paint"); + } + s.execute("select.set", &json!({"ids": [edited.0]})).unwrap(); + (edited, sibling, owner, geom) +} + +fn eraser_container_gradient_restore(s: &mut Session, before: &Value, selection: &vectorcraft_doc::Selection, history: usize) { + let after = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let after_selection = s.doc().unwrap().selection.clone(); + let after_pixels = eraser_gradient_image(s).pixels; + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1, "one erase remains one edit"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), *before); + assert_eq!(&s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), after); + assert_eq!(s.doc().unwrap().selection, after_selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + assert_eq!(eraser_gradient_image(s).pixels, after_pixels); +} + +fn eraser_container_gradient_case(placed: bool, nested: bool) { + let mut s = session(); + let (edited, sibling, owner, geom) = eraser_container_gradient_fixture(&mut s, placed, nested); + let before_image = eraser_gradient_image(&s); + assert_eq!(before_image.pixel(125, 105)[3], 255, "the extremal child really paints the erase region"); + assert_eq!(before_image.pixel(190, 175)[3], 255); + assert_ne!(before_image.pixel(190, 175), before_image.pixel(190, 185), "the owner's paint varies on the untouched sibling"); + assert_ne!(before_image.pixel(190, 175), [0, 0, 0, 255], "the Group's top paint actually covers the black child"); + let before = s.doc().unwrap().doc.clone(); + let before_json = serde_json::to_value(&before).unwrap(); + let sibling_before = serde_json::to_value(before.node(sibling).unwrap()).unwrap(); + let ancestry = before.ancestry(edited).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + let miss = eraser_gradient_region(&mut s, "rect", true, true); + assert_eq!(miss["ids"], json!([])); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &before), "a miss must not replace any ancestor"); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before_json); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + let result = eraser_gradient_region(&mut s, "rect", true, false); + assert_eq!(result["ids"].as_array().unwrap().len(), 1, "trim keeps one piece, not a split"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.ancestry(edited).unwrap(), ancestry, "the child and every original container retain their roles"); + assert_eq!(serde_json::to_value(d.node(sibling).unwrap()).unwrap(), sibling_before, "the sibling itself was not edited"); + let n = d.node(owner).unwrap(); + assert!(matches!(n.kind, NodeKind::Group { clip: false, .. })); + assert!((n.geometric_bounds().unwrap().y0 - 110.0).abs() < 1e-5, "the owner's original minimum y really shrinks"); + let after_image = eraser_gradient_image(&s); + assert_eq!(after_image.pixel(125, 105)[3], 0, "the intended band is erased through the Group's paint"); + assert_eq!( + after_image.pixel(190, 175), + before_image.pixel(190, 175), + "placed={placed}, nested={nested}: erasing one child must not recolor its untouched sibling" + ); + if placed { + let vectorcraft_doc::color::Paint::Gradient(g) = n.appearance.fill_paint() else { panic!("the own fill stays a gradient") }; + assert_eq!(serde_json::to_value(g.geom).unwrap(), geom, "an explicitly placed owner is not refitted"); + } + eraser_container_gradient_restore(&mut s, &before_json, &selection, history); +} + +#[test] +fn eraser_container_gradient_keeps_untouched_sibling_colors() { + // Positive control runs before the unchanged-product fitted-paint failure. + eraser_container_gradient_case(true, false); + eraser_container_gradient_case(false, false); + eraser_container_gradient_case(false, true); +} + +fn eraser_container_effect_gradient_case(group: bool, placed: bool) { + let mut s = session(); + let (edited, owner, geom) = if group { + let (edited, _, owner, geom) = eraser_container_gradient_fixture(&mut s, placed, false); + (edited, owner, geom) + } else { + let id = marquee_rectangle(&mut s, true, false); + let geom = eraser_gradient_fill(&mut s, id, placed); + (id, id, geom) + }; + s.execute( + "effect.apply", + &json!({ + "ids": [owner.0], "target": "object", "item": null, + "effect": "path.offsetPath", "params": {"offset": 10, "joins": "round"} + }), + ) + .unwrap(); + let d = &s.doc().unwrap().doc; + let n = d.node(owner).unwrap(); + assert_eq!(n.appearance.effects.len(), 1); + let effect = &n.appearance.effects[0]; + assert_eq!(effect.id, "path.offsetPath"); + assert!(effect.visible); + assert_eq!(effect.params["offset"].as_f64(), Some(10.0)); + assert_eq!(effect.params["joins"], json!("round")); + let effect_before = serde_json::to_value(&n.appearance.effects).unwrap(); + let vectorcraft_doc::color::Paint::Gradient(g) = n.appearance.fill_paint() else { panic!("the effect owner really owns the gradient") }; + assert_eq!(g.geom.is_some(), placed); + assert!(!g.gradient.dither); + assert_eq!(g.gradient.stops.len(), 2); + assert_ne!(g.gradient.stops[0].color, g.gradient.stops[1].color, "the own paint is a real nonconstant ramp before rendering"); + let original_bounds = n.geometric_bounds().unwrap(); + assert_eq!((original_bounds.y0, original_bounds.y1), (100.0, 200.0)); + let before_image = eraser_gradient_image(&s); + assert_eq!(before_image.pixel(125, 105)[3], 255); + assert_eq!(before_image.pixel(190, 175)[3], 255); + assert_eq!(before_image.pixel(190, 185)[3], 255); + assert_ne!(before_image.pixel(190, 175), before_image.pixel(190, 185), "the rendered own gradient is nonconstant"); + assert_eq!(before_image.pixel(190, 205)[3], 255, "the live positive offset paints beyond the source's y=200 bounds"); + let before = s.doc().unwrap().doc.clone(); + let before_json = serde_json::to_value(&before).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + let ancestry = before.ancestry(edited).unwrap(); + let miss = s.execute("path.eraseRegion", &json!({"rect": [10, 10, 10, 10]})).unwrap(); + assert_eq!(miss["ids"], json!([])); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &before)); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + + // Remove 30 pt of source height: the remaining +10 pt live offset cannot + // repaint the cleared (125,105) pixel. The offset itself remains live. + let result = s.execute("path.eraseRegion", &json!({"rect": [50, 80, 200, 50]})).unwrap(); + assert_eq!(result["ids"].as_array().unwrap().len(), 1, "this is a one-piece extremal trim"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.ancestry(edited).unwrap(), ancestry); + let n = d.node(owner).unwrap(); + assert!((n.geometric_bounds().unwrap().y0 - 130.0).abs() < 1e-5, "the original owner bounds really shrink"); + assert_eq!(serde_json::to_value(&n.appearance.effects).unwrap(), effect_before, "the edit must not flatten or remove the live effect"); + let after_image = eraser_gradient_image(&s); + assert_eq!(after_image.pixel(125, 105)[3], 0, "the +10 offset cannot repaint this deliberately deep erased band"); + assert_eq!( + after_image.pixel(190, 175), + before_image.pixel(190, 175), + "group={group}, placed={placed}: freezing the raw Node box must not recolor retained effected art" + ); + if placed { + let vectorcraft_doc::color::Paint::Gradient(g) = n.appearance.fill_paint() else { panic!("the placed fill remains a gradient") }; + assert_eq!(serde_json::to_value(g.geom).unwrap(), geom); + } + eraser_container_gradient_restore(&mut s, &before_json, &selection, history); +} + +#[test] +fn eraser_container_gradient_keeps_evaluated_offset_fit() { + // Establish ordinary legal placement through the SAME live offset first. + eraser_container_effect_gradient_case(true, true); + eraser_container_effect_gradient_case(false, true); + eraser_container_effect_gradient_case(true, false); + eraser_container_effect_gradient_case(false, false); +} + +fn eraser_placement_ramp(placed: bool, bottom: f64, top: f64) -> Value { + let mut gradient = json!({"kind": "linear", "angle": 90, "dither": false, "stops": [ + {"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"} + ]}); + if placed { + gradient["start"] = json!([160, bottom]); + gradient["end"] = json!([160, top]); + } + gradient +} + +fn eraser_placement_effects(s: &Session, owner: NodeId) -> Value { + let n = s.doc().unwrap().doc.node(owner).unwrap(); + json!({"object": n.appearance.effects, + "items": n.appearance.items.iter().map(|item| item.effects()).collect::>()}) +} + +fn eraser_placement_trim( + s: &mut Session, + edited: NodeId, + owner: NodeId, + clear: (u32, u32), +) -> (vectorcraft_render::Rendered, vectorcraft_render::Rendered) { + let before_image = eraser_gradient_image(s); + assert_eq!(before_image.pixel(clear.0, clear.1)[3], 255, "the actual effected art paints the erase witness"); + let before = s.doc().unwrap().doc.clone(); + let before_json = serde_json::to_value(&before).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + let ancestry = before.ancestry(edited).unwrap(); + let effects = eraser_placement_effects(s, owner); + let bounds = before.node(owner).unwrap().geometric_bounds().unwrap(); + assert_eq!((bounds.y0, bounds.y1), (100.0, 200.0)); + let miss = s.execute("path.eraseRegion", &json!({"rect": [10, 10, 10, 10]})).unwrap(); + assert_eq!(miss["ids"], json!([])); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &before)); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + let result = s.execute("path.eraseRegion", &json!({"rect": [50, 80, 200, 50]})).unwrap(); + assert_eq!(result["ids"].as_array().unwrap().len(), 1, "the extremal trim keeps one piece"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.ancestry(edited).unwrap(), ancestry); + assert!((d.node(owner).unwrap().geometric_bounds().unwrap().y0 - 130.0).abs() < 1e-5); + assert_eq!(eraser_placement_effects(s, owner), effects, "stored object and item effects stay live and identical"); + let after_image = eraser_gradient_image(s); + assert_eq!(after_image.pixel(clear.0, clear.1)[3], 0, "the witness really leaves the effected art"); + eraser_container_gradient_restore(s, &before_json, &selection, history); + (before_image, after_image) +} + +fn eraser_placement_matches( + placed: &(vectorcraft_render::Rendered, vectorcraft_render::Rendered), + fitted: &(vectorcraft_render::Rendered, vectorcraft_render::Rendered), + samples: &[(u32, u32)], +) { + for &(x, y) in samples { + assert_eq!(placed.0.pixel(x, y)[3], 255); + assert_eq!(placed.1.pixel(x, y)[3], 255, "the equivalent placed control retains the sample"); + assert_eq!(fitted.0.pixel(x, y), placed.0.pixel(x, y), "the public placed vector is equivalent BEFORE the edit at ({x},{y})"); + assert_eq!( + fitted.1.pixel(x, y), + placed.1.pixel(x, y), + "fitted and equivalent placed paint follow the SAME live effects AFTER the edit at ({x},{y})" + ); + } + assert_ne!(placed.0.pixel(samples[0].0, samples[0].1), placed.0.pixel(samples[1].0, samples[1].1)); +} + +fn eraser_placement_affine_scene(placed: bool) -> (vectorcraft_render::Rendered, vectorcraft_render::Rendered) { + let mut s = session(); + let (edited, _, owner, _) = eraser_container_gradient_fixture(&mut s, false, false); + // Offset10 makes the original aggregate fit y=90..210. The explicit control + // fixes THAT frame before the following Transform carries it, not the raw box. + s.execute( + "appearance.setItem", + &json!({"ids": [owner.0], "target": "object", "index": 0, + "gradient": eraser_placement_ramp(placed, 210.0, 90.0)}), + ) + .unwrap(); + s.execute( + "effect.apply", + &json!({"ids": [owner.0], "target": "object", "item": null, + "effect": "path.offsetPath", "params": {"offset": 10, "joins": "round"}}), + ) + .unwrap(); + s.execute( + "effect.apply", + &json!({"ids": [owner.0], "target": "object", "item": null, + "effect": "distort.transform", "params": {"scaleH": 100, "scaleV": 150, + "reference": 8, "objects": true, "copies": 0, "random": false, + "rotate": 0, "moveH": 0, "moveV": 0, "patterns": false, "strokes": false}}), + ) + .unwrap(); + let n = s.doc().unwrap().doc.node(owner).unwrap(); + assert_eq!(n.appearance.effects.len(), 2); + let transform = &n.appearance.effects[1]; + assert_eq!(transform.id, "distort.transform"); + assert!(transform.visible); + assert_eq!(transform.params["scaleV"].as_f64(), Some(150.0)); + assert_eq!(transform.params["reference"].as_f64(), Some(8.0)); + assert_eq!(transform.params["objects"].as_bool(), Some(true)); + assert_eq!(transform.params["copies"].as_f64(), Some(0.0)); + let vectorcraft_doc::color::Paint::Gradient(g) = n.appearance.fill_paint() else { panic!("own Group gradient missing") }; + assert_eq!(g.geom.is_some(), placed); + // Reference8 is the bottom-right of the effected aggregate (230,210), + // unchanged by the top trim. V150 sends the original y90 edge to y30; + // without this actual affine action pixel(125,60) would be transparent. + eraser_placement_trim(&mut s, edited, owner, (125, 60)) +} + +#[test] +fn eraser_placement_control_affine_carry_matches_equivalent_placed() { + let placed = eraser_placement_affine_scene(true); + let fitted = eraser_placement_affine_scene(false); + eraser_placement_matches(&placed, &fitted, &[(190, 175), (190, 185)]); +} + +fn eraser_placement_item_stroke_scene(placed: bool) -> (vectorcraft_render::Rendered, vectorcraft_render::Rendered) { + let mut s = session(); + let id = marquee_rectangle(&mut s, true, false); + s.execute("paint.setFill", &json!({"ids": [id.0], "none": true})).unwrap(); + s.execute("stroke.set", &json!({"ids": [id.0], "weight": 10})).unwrap(); + // The row's +10 geometry expands y100..200 to y90..210; Within stroke + // weight10 fits its gradient to the inflated y85..215 paint box. + s.execute( + "paint.setStroke", + &json!({"ids": [id.0], + "gradient": eraser_placement_ramp(placed, 215.0, 85.0)}), + ) + .unwrap(); + let index = s + .doc() + .unwrap() + .doc + .node(id) + .unwrap() + .appearance + .items + .iter() + .position(|item| matches!(item, vectorcraft_doc::AppearanceItem::Stroke(_))) + .unwrap(); + s.execute("paint.editGradient", &json!({"ids": [id.0], "item": index, "stroke": true, "strokeMode": "within"})).unwrap(); + s.execute( + "effect.apply", + &json!({"ids": [id.0], "target": "object", "item": index, + "effect": "path.offsetPath", "params": {"offset": 10, "joins": "round"}}), + ) + .unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let n = s.doc().unwrap().doc.node(id).unwrap(); + assert!(matches!(n.kind, NodeKind::Path { .. })); + assert!(n.appearance.fill_paint().is_none()); + assert!(n.appearance.effects.is_empty(), "this effect belongs only to the stroke row"); + let vectorcraft_doc::AppearanceItem::Stroke(st) = &n.appearance.items[index] else { panic!("public stroke row missing") }; + assert_eq!(st.width, 10.0); + assert_eq!(st.gradient_mode, vectorcraft_doc::StrokeGradientMode::Within); + assert!(st.path_gradient().is_none(), "the test excludes Along/Across path-coordinate paint"); + assert_eq!(st.effects.len(), 1); + assert_eq!(st.effects[0].id, "path.offsetPath"); + assert!(st.effects[0].visible); + let vectorcraft_doc::color::Paint::Gradient(g) = &st.paint else { panic!("stroke gradient missing") }; + assert_eq!(g.geom.is_some(), placed); + assert!(!g.gradient.dither); + eraser_placement_trim(&mut s, id, id, (150, 90)) +} + +#[test] +fn eraser_placement_control_item_within_stroke_matches_equivalent_placed() { + let placed = eraser_placement_item_stroke_scene(true); + let fitted = eraser_placement_item_stroke_scene(false); + eraser_placement_matches(&placed, &fitted, &[(210, 175), (210, 185)]); +} + +fn eraser_mixed_gradient_hidden_stroke(s: &mut Session, id: NodeId, rasterize: bool) -> usize { + let index = s.doc().unwrap().doc.node(id).unwrap().appearance.items.iter().position(|item| !item.is_fill()).unwrap(); + s.execute( + "appearance.setItem", + &json!({"ids": [id.0], "index": index, "weight": 4, "gradient": { + "kind": "linear", "stops": [{"offset": 0, "color": "#00ff00"}, {"offset": 1, "color": "#ff00ff"}] + }}), + ) + .unwrap(); + let mode = if rasterize { "within" } else { "along" }; + s.execute("paint.editGradient", &json!({"ids": [id.0], "item": index, "stroke": true, "strokeMode": mode})).unwrap(); + if rasterize { + s.execute("effect.apply", &json!({"ids": [id.0], "target": "object", "item": index, "effect": "rasterize", "params": {}})).unwrap(); + } + s.execute("appearance.setItem", &json!({"ids": [id.0], "index": index, "visible": false})).unwrap(); + index +} + +fn eraser_mixed_gradient_rows_case(placed: bool, rasterize: bool) -> ([[u8; 4]; 2], [[u8; 4]; 2]) { + let mut s = session(); + let id = marquee_rectangle(&mut s, false, false); + let placed_geom = eraser_gradient_fill(&mut s, id, placed); + let index = eraser_mixed_gradient_hidden_stroke(&mut s, id, rasterize); + let node = s.doc().unwrap().doc.node(id).unwrap(); + assert!(!path(&s, id).is_closed(), "the fixture exercises the fill-only open-path route"); + assert!(node.appearance.has_drawn_fill()); + let hidden = node.appearance.items[index].clone(); + let vectorcraft_doc::AppearanceItem::Stroke(stroke) = &hidden else { panic!("the explicit row is a stroke") }; + assert!(!stroke.visible); + assert_eq!(stroke.width, 4.0, "the hidden row has a genuine positive stroke weight"); + assert!(matches!(stroke.paint, vectorcraft_doc::color::Paint::Gradient(_))); + assert_eq!(stroke.path_gradient().is_some(), !rasterize, "the two cases isolate the two owner-wide guard branches"); + assert_eq!( + stroke.gradient_mode, + if rasterize { vectorcraft_doc::StrokeGradientMode::Within } else { vectorcraft_doc::StrokeGradientMode::Along } + ); + assert_eq!(stroke.effects.iter().any(|e| e.visible && e.id == "rasterize"), rasterize); + assert!( + node.appearance + .items + .iter() + .all(|item| { !matches!(item, vectorcraft_doc::AppearanceItem::Stroke(st) if st.visible && !st.paint.is_none() && st.width > 0.0) }), + "no visible painted stroke may change Eraser's area eligibility" + ); + let vectorcraft_doc::color::Paint::Gradient(fill) = node.appearance.fill_paint() else { panic!("the visible fill is a gradient") }; + assert_eq!(fill.geom.is_some(), placed); + let before = s.doc().unwrap().doc.clone(); + let before_json = serde_json::to_value(&before).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + let before_image = eraser_gradient_image(&s); + let before_colors = [before_image.pixel(150, 125), before_image.pixel(150, 175)]; + assert!(before_colors.iter().all(|color| color[3] == 255)); + assert_ne!(before_colors[0], before_colors[1], "the visible fill is a genuine nonconstant ramp"); + assert_eq!(before_image.pixel(150, 150)[3], 255); + + let miss = eraser_gradient_region(&mut s, "rect", false, true); + assert_eq!(miss["ids"], json!([])); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &before)); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before_json); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + + let result = eraser_gradient_region(&mut s, "rect", false, false); + let ids = result["ids"].as_array().unwrap(); + assert_eq!(ids.len(), 2, "the marquee splits the filled area into two retained pieces"); + for value in ids { + let node = s.doc().unwrap().doc.node(NodeId(value.as_u64().unwrap())).unwrap(); + assert_eq!(node.appearance.items[index], hidden, "the unsupported hidden row stays byte-for-byte unchanged"); + if placed { + let vectorcraft_doc::color::Paint::Gradient(fill) = node.appearance.fill_paint() else { panic!("the fill stays a gradient") }; + assert_eq!(serde_json::to_value(fill.geom).unwrap(), placed_geom); + } + } + let after_image = eraser_gradient_image(&s); + assert_eq!(after_image.pixel(150, 150)[3], 0, "the intended fill band is erased"); + let after_colors = [after_image.pixel(150, 125), after_image.pixel(150, 175)]; + eraser_container_gradient_restore(&mut s, &before_json, &selection, history); + (before_colors, after_colors) +} + +#[test] +fn eraser_mixed_gradient_rows_keep_visible_fill_placement() { + let placed_along = eraser_mixed_gradient_rows_case(true, false); + assert_eq!(placed_along.0, placed_along.1, "an explicitly placed fill with hidden Along stroke is the legitimate control"); + let placed_rasterize = eraser_mixed_gradient_rows_case(true, true); + assert_eq!(placed_rasterize.0, placed_rasterize.1, "an explicitly placed fill with a hidden Rasterize row remains unchanged"); + // Finish both fitted scenes, including metadata/no-op/Undo controls, before the shared color assertion. + let fitted_along = eraser_mixed_gradient_rows_case(false, false); + let fitted_rasterize = eraser_mixed_gradient_rows_case(false, true); + assert!( + fitted_along.0 == fitted_along.1 && fitted_rasterize.0 == fitted_rasterize.1, + "hidden rows must not suppress the visible fill's placement: Along {fitted_along:?}; Rasterize {fitted_rasterize:?}" + ); +} + +fn eraser_endpoint_region(s: &mut Session, mode: &str, miss: bool) -> Value { + if mode == "rect" { + let rect = if miss { json!([55, 145, 10, 10]) } else { json!([150, 140, 20, 20]) }; + s.execute("path.eraseRegion", &json!({"rect": rect})).unwrap() + } else { + let points = if miss { json!([[60, 150]]) } else { json!([[160, 150]]) }; + erase(s, json!({"points": points, "size": 20}), mode == "varied") + } +} + +fn eraser_keeps_unused_endpoint_handles_out_of_fill_case(mode: &str) { + for (closed, stroked) in [(false, false), (true, false), (false, true)] { + let mut s = session(); + let id = NodeId( + s.execute( + "path.create", + &json!({"closed": closed, "anchors": [ + {"x": 100, "y": 100, "in": [0, 100]}, {"x": 200, "y": 100}, + {"x": 200, "y": 200}, {"x": 100, "y": 200, "out": [0, 200]} + ]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + if stroked { + s.execute("paint.setFill", &json!({"ids": [id.0], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "color": "#000000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [id.0], "weight": 4})).unwrap(); + } else { + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap(); + } + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let sp = &path(&s, id).subpaths[0]; + assert_eq!(sp.closed, closed); + assert_eq!(sp.anchors.first().unwrap().h_in, Point::new(0.0, 100.0)); + assert_eq!(sp.anchors.last().unwrap().h_out, Point::new(0.0, 200.0)); + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + let before_image = eraser_gradient_image(&s); + assert_eq!(before_image.pixel(60, 150)[3], if closed { 255 } else { 0 }, "{mode}: fixture closure"); + assert_eq!(before_image.pixel(160, 150)[3], if stroked { 0 } else { 255 }, "{mode}: interior witness"); + + let result = eraser_endpoint_region(&mut s, mode, false); + let after_image = eraser_gradient_image(&s); + assert_eq!(after_image.pixel(160, 150)[3], 0, "{mode}: erased interior"); + assert_eq!(after_image.pixel(60, 150), before_image.pixel(60, 150), "{mode}: no new bulge or lost closed curve"); + if stroked { + assert_eq!(result["ids"], json!([]), "{mode}: the open outline misses an interior dab"); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + continue; + } + assert_eq!(after_image.pixel(180, 180), [0, 0, 0, 255], "{mode}: retained fill"); + assert_eq!(s.doc().unwrap().history.undo.len(), history + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before, "{mode}: original geometry and endpoint handles restored"); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + if !closed { + let miss = eraser_endpoint_region(&mut s, mode, true); + assert_eq!(miss["ids"], json!([]), "{mode}: the phantom bulge cannot count as an intersection"); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + } + } +} + +#[test] +fn eraser_keeps_unused_endpoint_handles_out_of_fill_marquee() { + eraser_keeps_unused_endpoint_handles_out_of_fill_case("rect"); +} + +#[test] +fn eraser_keeps_unused_endpoint_handles_out_of_fill_fixed_tip() { + eraser_keeps_unused_endpoint_handles_out_of_fill_case("fixed"); +} + +#[test] +fn eraser_keeps_unused_endpoint_handles_out_of_fill_varied_tip() { + eraser_keeps_unused_endpoint_handles_out_of_fill_case("varied"); +} + +fn eraser_copying_container_gradient_before_colors(before_image: &vectorcraft_render::Rendered) -> [[u8; 4]; 2] { + let before_colors = [before_image.pixel(190, 175), before_image.pixel(190, 185)]; + assert!(before_colors.iter().all(|color| color[3] == 255)); + assert_ne!(before_colors[0], before_colors[1], "the original sibling draws a nonconstant gradient"); + assert_ne!(before_colors[0], [0, 0, 0, 255], "the Group's own fill covers the black child"); + assert_eq!(before_image.pixel(125, 105)[3], 255, "the original extremal child paints the trim witness"); + assert_eq!(before_image.pixel(190, 295)[3], 255, "the translated sibling copy really paints"); + before_colors +} + +fn eraser_copying_container_gradient_child_offset(s: &mut Session, sibling: NodeId, owner: NodeId, placed: bool) { + s.execute( + "effect.apply", + &json!({"ids": [sibling.0], "target": "object", "item": null, + "effect": "path.offsetPath", "params": {"offset": 10, "joins": "round"}}), + ) + .unwrap(); + // The untouched sibling's live offset makes the evaluated source box + // [100,100,230,210]; the Group's raw source box is still [100,100,220,200]. + let mut gradient = eraser_placement_ramp(placed, 210.0, 100.0); + if placed { + gradient["start"] = json!([165, 210]); + gradient["end"] = json!([165, 100]); + } + s.execute("appearance.setItem", &json!({"ids": [owner.0], "target": "object", "index": 0, "gradient": gradient})).unwrap(); + let sibling_node = s.doc().unwrap().doc.node(sibling).unwrap(); + assert_eq!(sibling_node.appearance.effects.len(), 1); + assert_eq!(sibling_node.appearance.effects[0].id, "path.offsetPath"); + assert!(sibling_node.appearance.effects[0].visible); + assert_eq!(sibling_node.appearance.effects[0].params["offset"].as_f64(), Some(10.0)); +} + +fn eraser_copying_container_gradient_scene(placed: bool) -> ([[u8; 4]; 2], [[u8; 4]; 2]) { + let mut s = session(); + let (edited, sibling, owner, geom) = eraser_container_gradient_fixture(&mut s, placed, false); + s.execute( + "effect.apply", + &json!({"ids": [owner.0], "target": "object", "item": null, + "effect": "stylize.dropShadow", "params": {"x": 10, "y": 0, "blur": 0}}), + ) + .unwrap(); + s.execute( + "effect.apply", + &json!({"ids": [owner.0], "target": "object", "item": null, + "effect": "distort.transform", "params": {"scaleH": 100, "scaleV": 100, + "reference": 8, "objects": true, "copies": 1, "random": false, + "rotate": 0, "moveH": 0, "moveV": 120, "patterns": false, "strokes": false}}), + ) + .unwrap(); + let n = s.doc().unwrap().doc.node(owner).unwrap(); + assert!(matches!(n.kind, NodeKind::Group { clip: false, .. })); + assert_eq!(n.appearance.effects.len(), 2); + assert_eq!(n.appearance.effects[0].id, "stylize.dropShadow"); + assert!(n.appearance.effects[0].visible); + assert_eq!(n.appearance.effects[1].id, "distort.transform"); + assert!(n.appearance.effects[1].visible); + assert_eq!(n.appearance.effects[1].params["copies"].as_f64(), Some(1.0)); + assert_eq!(n.appearance.effects[1].params["moveV"].as_f64(), Some(120.0)); + let effects = serde_json::to_value(&n.appearance.effects).unwrap(); + let before_image = eraser_gradient_image(&s); + let before_colors = eraser_copying_container_gradient_before_colors(&before_image); + let before = s.doc().unwrap().doc.clone(); + let before_json = serde_json::to_value(&before).unwrap(); + let sibling_before = serde_json::to_value(before.node(sibling).unwrap()).unwrap(); + let ancestry = before.ancestry(edited).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + let miss = eraser_gradient_region(&mut s, "rect", true, true); + assert_eq!(miss["ids"], json!([])); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &before), "a miss cannot pin an ancestor"); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before_json); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + let result = eraser_gradient_region(&mut s, "rect", true, false); + assert_eq!(result["ids"].as_array().unwrap().len(), 1, "the extremal trim keeps one piece"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.ancestry(edited).unwrap(), ancestry); + assert_eq!(serde_json::to_value(d.node(sibling).unwrap()).unwrap(), sibling_before, "the sibling itself is unchanged"); + let n = d.node(owner).unwrap(); + assert!(matches!(n.kind, NodeKind::Group { clip: false, .. })); + assert!((n.geometric_bounds().unwrap().y0 - 110.0).abs() < 1e-5); + assert_eq!(serde_json::to_value(&n.appearance.effects).unwrap(), effects, "both effects stay live and unchanged"); + if placed { + let vectorcraft_doc::color::Paint::Gradient(g) = n.appearance.fill_paint() else { panic!("the own fill stays a gradient") }; + assert_eq!(serde_json::to_value(g.geom).unwrap(), geom, "the explicit source fit must not be rewritten"); + } + let after_image = eraser_gradient_image(&s); + assert_eq!(after_image.pixel(125, 105)[3], 0, "the intended band was erased"); + let after_colors = [after_image.pixel(190, 175), after_image.pixel(190, 185)]; + assert!(after_colors.iter().all(|color| color[3] == 255)); + eraser_container_gradient_restore(&mut s, &before_json, &selection, history); + (before_colors, after_colors) +} + +#[test] +fn eraser_copying_container_gradient_keeps_source_fit_on_untouched_sibling() { + // The source is painted before its translated copy is made. The fixture's explicit + // [160,200] -> [160,100] fit is equivalent to the source's original fitted paint. + let placed = eraser_copying_container_gradient_scene(true); + let fitted = eraser_copying_container_gradient_scene(false); + assert_eq!(placed.0, placed.1, "the legitimate explicitly placed source fit preserves the untouched sibling"); + assert_eq!(fitted.0, placed.0, "both source fits must draw the same original sibling before editing"); + assert_eq!(fitted.1, fitted.0, "pinning a copying container must not recolor an untouched original sibling"); + assert_eq!(fitted.1, placed.1, "the fitted edit must match the equivalent explicitly placed source fit"); +} + +fn eraser_copying_container_gradient_owner_effects(n: &vectorcraft_doc::Node, nested_copy: bool) { + assert!(matches!(n.kind, NodeKind::Group { clip: false, .. })); + assert_eq!(n.appearance.effects.len(), if nested_copy { 3 } else { 2 }); + assert_eq!(n.appearance.effects[0].id, "stylize.dropShadow"); + assert!(n.appearance.effects[0].visible); + for (index, effect) in n.appearance.effects.iter().enumerate().skip(1) { + assert_eq!(effect.id, "distort.transform"); + assert!(effect.visible); + assert_eq!(effect.params["copies"].as_f64(), Some(1.0)); + let move_v = if nested_copy && index == 1 { 60.0 } else { 120.0 }; + assert_eq!(effect.params["moveV"].as_f64(), Some(move_v)); + } +} + +fn eraser_copying_container_gradient_variant_scene(placed: bool, nested_copy: bool) -> ([[u8; 4]; 2], [[u8; 4]; 2]) { + let mut s = session(); + let (edited, sibling, owner, _) = eraser_container_gradient_fixture(&mut s, placed, false); + if !nested_copy { + eraser_copying_container_gradient_child_offset(&mut s, sibling, owner, placed); + } + s.execute( + "effect.apply", + &json!({"ids": [owner.0], "target": "object", "item": null, + "effect": "stylize.dropShadow", "params": {"x": 10, "y": 0, "blur": 0}}), + ) + .unwrap(); + if nested_copy { + s.execute( + "effect.apply", + &json!({"ids": [owner.0], "target": "object", "item": null, + "effect": "distort.transform", "params": {"scaleH": 100, "scaleV": 100, + "reference": 8, "objects": true, "copies": 1, "random": false, + "rotate": 0, "moveH": 0, "moveV": 60, "patterns": false, "strokes": false}}), + ) + .unwrap(); + } + s.execute( + "effect.apply", + &json!({"ids": [owner.0], "target": "object", "item": null, + "effect": "distort.transform", "params": {"scaleH": 100, "scaleV": 100, + "reference": 8, "objects": true, "copies": 1, "random": false, + "rotate": 0, "moveH": 0, "moveV": 120, "patterns": false, "strokes": false}}), + ) + .unwrap(); + let n = s.doc().unwrap().doc.node(owner).unwrap(); + eraser_copying_container_gradient_owner_effects(n, nested_copy); + let vectorcraft_doc::color::Paint::Gradient(g) = n.appearance.fill_paint() else { panic!("the Group owns the gradient") }; + assert_eq!(g.geom.is_some(), placed); + let geom = serde_json::to_value(g.geom).unwrap(); + let effects = serde_json::to_value(&n.appearance.effects).unwrap(); + let before_image = eraser_gradient_image(&s); + let before_colors = eraser_copying_container_gradient_before_colors(&before_image); + let before = s.doc().unwrap().doc.clone(); + let before_json = serde_json::to_value(&before).unwrap(); + let sibling_before = serde_json::to_value(before.node(sibling).unwrap()).unwrap(); + let ancestry = before.ancestry(edited).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + let history = s.doc().unwrap().history.undo.len(); + let miss = eraser_gradient_region(&mut s, "rect", true, true); + assert_eq!(miss["ids"], json!([])); + assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &before), "a miss cannot pin an ancestor"); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before_json); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + let result = eraser_gradient_region(&mut s, "rect", true, false); + assert_eq!(result["ids"].as_array().unwrap().len(), 1, "the extremal trim keeps one piece"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.ancestry(edited).unwrap(), ancestry); + assert_eq!(serde_json::to_value(d.node(sibling).unwrap()).unwrap(), sibling_before, "the sibling itself is unchanged"); + let n = d.node(owner).unwrap(); + assert!(matches!(n.kind, NodeKind::Group { clip: false, .. })); + assert!((n.geometric_bounds().unwrap().y0 - 110.0).abs() < 1e-5); + assert_eq!(serde_json::to_value(&n.appearance.effects).unwrap(), effects, "both effects stay live and unchanged"); + if placed { + let vectorcraft_doc::color::Paint::Gradient(g) = n.appearance.fill_paint() else { panic!("the own fill stays a gradient") }; + assert_eq!(serde_json::to_value(g.geom).unwrap(), geom, "the explicit source fit must not be rewritten"); + } + let after_image = eraser_gradient_image(&s); + assert_eq!(after_image.pixel(125, 105)[3], 0, "the intended band was erased"); + let after_colors = [after_image.pixel(190, 175), after_image.pixel(190, 185)]; + assert!(after_colors.iter().all(|color| color[3] == 255)); + eraser_container_gradient_restore(&mut s, &before_json, &selection, history); + (before_colors, after_colors) +} + +#[test] +fn eraser_copying_container_gradient_keeps_evaluated_child_source_fit() { + let placed = eraser_copying_container_gradient_variant_scene(true, false); + let fitted = eraser_copying_container_gradient_variant_scene(false, false); + assert_eq!(placed.0, placed.1, "the explicitly placed evaluated-child source fit preserves the untouched sibling"); + assert_eq!(fitted.0, placed.0, "both paints fit the evaluated source before copying"); + assert_eq!(fitted.1, fitted.0, "pinning uses evaluated child geometry, not the raw prefix box"); + assert_eq!(fitted.1, placed.1, "fitted paint matches the equivalent evaluated-source placement after editing"); +} + +#[test] +fn eraser_copying_container_gradient_keeps_source_fit_through_earlier_copy() { + // Both copying effects are eligible: the outer split still leaves the earlier + // copying Transform in its prefix. Own paint is fitted before either copy. + let placed = eraser_copying_container_gradient_variant_scene(true, true); + let fitted = eraser_copying_container_gradient_variant_scene(false, true); + assert_eq!(placed.0, placed.1, "the explicit original-source fit is unchanged by the trim"); + assert_eq!(fitted.0, placed.0, "the original source fit is equivalent before both copy stages"); + assert_eq!(fitted.1, fitted.0, "pinning follows the earlier eligible copy split as rendering does"); + assert_eq!(fitted.1, placed.1, "both live copy stages preserve the same source placement after editing"); +} + +#[test] +fn eraser_keeps_group_painted_open_paths_on_the_outline_route() { + for mode in ["fixed", "varied", "marquee"] { + for group_stroke in [false, true] { + let mut s = session(); + let id = NodeId( + s.execute( + "path.create", + &json!({"anchors": [ + {"x": 100, "y": 100}, {"x": 200, "y": 100}, + {"x": 200, "y": 200}, {"x": 100, "y": 200} + ]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#0000ff"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + if group_stroke { + s.execute("appearance.addStroke", &json!({"ids": [group.0], "target": "object"})).unwrap(); + s.execute( + "appearance.setItem", + &json!({"ids": [group.0], "target": "object", "index": 0, + "color": "#ff0000", "weight": 4}), + ) + .unwrap(); + } + s.execute("select.none", &json!({})).unwrap(); + assert!(!path(&s, id).is_closed()); + let d = &s.doc().unwrap().doc; + assert_eq!(d.parent_of(id), Some(group)); + assert!(d.node(id).unwrap().appearance.stroke_paint().is_none()); + assert_eq!(d.node(group).unwrap().appearance.stroke_width(), if group_stroke { 4.0 } else { 0.0 }); + let render = |s: &Session| { + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()) + }; + let before_image = render(&s); + assert_eq!(before_image.pixel(150, 150), [0, 0, 255, 255]); + if group_stroke { + assert_eq!(before_image.pixel(150, 100), [255, 0, 0, 255], "the Group really paints the child's open outline"); + assert_eq!(before_image.pixel(99, 125)[3], 0, "the missing closing edge is not stroked"); + } + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let history = s.doc().unwrap().history.undo.len(); + let selection = s.doc().unwrap().selection.clone(); + let paint = s.paint.clone(); + // This ordinary Eraser gesture hits fill, at least 30 pt from every real outline. + let result = match mode { + "marquee" => s.execute("path.eraseRegion", &json!({"rect": [130, 145, 40, 10]})).unwrap(), + _ => erase(&mut s, json!({"points": [[130, 150], [170, 150]], "size": 10}), mode == "varied"), + }; + if group_stroke { + assert_eq!(result["ids"], json!([]), "{mode}: a Group-painted open outline keeps main's miss behavior"); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(render(&s).pixels, before_image.pixels); + } else { + assert!(!result["ids"].as_array().unwrap().is_empty(), "{mode}: the fill-only Group control still cuts as an area"); + let after_image = render(&s); + assert_eq!(after_image.pixel(150, 150)[3], 0); + assert_eq!(after_image.pixel(120, 125), [0, 0, 255, 255]); + } + assert_eq!(s.paint, paint); + } + } +} + +#[test] +fn eraser_ancestor_stroke_classification_keeps_container_context() { + for container in ["nested", "layer", "compound", "clip"] { + for stroke in ["painted", "hidden", "none", "zero"] { + eraser_ancestor_stroke_case(container, stroke); + } + } +} + +fn eraser_ancestor_stroke_case(container: &str, stroke: &str) { + let mut s = eraser_ancestor_stroke_scene(container, stroke); + let render = |s: &Session| { + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()) + }; + let before_image = render(&s); + assert_eq!(before_image.pixel(150, 150), [0, 0, 255, 255], "{container}/{stroke}: actual filled input"); + let outline_route = stroke == "painted" && container != "clip"; + if outline_route { + assert_eq!(before_image.pixel(150, 100), [255, 0, 0, 255], "{container}: actual ancestor stroke"); + } else if container == "clip" && stroke == "painted" { + assert_eq!(before_image.pixel(150, 90), [255, 0, 0, 255], "the ancestor paints the clipping outline"); + assert_eq!(before_image.pixel(150, 100), [0, 0, 255, 255], "the ancestor does not stroke the clipped child's outline"); + } + let before = serde_json::to_value(&s.doc().unwrap().doc).unwrap(); + let history = s.doc().unwrap().history.undo.len(); + let selection = s.doc().unwrap().selection.clone(); + let paint = s.paint.clone(); + let result = erase(&mut s, json!({"points": [[130, 150], [170, 150]], "size": 10}), false); + if outline_route { + assert_eq!(result["ids"], json!([]), "{container}/{stroke}: preserve main's open-outline miss"); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().history.undo.len(), history); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(render(&s).pixels, before_image.pixels); + } else { + assert!(!result["ids"].as_array().unwrap().is_empty(), "{container}/{stroke}: the eligible fill still cuts"); + let after_image = render(&s); + assert_eq!(after_image.pixel(150, 150)[3], 0, "{container}/{stroke}"); + assert_eq!(after_image.pixel(120, 125), [0, 0, 255, 255], "{container}/{stroke}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(serde_json::to_value(&s.doc().unwrap().doc).unwrap(), before); + assert_eq!(s.doc().unwrap().selection, selection); + assert_eq!(render(&s).pixels, before_image.pixels); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(render(&s).pixel(150, 150)[3], 0); + } + assert_eq!(s.paint, paint); +} + +fn eraser_ancestor_stroke_scene(container: &str, stroke: &str) -> Session { + let mut s = session(); + let id = NodeId( + s.execute( + "path.create", + &json!({"anchors": [ + {"x": 100, "y": 100}, {"x": 200, "y": 100}, + {"x": 200, "y": 200}, {"x": 100, "y": 200} + ]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "#0000ff"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let mut subject = id; + if container == "compound" { + let other = s + .execute( + "path.create", + &json!({"anchors": [ + {"x": 220, "y": 100}, {"x": 240, "y": 100}, + {"x": 240, "y": 120}, {"x": 220, "y": 120} + ]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("paint.setFill", &json!({"ids": [other], "color": "#0000ff"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [other], "none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0, other]})).unwrap(); + subject = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let NodeKind::Compound { children, .. } = &s.doc().unwrap().doc.node(subject).unwrap().kind else { + panic!("the public Make command produces a compound path") + }; + assert_eq!(children.len(), 2); + assert!(children.iter().all(|child| !child.path_data().unwrap().is_closed())); + } else if container == "clip" { + let mask = s.execute("shape.rectangle", &json!({"x": 90, "y": 90, "width": 120, "height": 120})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [id.0, mask]})).unwrap(); + subject = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + assert!(s.doc().unwrap().doc.node(subject).unwrap().clips()); + } + let owner = if container == "layer" { + s.doc().unwrap().doc.layer_of(id).unwrap() + } else { + s.execute("select.set", &json!({"ids": [subject.0]})).unwrap(); + let inner = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + if container == "nested" { NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()) } else { inner } + }; + s.execute("appearance.addStroke", &json!({"ids": [owner.0], "target": "object"})).unwrap(); + s.execute( + "appearance.setItem", + &json!({"ids": [owner.0], "target": "object", "index": 0, + "color": "#ff0000", "weight": if stroke == "zero" { 0 } else { 4 }, "visible": stroke != "hidden"}), + ) + .unwrap(); + if stroke == "none" { + s.execute("appearance.setItem", &json!({"ids": [owner.0], "target": "object", "index": 0, "none": true})).unwrap(); + } + // Select only the original open child (or the two-member compound). In the clip + // control, neither the mask nor the other container geometry is an Eraser target. + let selected = if container == "compound" { subject } else { id }; + s.execute("select.set", &json!({"ids": [selected.0]})).unwrap(); + s +} + +// Pinning-only checks: no Eraser operation or other geometry edit is performed below. +fn eraser_pinning_only_same_pixels(a: &vectorcraft_render::Rendered, b: &vectorcraft_render::Rendered, label: &str) { + let changed = (0..300).find_map(|y| (0..300).find(|&x| a.pixel(x, y) != b.pixel(x, y)).map(|x| (x, y, a.pixel(x, y), b.pixel(x, y)))); + assert_eq!(changed, None, "{label}: first changed pixel"); +} + +fn eraser_pinning_only_nested_scene(placed: bool, parent_offset: bool) -> (Session, NodeId) { + let mut s = session(); + let (_, _, owner, _) = eraser_container_gradient_fixture(&mut s, false, false); + s.execute("select.set", &json!({"ids": [owner.0]})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + if parent_offset { + s.execute( + "effect.apply", + &json!({"ids": [outer.0], "target": "object", "item": null, + "effect": "path.offsetPath", "params": {"offset": 10, "joins": "round"}}), + ) + .unwrap(); + } + // These are the retained ordinary fit and the existing +10 pt evaluated fit. + let (bottom, top) = if parent_offset { (210.0, 90.0) } else { (200.0, 100.0) }; + s.execute( + "appearance.setItem", + &json!({"ids": [owner.0], "target": "object", "index": 0, + "gradient": eraser_placement_ramp(placed, bottom, top)}), + ) + .unwrap(); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.parent_of(owner), Some(outer), "INPUT: the gradient owner is nested in the effect owner"); + assert_eq!(doc.node(owner).unwrap().geometric_bounds().unwrap(), vectorcraft_geom::Rect::new(100.0, 100.0, 220.0, 200.0)); + assert!(doc.node(owner).unwrap().appearance.effects.is_empty(), "INPUT: the offset belongs to the enclosing Group only"); + let effects = &doc.node(outer).unwrap().appearance.effects; + assert_eq!(effects.len(), usize::from(parent_offset)); + if parent_offset { + assert_eq!(effects[0].id, "path.offsetPath"); + assert!(effects[0].visible); + assert_eq!(effects[0].params["offset"].as_f64(), Some(10.0)); + assert_eq!(effects[0].params["joins"], json!("round")); + } + let vectorcraft_doc::color::Paint::Gradient(g) = doc.node(owner).unwrap().appearance.fill_paint() else { + panic!("INPUT: the nested Group owns the gradient") + }; + assert_eq!(g.geom.is_some(), placed); + assert!(!g.gradient.dither); + (s, owner) +} + +fn eraser_pinning_only_nested_case(parent_offset: bool) { + let (s, owner) = eraser_pinning_only_nested_scene(false, parent_offset); + let (placed, placed_owner) = eraser_pinning_only_nested_scene(true, parent_offset); + let before = eraser_gradient_image(&s); + let explicit = eraser_gradient_image(&placed); + assert_eq!(before.pixel(190, 175)[3], 255, "INPUT: the retained sibling is painted"); + assert_eq!(before.pixel(190, 185)[3], 255); + assert_ne!(before.pixel(190, 175), before.pixel(190, 185), "INPUT: the fitted ramp is nonconstant"); + if parent_offset { + assert_eq!(before.pixel(190, 205)[3], 255, "INPUT: the enclosing positive offset reaches beyond the raw box"); + } + eraser_pinning_only_same_pixels(&before, &explicit, "INPUT: the independently placed control matches before pinning"); + let placed_doc = &placed.doc().unwrap().doc; + assert!( + vectorcraft_render::pinned_appearance_for_geometry_edit(placed_doc, placed_doc.node(placed_owner).unwrap()).is_none(), + "INPUT: an already explicit placement needs no pinning" + ); + let label = + if parent_offset { "PINNING_ONLY: nested Group under positive Offset Path" } else { "CONTROL: nested Group without enclosing effects" }; + eraser_pinning_only_store(&s.doc().unwrap().doc, owner, &before, !parent_offset, label); +} + +fn eraser_pinning_only_store(doc: &vectorcraft_doc::Document, owner: NodeId, before: &vectorcraft_render::Rendered, required: bool, label: &str) { + let original = serde_json::to_value(doc).unwrap(); + let node = doc.node(owner).unwrap(); + let Some(pinned) = vectorcraft_render::pinned_appearance_for_geometry_edit(doc, node) else { + assert!(!required, "INPUT: the ordinary control must pin reproducibly: {label}"); + assert_eq!(serde_json::to_value(doc).unwrap(), original); + println!("PINNING_FALLBACK: {label} remains fitted; no pixel failure established"); + return; + }; + assert_eq!(serde_json::to_value(doc).unwrap(), original, "INPUT: the public helper leaves its input unchanged"); + let vectorcraft_doc::color::Paint::Gradient(g) = pinned.fill_paint() else { panic!("INPUT: returned paint is a gradient") }; + assert!(g.geom.is_some(), "INPUT: the returned fitted gradient has an explicit placement"); + // The fixed linear fixture permits only stored gradient geometry to change, not effects or other row data. + let mut normalized = pinned.clone(); + assert_eq!(normalized.items.len(), node.appearance.items.len()); + for (after, before) in normalized.items.iter_mut().zip(&node.appearance.items) { + if let (vectorcraft_doc::color::Paint::Gradient(a), vectorcraft_doc::color::Paint::Gradient(b)) = (after.paint_mut(), before.paint()) { + a.geom = b.geom; + } + } + assert_eq!(serde_json::to_value(&normalized).unwrap(), serde_json::to_value(&node.appearance).unwrap(), "INPUT: only placement changes"); + let mut only_paint = doc.clone(); + only_paint.node_mut(owner).unwrap().appearance = pinned.into(); + let mut restored = only_paint.clone(); + restored.node_mut(owner).unwrap().appearance = node.appearance.clone(); + assert_eq!(serde_json::to_value(&restored).unwrap(), original, "INPUT: geometry, effects and every other source field are unchanged"); + let after = vectorcraft_render::Renderer::new().render(&only_paint, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()); + eraser_pinning_only_same_pixels(before, &after, label); +} + +#[test] +fn eraser_pinning_only_nested_gradient_matches_unchanged_render() { + // Establish the ordinary nested Group without an enclosing geometry effect FIRST. + eraser_pinning_only_nested_case(false); + // One retained positive offset, no cut, parameter search or timing measurement. + eraser_pinning_only_nested_case(true); +} + +fn eraser_pinning_only_text_clip_case(stroked: bool, no_stroke: Option<&vectorcraft_render::Rendered>) -> vectorcraft_render::Rendered { + assert_eq!(stroked, no_stroke.is_some(), "INPUT: the subject follows its no-stroke control"); + // Original clippaint.rs text, paint, font defaults and geometry; one retained ordinary scale. + let mut s = session(); + let art = s.execute("shape.rectangle", &json!({"x": 0, "y": 50, "width": 30, "height": 100})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"ids": [art], "color": "#ff0000"})).unwrap(); + let text = NodeId(s.execute("text.create", &json!({"x": 10, "y": 120, "text": "Clip", "size": 72})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.all", &json!({})).unwrap(); + let owner = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [text.0], "color": "#0000ff"})).unwrap(); + if stroked { + s.execute("paint.setStroke", &json!({"ids": [text.0], "color": "#00ff00"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [text.0], "weight": 2})).unwrap(); + } else { + s.execute("paint.setStroke", &json!({"ids": [text.0], "none": true})).unwrap(); + } + s.execute("appearance.addFill", &json!({"ids": [owner.0], "target": "object"})).unwrap(); + s.execute( + "appearance.setItem", + &json!({"ids": [owner.0], "target": "object", "index": 0, "gradient": eraser_placement_ramp(false, 200.0, 100.0)}), + ) + .unwrap(); + s.execute( + "effect.apply", + &json!({"ids": [owner.0], "target": "object", "item": null, "effect": "distort.transform", + "params": {"scaleH": 100, "scaleV": 150, "reference": 8, "objects": true, "copies": 0, + "random": false, "rotate": 0, "moveH": 0, "moveV": 0, "patterns": false, "strokes": false}}), + ) + .unwrap(); + let doc = &s.doc().unwrap().doc; + let node = doc.node(owner).unwrap(); + assert!(node.clips(), "INPUT: the source is a clipping Group"); + assert_eq!(node.children().unwrap()[0].id, text); + let t = doc.node(text).unwrap(); + let NodeKind::Text(type_) = &t.kind else { panic!("INPUT: the clipping object is type") }; + assert_eq!(type_.plain_text(), "Clip"); + assert_eq!(t.clip_paint().stroke.is_some(), stroked, "INPUT: only the character-stroke paint distinguishes the control"); + let bounds = t.geometric_bounds().unwrap(); + assert!(bounds.width() > 0.0 && bounds.height() > 0.0, "INPUT: actual font setup supplies nonempty glyph geometry"); + let effects = &node.appearance.effects; + assert_eq!(effects.len(), 1); + assert_eq!(effects[0].id, "distort.transform"); + assert!(effects[0].visible); + for (key, expected) in [("scaleH", 100.0), ("scaleV", 150.0), ("reference", 8.0), ("copies", 0.0)] { + assert_eq!(effects[0].params[key].as_f64(), Some(expected), "INPUT: accepted Transform {key}"); + } + let before = eraser_gradient_image(&s); + let background = before.pixel(299, 299); + assert_eq!(background[3], 0, "INPUT: the retained background sample is clear"); + if let Some(control) = no_stroke { + assert_eq!(control.pixel(299, 299), background, "INPUT: both unchanged renders use the same background"); + } + let mut ramp = std::collections::BTreeSet::new(); + let mut green = 0; + let mut outside_green = 0; + for y in 0..300 { + for x in 0..300 { + let p = before.pixel(x, y); + if p[3] == 255 && p[0] > 0 && p[2] > 0 && p[1] == 0 { + ramp.insert(p); + } + let painted_stroke = p[3] > 0 && p[1] > 200 && p[0] < 60 && p[2] < 60; + green += usize::from(painted_stroke); + outside_green += usize::from(painted_stroke && no_stroke.is_some_and(|control| control.pixel(x, y) == background)); + } + } + assert!(ramp.len() > 1, "INPUT: the fitted container gradient paints actual nonconstant glyph pixels"); + assert_eq!(green > 0, stroked, "INPUT: the painted-character stroke is actually visible only in the subject"); + if stroked { + assert!(outside_green > 0, "INPUT: the actual character stroke paints where the no-stroke control has only clear background"); + } + let label = + if stroked { "PINNING_ONLY: painted clipping text under nonuniform scale" } else { "CONTROL: same glyph/scale without painted-clip wrapper" }; + eraser_pinning_only_store(doc, owner, &before, !stroked, label); + before +} + +#[test] +fn eraser_pinning_only_painted_text_clip_matches_unchanged_render() { + let control = eraser_pinning_only_text_clip_case(false, None); + eraser_pinning_only_text_clip_case(true, Some(&control)); +} + +#[test] +fn eraser_pinning_only_keeps_hidden_geometry_and_raster_ancestors_supported() { + for raster in [false, true] { + let (mut s, owner) = eraser_pinning_only_nested_scene(false, !raster); + let outer = s.doc().unwrap().doc.parent_of(owner).unwrap(); + if raster { + s.execute( + "effect.apply", + &json!({"ids": [outer.0], "target": "object", "item": null, "effect": "blur.gaussian", "params": {"radius": 3}}), + ) + .unwrap(); + } + let mut doc = (*s.doc().unwrap().doc).clone(); + if !raster { + let ancestor = doc.node_mut(outer).unwrap(); + ancestor.appearance.effects[0].visible = false; + } + let effect = &doc.node(outer).unwrap().appearance.effects[0]; + assert_eq!(doc.node(outer).unwrap().appearance.effects.len(), 1); + assert_eq!(effect.visible, raster); + if raster { + assert_eq!(effect.id, "blur.gaussian"); + assert_eq!(effect.params["radius"].as_f64(), Some(3.0)); + } else { + assert_eq!(effect.id, "path.offsetPath"); + assert_eq!(effect.params["offset"].as_f64(), Some(10.0)); + } + let before = vectorcraft_render::Renderer::new().render(&doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()); + assert_eq!(before.pixel(190, 175)[3], 255, "INPUT: ordinary gradient art remains visible"); + assert_ne!(before.pixel(190, 175), before.pixel(190, 185), "INPUT: the paint is nonconstant"); + let label = if raster { "CONTROL: visible Gaussian ancestor" } else { "CONTROL: hidden Offset Path ancestor" }; + eraser_pinning_only_store(&doc, owner, &before, true, label); + } +} diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index ca766a64f4..27ce315d92 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -7,8 +7,10 @@ //! opcodes with random contents) opened or placed, nor EPS and PostScript files //! (damaged ones, hostile programs) read by the PostScript interpreter, nor the editing data of //! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor Affinity documents -//! (mutated object streams, archives and indexed PNG previews, hostile image dimensions), nor the -//! font files a folder search reads (damaged fonts, collections whose headers give any count of +//! (mutated object streams, archives and indexed PNG previews, hostile image dimensions), nor +//! `.cdr` drawings (mutated and cut short, plain, compressed and packaged, opened and placed), +//! nor `.cmx` files (mutated, cut short and garbage after the header, opened and placed), +//! nor the font files a folder search reads (damaged fonts, collections whose headers give any count of //! faces), nor scripts written for the reference app checked without running them (garbage, //! generated script text and mutated scripts). //! @@ -303,6 +305,181 @@ proptest! { } } +// ---------- .cdr drawings ---------- + +proptest! { + #![proptest_config(config())] + + #[test] + fn cdr_mutated_drawings_render_and_export( + version in prop::sample::select(vec![300u16, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200, 1300]), + compress: bool, + features: bool, + cut in 12usize..8192, + edits in prop::collection::vec((0usize..8192, any::()), 0..24), + ) { + // The feature sample adds a style table, a clipping container and a lens to the shapes. + let compress = compress && version >= 700; + let mut bytes = + if features { vectorcraft_cdr::synth::feature_sample(version, compress) } else { vectorcraft_cdr::synth::sample(version, compress) }; + let n = bytes.len(); + for (at, b) in edits { bytes[at % n] = b; } + bytes.truncate(cut); + survive("CDR drawing", || vectorcraft_engine::cmd::fileio::load("x.cdr", &bytes).ok().map(|l| l.doc))?; + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + let p = json!({"name":"x.cdr", "dataBase64":vectorcraft_format::base64_encode(&bytes)}); + let _ = no_panic(s.execute("file.place", &p)); + }); + prop_assert!(r.is_ok(), "CDR drawing placement panicked: {:?}", r.err()); + } + + #[test] + fn cdr_mutated_packages_render_and_export( + version in prop::sample::select(vec![1400u16, 1500, 1600, 2000, 2700]), + cut in prop::option::of(22usize..16384), + edits in prop::collection::vec((any::(), 0usize..8192, any::()), 0..24), + ) { + // The members are edited before they are zipped, so that the edits reach the drawing + // rather than stop at the CRC-32; the archive may then be cut short. + let mut members = if version < 1600 { + vec![vectorcraft_cdr::synth::Member { name: "content/riffData.cdr".into(), data: vectorcraft_cdr::synth::sample(version, true), deflate: false }] + } else { + let mut body = vec![vectorcraft_cdr::synth::chunk(b"vrsn", version.to_le_bytes().to_vec())]; + body.extend(vectorcraft_cdr::synth::sample_content(version)); + vectorcraft_cdr::synth::package16_members(version, &body, false, &[]) + }; + for (m, at, b) in edits { + let k = m % members.len(); + let data = &mut members[k].data; + if !data.is_empty() { + let n = data.len(); + data[at % n] = b; + } + } + let mut bytes = vectorcraft_cdr::synth::zip(&members, b""); + if let Some(cut) = cut { + bytes.truncate(cut); + } + survive("CDR package", || vectorcraft_engine::cmd::fileio::load("x.cdr", &bytes).ok().map(|l| l.doc))?; + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + let p = json!({"name":"x.cdr", "dataBase64":vectorcraft_format::base64_encode(&bytes)}); + let _ = no_panic(s.execute("file.place", &p)); + }); + prop_assert!(r.is_ok(), "CDR package placement panicked: {:?}", r.err()); + } + + #[test] + fn cdr_garbage_opens_and_places_without_panicking(tail in prop::collection::vec(any::(), 0..2048)) { + let mut bytes = b"RIFF".to_vec(); + bytes.extend(((4 + tail.len()) as u32).to_le_bytes()); + bytes.extend(b"CDRB"); + bytes.extend(tail); + survive("CDR garbage", || vectorcraft_engine::cmd::fileio::load("x.cdr", &bytes).ok().map(|l| l.doc))?; + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + let p = json!({"name":"x.cdr", "dataBase64":vectorcraft_format::base64_encode(&bytes)}); + let _ = no_panic(s.execute("file.place", &p)); + }); + prop_assert!(r.is_ok(), "CDR placement panicked: {:?}", r.err()); + } + + // Drawings of versions 1 and 2 are not RIFF files: a header of offsets, then records. + #[test] + fn cdr_mutated_wl_drawings_render_and_export( + marker in prop::sample::select(vec![b'e', b'l', b'm']), + cut in prop::option::of(0usize..1024), + edits in prop::collection::vec((0usize..8192, any::()), 0..24), + ) { + let mut bytes = vectorcraft_cdr::synth::wl_sample(marker); + let n = bytes.len(); + for (at, b) in edits { bytes[at % n] = b; } + if let Some(cut) = cut { + bytes.truncate(cut); + } + survive("CDR drawing of version 1 or 2", || vectorcraft_engine::cmd::fileio::load("x.cdr", &bytes).ok().map(|l| l.doc))?; + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + let p = json!({"name":"x.cdr", "dataBase64":vectorcraft_format::base64_encode(&bytes)}); + let _ = no_panic(s.execute("file.place", &p)); + }); + prop_assert!(r.is_ok(), "placing a CDR drawing of version 1 or 2 panicked: {:?}", r.err()); + } + + #[test] + fn cdr_garbage_after_a_wl_header_opens_and_places_without_panicking( + marker in prop::sample::select(vec![b'e', b'l', b'm']), + tail in prop::collection::vec(any::(), 0..2048), + ) { + // Offsets that fit the file, so the garbage is walked as records. + let mut bytes = vec![b'W', b'L', marker, 0]; + bytes.extend(28u32.to_le_bytes()); + bytes.extend(28u32.to_le_bytes()); + bytes.extend((28 + tail.len() as u32).to_le_bytes()); + bytes.extend([0; 12]); + bytes.extend(tail); + survive("CDR garbage of version 1 or 2", || vectorcraft_engine::cmd::fileio::load("x.cdr", &bytes).ok().map(|l| l.doc))?; + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + let p = json!({"name":"x.cdr", "dataBase64":vectorcraft_format::base64_encode(&bytes)}); + let _ = no_panic(s.execute("file.place", &p)); + }); + prop_assert!(r.is_ok(), "placing CDR garbage of version 1 or 2 panicked: {:?}", r.err()); + } +} + +// ---------- .cmx files ---------- + +proptest! { + #![proptest_config(config())] + + #[test] + fn cmx_mutated_files_render_and_export( + cut in prop::option::of(12usize..4096), + edits in prop::collection::vec((0usize..8192, any::()), 0..24), + ) { + let mut bytes = vectorcraft_cdr::synth_cmx::sample(); + let n = bytes.len(); + for (at, b) in edits { bytes[at % n] = b; } + if let Some(cut) = cut { + bytes.truncate(cut); + } + survive("CMX file", || vectorcraft_engine::cmd::fileio::load("x.cmx", &bytes).ok().map(|l| l.doc))?; + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + let p = json!({"name":"x.cmx", "dataBase64":vectorcraft_format::base64_encode(&bytes)}); + let _ = no_panic(s.execute("file.place", &p)); + }); + prop_assert!(r.is_ok(), "CMX placement panicked: {:?}", r.err()); + } + + #[test] + fn cmx_garbage_opens_and_places_without_panicking(tail in prop::collection::vec(any::(), 0..2048)) { + // A 32-bit header, so the garbage is walked as chunks, tables and instructions. + let mut bytes = b"RIFF".to_vec(); + let cont = vectorcraft_cdr::synth_cmx::cont(b'4', 1e-7); + bytes.extend(((4 + cont.len() + tail.len()) as u32).to_le_bytes()); + bytes.extend(b"CMX1"); + bytes.extend(cont); + bytes.extend(tail); + survive("CMX garbage", || vectorcraft_engine::cmd::fileio::load("x.cmx", &bytes).ok().map(|l| l.doc))?; + let r = catch_quiet(|| { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + let p = json!({"name":"x.cmx", "dataBase64":vectorcraft_format::base64_encode(&bytes)}); + let _ = no_panic(s.execute("file.place", &p)); + }); + prop_assert!(r.is_ok(), "CMX placement panicked: {:?}", r.err()); + } +} + // ---------- Affinity documents with every feature the reader maps ---------- #[path = "support/affinity_docs.rs"] diff --git a/crates/engine/tests/it/align_automatic_reference.rs b/crates/engine/tests/it/align_automatic_reference.rs new file mode 100644 index 0000000000..2bdc5df5fc --- /dev/null +++ b/crates/engine/tests/it/align_automatic_reference.rs @@ -0,0 +1,69 @@ +//! Engine-only controls for explicit automatic Align references. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; +use vectorcraft_engine::Session; +use vectorcraft_geom::Point; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300, "profile": null})).unwrap(); + s +} + +fn align_with(s: &mut Session, mut params: Value, automatic: bool) { + if automatic { + params["to"] = json!("auto"); + } + s.execute("object.align", ¶ms).unwrap(); +} + +#[test] +fn automatic_align_keeps_one_objects_key_guide_reference() { + for automatic in [false, true] { + let mut s = session(); + let id = NodeId(s.execute("shape.rectangle", &json!({"x": 20, "y": 40, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap()); + s.execute("guide.add", &json!({"vertical": false, "pos": 210})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + s.execute("select.key", &json!({"guide": 0})).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + assert_eq!(selection.len(), 1); + assert!(selection.has_key()); + let guide = selection.key_guide.unwrap(); + + align_with(&mut s, json!({"horizontal": "right", "vertical": "bottom", "bounds": "geometric"}), automatic); + let bounds = s.doc().unwrap().doc.bounds_of(&[id], false).unwrap(); + assert_eq!( + (bounds.x0, bounds.y0, bounds.x1, bounds.y1), + (20.0, 190.0, 60.0, 210.0), + "the horizontal key guide overrides the one-object artboard rule and leaves x alone" + ); + assert_eq!(s.doc().unwrap().doc.ruler_guide(guide).unwrap().pos, 210.0); + assert_eq!(s.doc().unwrap().selection, selection, "reference resolution does not create or clear a key"); + } +} + +#[test] +fn automatic_align_keeps_a_single_paths_selected_anchor_bounds() { + for automatic in [false, true] { + let mut s = session(); + let id = NodeId(s.execute("path.create", &json!({"d": "M20 40 L60 100 L100 40", "closed": false})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); + let selection = s.doc().unwrap().selection.clone(); + assert_eq!(selection.len(), 1); + assert!(!selection.anchors.is_empty()); + assert!(!selection.has_key()); + + align_with(&mut s, json!({"horizontal": "center", "bounds": "geometric"}), automatic); + let document = &s.doc().unwrap().doc; + let path = document.node(id).unwrap().path_data().unwrap(); + let points: Vec = path.subpaths.first().unwrap().anchors.iter().map(|anchor| anchor.p).collect(); + assert_eq!( + points, + [Point::new(40.0, 40.0), Point::new(40.0, 100.0), Point::new(100.0, 40.0)], + "only picked anchors use their own center; the whole path is not centered on the artboard" + ); + assert_eq!(s.doc().unwrap().selection, selection); + } +} diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index f864877025..28417f031a 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -1956,6 +1956,182 @@ fn an_anchor_beside_a_drawn_dimension_takes_the_point() { assert_eq!(linear_marker(&mut s, zoomed, 125.5, 358.3), (Some((pt(126.0, 358.0), 10.0)), vec!["anchor".to_string()])); } +/// The Smart Guide lines a pointer move at (`x`, `y`) shows, as their ends. +fn guide_lines(s: &mut Session, view: ViewInfo, x: f64, y: f64) -> Vec<(vectorcraft_geom::Point, vectorcraft_geom::Point)> { + use vectorcraft_engine::tools::Overlay; + s.pointer(&PointerEvent::new(PointerKind::Move, x, y), view).unwrap(); + s.overlays(view).into_iter().filter_map(|o| if let Overlay::Line { a, b, .. } = o { Some((a, b)) } else { None }).collect() +} + +/// An edge with anchors at x 100, 200 and 300, and a dimension from 100 to 200 placed 30 points +/// above it, with the Dimension tool active and nothing selected: the session and the dimension. +fn level_start(view: ViewInfo) -> (Session, u64) { + let pt = vectorcraft_geom::Point::new; + let mut s = session(); + run(&mut s, "path.create", json!({"d": "M100 200 L200 200 L300 200 L300 300 L100 300 Z"})); + run(&mut s, "select.none", json!({})); + s.select_tool("dimension", view).unwrap(); + linear_click(&mut s, view, 100.0, 200.0); + linear_click(&mut s, view, 200.0, 200.0); + linear_click(&mut s, view, 150.0, 170.0); + let first = s.doc().unwrap().selection.objects[0].0; + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0))); + run(&mut s, "select.none", json!({})); + (s, first) +} + +/// The next dimension, from 200 to 300, placed with the pointer at `y`: where its line lies. +fn level_next(s: &mut Session, view: ViewInfo, y: f64) -> (vectorcraft_geom::Point, vectorcraft_geom::Point) { + linear_click(s, view, 200.0, 200.0); + linear_click(s, view, 300.0, 200.0); + linear_click(s, view, 250.0, y); + let id = s.doc().unwrap().selection.objects[0].0; + recipe(s, id).line_ends() +} + +/// A dimension placed next to another, with its line within the Smart Guides snapping tolerance of +/// the level of the other's parallel line, has its line on that level. A level further off, Smart +/// Guides off, a locked dimension or one that is not parallel leaves the line where the pointer +/// puts it. +#[test] +fn a_dimension_line_placed_beside_another_lands_on_its_level() { + let plain = ViewInfo::default(); + let off = ViewInfo { smart_guides: false, ..plain }; + let pt = vectorcraft_geom::Point::new; + // 2.5 points below the first line's level, and 3.5 above it: on the level. + for y in [172.5, 166.5] { + let (mut s, _) = level_start(plain); + assert_eq!(level_next(&mut s, plain, y), (pt(200.0, 170.0), pt(300.0, 170.0)), "pointer at y {y}"); + } + // 10 points off: where the pointer is. + let (mut s, _) = level_start(plain); + assert_eq!(level_next(&mut s, plain, 180.0), (pt(200.0, 180.0), pt(300.0, 180.0))); + // Smart Guides off: where the pointer is. + let (mut s, _) = level_start(off); + assert_eq!(level_next(&mut s, off, 172.5), (pt(200.0, 172.5), pt(300.0, 172.5))); + // A locked dimension does not pull the line. + let (mut s, first) = level_start(plain); + run(&mut s, "select.set", json!({"ids":[first]})); + run(&mut s, "object.lock", json!({})); + assert_eq!(level_next(&mut s, plain, 172.5), (pt(200.0, 172.5), pt(300.0, 172.5))); + // A dimension of the right edge has a vertical line, which is not parallel to the first: the + // pointer 2.5 points below the first line's level places it where the pointer is. + let (mut s, _) = level_start(plain); + linear_click(&mut s, plain, 300.0, 200.0); + linear_click(&mut s, plain, 300.0, 300.0); + linear_click(&mut s, plain, 330.0, 172.5); + let id = s.doc().unwrap().selection.objects[0].0; + assert_eq!(recipe(&s, id).line_ends(), (pt(330.0, 200.0), pt(330.0, 300.0))); +} + +/// While a dimension is placed with its line on the level of another, one alignment guide runs +/// along the level across both lines. Off the level, after a dropped press and with Alignment +/// Guides off, no guide shows. +#[test] +fn a_dimension_line_on_another_level_shows_one_guide_across_both() { + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + let (mut s, _) = level_start(plain); + linear_click(&mut s, plain, 200.0, 200.0); + linear_click(&mut s, plain, 300.0, 200.0); + let guides = guide_lines(&mut s, plain, 250.0, 172.5); + assert!(guides.iter().any(|(a, b)| near(*a, pt(100.0, 170.0)) && near(*b, pt(300.0, 170.0))), "{guides:?}"); + assert!(guide_lines(&mut s, plain, 250.0, 180.0).is_empty(), "no guide off the level"); + // A press on the level that the app drops cancels the preview, and its guide goes with it. + assert!(!guide_lines(&mut s, plain, 250.0, 172.5).is_empty()); + s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 172.5), plain).unwrap(); + s.drop_tool_press(plain).unwrap(); + assert!(s.overlays(plain).iter().all(|o| !matches!(o, vectorcraft_engine::tools::Overlay::Line { .. })), "{:?}", s.overlays(plain)); + // Alignment Guides off: the line still lands on the level, with no guide. + let (mut s, _) = level_start(plain); + run(&mut s, "prefs.set", json!({"key": "alignmentGuides", "value": false})); + linear_click(&mut s, plain, 200.0, 200.0); + linear_click(&mut s, plain, 300.0, 200.0); + assert!(guide_lines(&mut s, plain, 250.0, 172.5).is_empty()); + linear_click(&mut s, plain, 250.0, 172.5); + let id = s.doc().unwrap().selection.objects[0].0; + assert_eq!(recipe(&s, id).line_ends(), (pt(200.0, 170.0), pt(300.0, 170.0))); +} + +/// A second dimension of the same two points as a dimension already drawn lands on its level too. +/// Off every level, a pointer moved in small steps while it is placed puts the line at each step, +/// with no pull from the preview of the dimension itself. +#[test] +fn a_dimension_of_the_same_points_lines_up_and_the_line_follows_the_pointer() { + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + let (mut s, first) = level_start(plain); + linear_click(&mut s, plain, 100.0, 200.0); + linear_click(&mut s, plain, 200.0, 200.0); + linear_click(&mut s, plain, 150.0, 172.5); + let id = s.doc().unwrap().selection.objects[0].0; + assert_ne!(id, first); + assert_eq!(recipe(&s, id).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0))); + let (mut s, _) = level_start(plain); + linear_click(&mut s, plain, 200.0, 200.0); + linear_click(&mut s, plain, 300.0, 200.0); + for y in [190.0, 189.0, 188.0, 187.0, 186.0] { + s.pointer(&PointerEvent::new(PointerKind::Move, 250.0, y), plain).unwrap(); + } + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 250.0, 186.0), plain).unwrap(); + } + let id = s.doc().unwrap().selection.objects[0].0; + assert_eq!(recipe(&s, id).line_ends(), (pt(200.0, 186.0), pt(300.0, 186.0))); +} + +/// A command that moves or hides a dimension while another is placed (Real-time Drawing on) does +/// not leave the placed dimension on a level the committed document does not have: committed with +/// its line near the other dimension's line as the document has it then, it is on that level, and +/// otherwise at the pointer. +#[test] +fn a_dimension_placed_after_a_command_lines_up_with_the_committed_document() { + let plain = ViewInfo::default(); + for (cmd, params, y) in [("dimension.update", json!({"offset": -10.0}), 192.0), ("object.hide", json!({}), 172.0)] { + let (mut s, first) = level_start(plain); + run(&mut s, "prefs.set", json!({"key": "realTimeDrawing", "value": true})); + // The bottom edge dragged out onto the level of the first line. + for (kind, y) in [(PointerKind::Move, 300.0), (PointerKind::Down, 300.0), (PointerKind::Drag, 240.0), (PointerKind::Drag, 172.0)] { + s.pointer(&PointerEvent::new(kind, 160.0, y), plain).unwrap(); + } + let mut params = params; + params["ids"] = json!([first]); + run(&mut s, cmd, params); + if cmd == "dimension.update" { + assert_eq!(recipe(&s, first).line_ends().0.y, 190.0, "moved before the release"); + } + // Released without a drag in between: the release places the dimension. + s.pointer(&PointerEvent::new(PointerKind::Up, 160.0, y), plain).unwrap(); + let placed = s.doc().unwrap().selection.objects[0].0; + assert_ne!(placed, first, "{cmd}: a new dimension"); + let reference = s.doc().unwrap().doc.node(NodeId(first)).map(|n| (n.visible, recipe(&s, first).line_ends().0.y)); + let expected = match reference { + Some((true, level)) if (level - y).abs() <= 4.0 => level, + _ => y, + }; + assert_eq!(recipe(&s, placed).line_ends().0.y, expected, "{cmd}: the other dimension is {reference:?}"); + } +} + +/// A dimension dragged out from a segment, with its line within the Smart Guides snapping +/// tolerance of the level of another dimension's parallel line, lands on that level. +#[test] +fn a_dimension_dragged_out_beside_another_lands_on_its_level() { + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + // The bottom edge dragged out to 2 points below the level of the first line, 130 points + // above the edge: on the level. + let (mut s, _) = level_start(plain); + for (kind, y) in + [(PointerKind::Move, 300.0), (PointerKind::Down, 300.0), (PointerKind::Drag, 240.0), (PointerKind::Drag, 172.0), (PointerKind::Up, 172.0)] + { + s.pointer(&PointerEvent::new(kind, 160.0, y), plain).unwrap(); + } + let id = s.doc().unwrap().selection.objects[0].0; + let (a, b) = recipe(&s, id).line_ends(); + assert!(near(a, pt(300.0, 170.0)) && near(b, pt(100.0, 170.0)) || near(a, pt(100.0, 170.0)) && near(b, pt(300.0, 170.0)), "{a:?} {b:?}"); +} + /// The page content streams of exported PDF `v`, inflated. fn pdf_content(v: &Value) -> String { let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 9227ee199d..836190aca6 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -9,6 +9,7 @@ mod text_fixture; mod affinity_features; mod affinity_local; +mod align_automatic_reference; mod artboard_click; mod beyond_canvas; mod clear_commands; @@ -27,6 +28,7 @@ mod param_keys; mod paste_many; mod pen_click_after_smooth; mod pen_endpoint_picking; +mod pen_rubber_band; mod ruler_guide_nodes; mod ruler_guide_perf; mod ruler_origin; diff --git a/crates/engine/tests/it/pen_rubber_band.rs b/crates/engine/tests/it/pen_rubber_band.rs new file mode 100644 index 0000000000..4d97f1c06b --- /dev/null +++ b/crates/engine/tests/it/pen_rubber_band.rs @@ -0,0 +1,264 @@ +//! The Pen's rubber band after a smooth anchor is the segment the next click adds: a new corner, +//! a close on the first anchor, or a join with an end of another open path. + +use serde_json::json; +use vectorcraft_doc::NodeKind; +use vectorcraft_engine::{Session, ViewInfo}; +use vectorcraft_geom::{CubicBez, PathData, PathEl, Point}; +use vectorcraft_tools::{Overlay, PointerEvent, PointerKind}; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn view() -> ViewInfo { + ViewInfo { zoom: 1.0, smart_guides: false, snap_to_grid: false, snap_to_pixel: false, snap_to_point: false, ..Default::default() } +} + +fn at(s: &mut Session, v: ViewInfo, kind: PointerKind, p: Point) { + s.pointer(&PointerEvent::new(kind, p.x, p.y), v).unwrap(); +} + +/// A press at `p` dragged to `out`: a smooth anchor with its outgoing handle at `out`. +fn smooth(s: &mut Session, v: ViewInfo, p: Point, out: Point) { + at(s, v, PointerKind::Down, p); + at(s, v, PointerKind::Drag, out); + at(s, v, PointerKind::Up, out); +} + +fn click(s: &mut Session, v: ViewInfo, p: Point) { + at(s, v, PointerKind::Down, p); + at(s, v, PointerKind::Up, p); +} + +/// The rubber band shown with the pointer hovering at `h`, as one cubic segment. +fn band(s: &mut Session, v: ViewInfo, h: Point) -> CubicBez { + at(s, v, PointerKind::Move, h); + let paths: Vec> = + s.overlays(v).into_iter().filter_map(|o| if let Overlay::Path { path, .. } = o { Some(path.elements().to_vec()) } else { None }).collect(); + match paths.as_slice() { + [els] => match els.as_slice() { + [PathEl::MoveTo(p0), PathEl::CurveTo(p1, p2, p3)] => CubicBez::new(*p0, *p1, *p2, *p3), + other => panic!("the rubber band is one curve, got {other:?}"), + }, + other => panic!("one rubber band, got {other:?}"), + } +} + +/// How many rubber bands show with the pointer hovering at `h` with Alt held as `alt` says. +fn bands(s: &mut Session, v: ViewInfo, h: Point, alt: bool) -> usize { + let mut ev = PointerEvent::new(PointerKind::Move, h.x, h.y); + ev.mods.alt = alt; + s.pointer(&ev, v).unwrap(); + s.overlays(v).into_iter().filter(|o| matches!(o, Overlay::Path { .. })).count() +} + +/// The measurement label shown with the pointer hovering at `h`. +fn label(s: &mut Session, v: ViewInfo, h: Point) -> String { + at(s, v, PointerKind::Move, h); + let labels: Vec = + s.overlays(v).into_iter().filter_map(|o| if let Overlay::Measure { text, .. } = o { Some(text) } else { None }).collect(); + match labels.as_slice() { + [text] => text.clone(), + other => panic!("one measurement label, got {other:?}"), + } +} + +fn paths(s: &Session) -> Vec { + let mut v = vec![]; + s.doc().unwrap().doc.walk(|n| { + if let NodeKind::Path { path, .. } = &n.kind { + v.push(path.clone()); + } + }); + v +} + +/// An open path whose first anchor, at `end`, is smooth with its incoming handle at `h_in`. +fn smooth_ended_path(s: &mut Session, end: Point, h_in: Point, other: Point) { + s.execute( + "path.create", + &json!({"anchors": [{"x": end.x, "y": end.y, "in": [h_in.x, h_in.y], "out": [2.0 * end.x - h_in.x, 2.0 * end.y - h_in.y]}, {"x": other.x, "y": other.y}]}), + ) + .unwrap(); + s.execute("select.none", &json!({})).unwrap(); +} + +#[test] +fn rubber_band_is_the_corner_a_click_adds() { + let (mut s, v) = (session(), view()); + s.select_tool("pen", v).unwrap(); + smooth(&mut s, v, Point::new(100.0, 100.0), Point::new(150.0, 60.0)); + let h = Point::new(300.0, 200.0); + let preview = band(&mut s, v, h); + click(&mut s, v, h); + let [path] = paths(&s).try_into().unwrap(); + assert_eq!(path.subpaths[0].segment(0), preview); +} + +#[test] +fn rubber_band_on_the_first_anchor_is_the_closing_segment() { + let (mut s, v) = (session(), view()); + s.select_tool("pen", v).unwrap(); + let first = Point::new(100.0, 100.0); + smooth(&mut s, v, first, Point::new(150.0, 60.0)); + click(&mut s, v, Point::new(300.0, 100.0)); + smooth(&mut s, v, Point::new(300.0, 300.0), Point::new(350.0, 340.0)); + // Within the pick tolerance of the first anchor: the band ends on the anchor, not the pointer. + let preview = band(&mut s, v, Point::new(102.0, 101.0)); + assert_eq!(preview.p3, first); + click(&mut s, v, Point::new(102.0, 101.0)); + let [path] = paths(&s).try_into().unwrap(); + let sp = &path.subpaths[0]; + assert!(sp.closed); + assert_eq!(sp.segment(2), preview); +} + +#[test] +fn rubber_band_on_another_paths_end_is_the_joining_segment() { + let (mut s, v) = (session(), view()); + let end = Point::new(400.0, 300.0); + smooth_ended_path(&mut s, end, Point::new(430.0, 250.0), Point::new(500.0, 300.0)); + s.select_tool("pen", v).unwrap(); + smooth(&mut s, v, Point::new(100.0, 100.0), Point::new(150.0, 60.0)); + let preview = band(&mut s, v, Point::new(402.0, 301.0)); + assert_eq!((preview.p2, preview.p3), (Point::new(430.0, 250.0), end)); + click(&mut s, v, Point::new(402.0, 301.0)); + let [path] = paths(&s).try_into().unwrap(); + assert_eq!(path.subpaths[0].anchors.len(), 3); + assert_eq!(path.subpaths[0].segment(0), preview); +} + +#[test] +fn rubber_band_picks_the_end_at_the_pointer_before_grid_snapping() { + let mut s = session(); + let mut prefs = s.prefs.clone(); + prefs.gridline_every = 100.0; + prefs.grid_subdivisions = 1; + s.apply_prefs(prefs); + let v = ViewInfo { snap_to_grid: true, ..view() }; + // The end is off the grid: the pointer next to it snaps to (100, 300), out of its pick tolerance, + // and a press there still joins at the pointer. + let end = Point::new(63.0, 303.0); + smooth_ended_path(&mut s, end, Point::new(90.0, 250.0), Point::new(13.0, 303.0)); + s.select_tool("pen", v).unwrap(); + smooth(&mut s, v, Point::new(300.0, 500.0), Point::new(350.0, 450.0)); + let pointer = Point::new(64.0, 303.0); + let preview = band(&mut s, v, pointer); + assert_eq!((preview.p2, preview.p3), (Point::new(90.0, 250.0), end)); + click(&mut s, v, pointer); + let [path] = paths(&s).try_into().unwrap(); + assert_eq!(path.subpaths[0].anchors.len(), 3); + assert_eq!(path.subpaths[0].segment(0), preview); +} + +#[test] +fn rubber_band_joins_an_end_the_grid_snaps_to_from_a_corner() { + let mut s = session(); + let mut prefs = s.prefs.clone(); + prefs.gridline_every = 100.0; + prefs.grid_subdivisions = 1; + s.apply_prefs(prefs); + let v = ViewInfo { snap_to_grid: true, ..view() }; + // The end is on the grid and the pointer is out of its pick tolerance: only the snapped point + // joins. The path ends on a corner, so only the end's own handle makes the segment a curve. + let end = Point::new(100.0, 300.0); + smooth_ended_path(&mut s, end, Point::new(130.0, 250.0), Point::new(13.0, 300.0)); + s.select_tool("pen", v).unwrap(); + click(&mut s, v, Point::new(300.0, 500.0)); + let pointer = Point::new(88.0, 300.0); + let preview = band(&mut s, v, pointer); + assert_eq!((preview.p1, preview.p2, preview.p3), (Point::new(300.0, 500.0), Point::new(130.0, 250.0), end)); + click(&mut s, v, pointer); + let [path] = paths(&s).try_into().unwrap(); + assert_eq!(path.subpaths[0].anchors.len(), 3); + assert_eq!(path.subpaths[0].segment(0), preview); +} + +#[test] +fn measurement_label_measures_the_segment_a_click_adds() { + let mut s = session(); + let mut prefs = s.prefs.clone(); + prefs.gridline_every = 100.0; + prefs.grid_subdivisions = 1; + s.apply_prefs(prefs); + let grid = ViewInfo { snap_to_grid: true, ..view() }; + let end = Point::new(63.0, 303.0); + smooth_ended_path(&mut s, end, Point::new(90.0, 250.0), Point::new(13.0, 303.0)); + s.select_tool("pen", grid).unwrap(); + smooth(&mut s, grid, Point::new(300.0, 500.0), Point::new(350.0, 450.0)); + // The pointer snaps to (100, 300), and the click joins at the end: the label measures to the end. + let joining = label(&mut s, grid, Point::new(64.0, 303.0)); + assert_eq!(joining, label(&mut s, view(), end)); +} + +#[test] +fn no_rubber_band_over_the_last_anchor() { + let (mut s, v) = (session(), view()); + s.select_tool("pen", v).unwrap(); + smooth(&mut s, v, Point::new(100.0, 100.0), Point::new(150.0, 60.0)); + smooth(&mut s, v, Point::new(300.0, 300.0), Point::new(350.0, 340.0)); + // A click there retracts the last anchor's outgoing handle and adds no segment. + let h = Point::new(303.0, 300.0); + assert_eq!(bands(&mut s, v, h, false), 0); + click(&mut s, v, h); + let [path] = paths(&s).try_into().unwrap(); + assert_eq!(path.subpaths[0].anchors.len(), 2); +} + +#[test] +fn no_rubber_band_where_alt_converts_an_anchor() { + let (mut s, v) = (session(), view()); + // Another path, in front, starts on an inner anchor of the path being drawn. + let shared = Point::new(300.0, 100.0); + let drawn = s + .execute( + "path.create", + &json!({"anchors": [{"x": 100.0, "y": 100.0, "out": [150.0, 60.0]}, {"x": shared.x, "y": shared.y}, {"x": 300.0, "y": 300.0, "in": [250.0, 260.0], "out": [350.0, 340.0]}]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(); + smooth_ended_path(&mut s, shared, Point::new(330.0, 50.0), Point::new(400.0, 50.0)); + s.execute("select.set", &json!({"ids": [drawn]})).unwrap(); + s.select_tool("pen", v).unwrap(); + // A click on the last anchor goes on drawing the path. + click(&mut s, v, Point::new(300.0, 300.0)); + let paths_before = paths(&s).len(); + let h = Point::new(301.0, 100.0); + assert_eq!(band(&mut s, v, h).p3, shared); + // With Alt the click hands the anchor under the pointer to the Anchor Point tool and joins nothing. + assert_eq!(bands(&mut s, v, h, true), 0); + let mut down = PointerEvent::new(PointerKind::Down, h.x, h.y); + down.mods.alt = true; + s.pointer(&down, v).unwrap(); + let mut up = PointerEvent::new(PointerKind::Up, h.x, h.y); + up.mods.alt = true; + s.pointer(&up, v).unwrap(); + assert_eq!(paths(&s).len(), paths_before); +} + +#[test] +fn no_rubber_band_where_a_join_merges_the_ends() { + let (mut s, v) = (session(), view()); + // Another path's end lies less than the join's merge distance from where this path ends. + let drawn = s + .execute("path.create", &json!({"anchors": [{"x": 100.0, "y": 100.0, "out": [150.0, 60.0]}, {"x": 300.0, "y": 300.0, "in": [250.0, 260.0], "out": [350.0, 340.0]}]})) + .unwrap()["id"] + .as_u64() + .unwrap(); + smooth_ended_path(&mut s, Point::new(300.000_000_9, 300.0), Point::new(330.0, 250.0), Point::new(400.0, 300.0)); + s.execute("select.set", &json!({"ids": [drawn]})).unwrap(); + s.select_tool("pen", v).unwrap(); + // A click on the last anchor goes on drawing the path. + click(&mut s, v, Point::new(300.0, 300.0)); + // Just out of the pick tolerance of the last anchor and in it of the other end: the click + // merges the two ends into one anchor and adds no segment. + let h = Point::new(305.000_000_5, 300.0); + assert_eq!(bands(&mut s, v, h, false), 0); + click(&mut s, v, h); + let [path] = paths(&s).try_into().unwrap(); + assert_eq!(path.subpaths[0].anchors.len(), 3); +} diff --git a/crates/engine/tests/pen_space_handle.rs b/crates/engine/tests/pen_space_handle.rs new file mode 100644 index 0000000000..5e37ca8a11 --- /dev/null +++ b/crates/engine/tests/pen_space_handle.rs @@ -0,0 +1,404 @@ +//! Pen lends Direct Selection for one handle gesture; Space repositions that handle's owner. +// Integration tests may unwrap and panic (AGENTS.md, Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use serde_json::json; +use vectorcraft_doc::NodeId; +use vectorcraft_engine::{Session, ViewInfo}; +use vectorcraft_geom::{Anchor, AnchorKind, PathData, Point}; +use vectorcraft_tools::{Cursor, Mods, PointerEvent, PointerKind, ToolKey}; + +fn view() -> ViewInfo { + ViewInfo { + zoom: 1.0, + smart_guides: false, + guides: false, + snap_to_grid: false, + snap_to_pixel: false, + snap_to_point: false, + snap_to_glyph: false, + pixel_preview: false, + ..Default::default() + } +} + +fn command(space: bool) -> Mods { + Mods { cmd: true, space, ..Default::default() } +} + +fn pointer(s: &mut Session, kind: PointerKind, at: (f64, f64), mods: Mods) { + s.pointer(&PointerEvent::new(kind, at.0, at.1).with_mods(mods), view()).unwrap(); +} + +fn path(s: &Session, id: NodeId) -> PathData { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone() +} + +fn history(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn open_pen_path() -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s.prefs.selection_tolerance = 8.0; + s.prefs.use_precise_cursors = false; + // Choose the tool the Pen will lend before beginning its path. + s.select_tool("directSelection", view()).unwrap(); + s.select_tool("pen", view()).unwrap(); + let none = Mods::default(); + pointer(&mut s, PointerKind::Down, (100.0, 300.0), none); + pointer(&mut s, PointerKind::Up, (100.0, 300.0), none); + pointer(&mut s, PointerKind::Down, (200.0, 300.0), none); + pointer(&mut s, PointerKind::Drag, (250.0, 300.0), none); + pointer(&mut s, PointerKind::Up, (250.0, 300.0), none); + let id = s.doc().unwrap().selection.objects[0]; + let p = path(&s, id); + assert_eq!(p.subpaths.len(), 1); + assert!(!p.subpaths[0].closed); + assert_eq!(p.subpaths[0].anchors.len(), 2); + let a = p.subpaths[0].anchors[1]; + assert_eq!((a.p, a.h_in, a.h_out, a.kind), (Point::new(200.0, 300.0), Point::new(150.0, 300.0), Point::new(250.0, 300.0), AnchorKind::Smooth)); + assert_eq!(s.tool_id(), "pen"); + assert_eq!(s.cursor(a.h_out, command(false), view()), Cursor::ArrowHollow); + (s, id) +} + +fn assert_anchor(s: &Session, id: NodeId, first: Anchor, owner: (f64, f64), inside: (f64, f64), outside: (f64, f64)) { + let p = path(s, id); + assert_eq!(p.subpaths.len(), 1); + assert!(!p.subpaths[0].closed); + assert_eq!(p.subpaths[0].anchors.len(), 2); + assert_eq!(p.subpaths[0].anchors[0], first, "the other anchor and its handles stay unchanged"); + let a = p.subpaths[0].anchors[1]; + assert_eq!(a.kind, AnchorKind::Smooth); + for (label, actual, expected) in [ + ("owner", a.p, Point::new(owner.0, owner.1)), + ("in handle", a.h_in, Point::new(inside.0, inside.1)), + ("out handle", a.h_out, Point::new(outside.0, outside.1)), + ] { + assert!(actual.distance(expected) < 1e-6, "{label}: expected {expected:?}, got {actual:?}"); + } +} + +/// Do not insert a zero-motion Space-on event: the first motion must use the previous pointer. +fn borrowed_space_drag(s: &mut Session, id: NodeId) { + let first = path(s, id).subpaths[0].anchors[0]; + pointer(s, PointerKind::Down, (250.0, 300.0), command(false)); + assert_eq!(s.tool_id(), "directSelection"); + assert!(s.in_interaction()); + pointer(s, PointerKind::Drag, (260.0, 300.0), command(false)); + assert_anchor(s, id, first, (200.0, 300.0), (150.0, 300.0), (260.0, 300.0)); + pointer(s, PointerKind::Drag, (280.0, 310.0), command(true)); + assert_anchor(s, id, first, (220.0, 310.0), (170.0, 310.0), (280.0, 310.0)); + // Releasing Space while the button stays down neither jumps nor commits the gesture. + pointer(s, PointerKind::Drag, (280.0, 310.0), command(false)); + assert_anchor(s, id, first, (220.0, 310.0), (170.0, 310.0), (280.0, 310.0)); + pointer(s, PointerKind::Drag, (300.0, 310.0), command(false)); + assert_anchor(s, id, first, (220.0, 310.0), (170.0, 310.0), (300.0, 310.0)); + pointer(s, PointerKind::Drag, (290.0, 325.0), command(true)); + assert_anchor(s, id, first, (210.0, 325.0), (160.0, 325.0), (290.0, 325.0)); + pointer(s, PointerKind::Drag, (290.0, 325.0), command(false)); + assert_anchor(s, id, first, (210.0, 325.0), (160.0, 325.0), (290.0, 325.0)); + pointer(s, PointerKind::Drag, (310.0, 325.0), command(false)); + assert_anchor(s, id, first, (210.0, 325.0), (160.0, 325.0), (310.0, 325.0)); + assert_eq!(s.tool_id(), "directSelection"); + assert!(s.in_interaction()); +} + +#[test] +fn pen_space_first_motion_repeated_toggle_and_pen_continuation() { + let (mut s, id) = open_pen_path(); + let before = history(&s); + borrowed_space_drag(&mut s, id); + pointer(&mut s, PointerKind::Up, (310.0, 325.0), command(false)); + assert_eq!(s.tool_id(), "pen"); + assert!(!s.in_interaction()); + assert_eq!(history(&s), before + 1, "one completed handle gesture"); + let moved = path(&s, id).subpaths[0].anchors[1]; + pointer(&mut s, PointerKind::Down, (350.0, 380.0), Mods::default()); + pointer(&mut s, PointerKind::Up, (350.0, 380.0), Mods::default()); + let p = path(&s, id); + assert_eq!(p.subpaths[0].anchors.len(), 3, "the Pen continues the same path after its loan"); + assert_eq!(p.subpaths[0].anchors[1], moved); + assert_eq!(p.subpaths[0].anchors[2].p, Point::new(350.0, 380.0)); + assert_eq!(s.doc().unwrap().selection.objects, [id]); + let mut count = 0; + s.doc().unwrap().doc.walk(|node| count += usize::from(node.path_data().is_some())); + assert_eq!(count, 1, "continuation creates no second path"); + assert_eq!(history(&s), before + 2, "the new Pen anchor is its own step"); +} + +#[test] +fn pen_space_no_space_handle_drag_preserves_owner() { + let (mut s, id) = open_pen_path(); + let first = path(&s, id).subpaths[0].anchors[0]; + let before = history(&s); + pointer(&mut s, PointerKind::Down, (250.0, 300.0), command(false)); + assert_eq!(s.tool_id(), "directSelection"); + pointer(&mut s, PointerKind::Drag, (260.0, 300.0), command(false)); + pointer(&mut s, PointerKind::Up, (260.0, 300.0), command(false)); + assert_anchor(&s, id, first, (200.0, 300.0), (150.0, 300.0), (260.0, 300.0)); + assert_eq!(s.tool_id(), "pen"); + assert!(!s.in_interaction()); + assert_eq!(history(&s), before + 1); +} + +#[test] +fn pen_space_handle_drag_undo_redo_is_one_step() { + let (mut s, id) = open_pen_path(); + let original = path(&s, id); + let before = history(&s); + borrowed_space_drag(&mut s, id); + pointer(&mut s, PointerKind::Up, (310.0, 325.0), command(false)); + let changed = path(&s, id); + assert_eq!(history(&s), before + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&s, id), original); + assert_eq!(history(&s), before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(path(&s, id), changed); + assert_eq!(history(&s), before + 1); +} + +#[test] +fn pen_space_escape_restores_entire_borrowed_gesture() { + let (mut s, id) = open_pen_path(); + let original = path(&s, id); + let before = history(&s); + borrowed_space_drag(&mut s, id); + s.tool_key(ToolKey::Escape, command(false), view()).unwrap(); + assert_eq!(path(&s, id), original, "cancel restores pre-borrow geometry, not just the latest Space phase"); + assert_eq!(history(&s), before); + assert!(!s.in_interaction()); + // Up releases the borrowed selection tool; Escape itself need not return the lender. + pointer(&mut s, PointerKind::Up, (310.0, 325.0), command(false)); + assert_eq!(s.tool_id(), "pen"); + assert_eq!(path(&s, id), original); + assert_eq!(history(&s), before); +} + +#[test] +fn pen_space_type_on_path_without_space_stays_text() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let source = s + .execute("path.create", &json!({"anchors": [{"x": 100, "y": 300, "in": [50, 300], "out": [150, 300]}, {"x": 400, "y": 300}]})) + .unwrap()["id"] + .clone(); + let id = NodeId( + s.execute("text.createInPath", &json!({"path": source, "mode": "onPath", "text": "Along", "size": 12})).unwrap()["id"].as_u64().unwrap(), + ); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.select_tool("directSelection", view()).unwrap(); + let text_path = |s: &Session| match &s.doc().unwrap().doc.node(id).unwrap().kind { + vectorcraft_doc::NodeKind::Text(text) => { + assert_eq!(text.plain_text(), "Along"); + text.type_path().expect("the object remains type on a path") + } + kind => panic!("the object must remain text, got {kind:?}"), + }; + let original = text_path(&s); + let before = history(&s); + pointer(&mut s, PointerKind::Down, (150.0, 300.0), Mods::default()); + pointer(&mut s, PointerKind::Drag, (160.0, 280.0), Mods::default()); + pointer(&mut s, PointerKind::Up, (160.0, 280.0), Mods::default()); + let changed = text_path(&s); + let a = changed.subpaths[0].anchors[0]; + assert_eq!(a.p, original.subpaths[0].anchors[0].p); + assert_eq!(a.h_out, Point::new(160.0, 280.0)); + assert_eq!(a.kind, AnchorKind::Smooth); + let original_anchor = original.subpaths[0].anchors[0]; + let opposite = a.p + (a.p - a.h_out) * (original_anchor.h_in.distance(original_anchor.p) / a.h_out.distance(a.p)); + assert!(a.h_in.distance(opposite) < 1e-6, "the ordinary smooth type-path handle keeps its opposite handle's length and direction: {a:?}"); + assert_eq!(changed.subpaths[0].anchors[1], original.subpaths[0].anchors[1]); + assert_eq!(history(&s), before + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(text_path(&s), original); +} + +#[test] +fn pen_space_after_alt_drag_keeps_corner_and_opposite_handle_offset() { + let (mut s, id) = open_pen_path(); + let first = path(&s, id).subpaths[0].anchors[0]; + let before = history(&s); + pointer(&mut s, PointerKind::Down, (250.0, 300.0), command(false)); + let alt = Mods { alt: true, ..command(false) }; + pointer(&mut s, PointerKind::Drag, (260.0, 280.0), alt); + let a = path(&s, id).subpaths[0].anchors[1]; + assert_eq!((a.kind, a.p, a.h_in, a.h_out), (AnchorKind::Corner, Point::new(200.0, 300.0), Point::new(150.0, 300.0), Point::new(260.0, 280.0))); + let space = Mods { space: true, ..alt }; + pointer(&mut s, PointerKind::Drag, (280.0, 290.0), space); + let moved = path(&s, id).subpaths[0].anchors[1]; + assert_eq!( + (moved.kind, moved.p, moved.h_in, moved.h_out), + (AnchorKind::Corner, Point::new(220.0, 310.0), Point::new(170.0, 310.0), Point::new(280.0, 290.0)) + ); + pointer(&mut s, PointerKind::Drag, (280.0, 290.0), alt); + assert_eq!(path(&s, id).subpaths[0].anchors[1], moved, "releasing Space does not restore Smooth or move the independent opposite handle"); + pointer(&mut s, PointerKind::Up, (280.0, 290.0), alt); + assert_eq!(path(&s, id).subpaths[0].anchors[0], first); + assert_eq!(s.tool_id(), "pen"); + assert_eq!(history(&s), before + 1); +} + +#[test] +fn pen_space_after_shift_uses_the_accepted_handle_without_a_release_jump() { + let (mut s, id) = open_pen_path(); + pointer(&mut s, PointerKind::Down, (250.0, 300.0), command(false)); + let shift = Mods { shift: true, ..command(false) }; + pointer(&mut s, PointerKind::Drag, (260.0, 320.0), shift); + let accepted = path(&s, id).subpaths[0].anchors[1]; + assert!(accepted.h_out.distance(Point::new(260.0, 320.0)) > 1.0, "Shift accepts a constrained handle, not the raw pointer"); + pointer(&mut s, PointerKind::Drag, (280.0, 330.0), Mods { space: true, ..shift }); + let delta = vectorcraft_geom::Vec2::new(20.0, 10.0); + let moved = path(&s, id).subpaths[0].anchors[1]; + assert_eq!(moved.kind, accepted.kind); + for (actual, expected) in [(moved.p, accepted.p + delta), (moved.h_in, accepted.h_in + delta), (moved.h_out, accepted.h_out + delta)] { + assert!(actual.distance(expected) < 1e-6, "Space translates the accepted constrained handles: {moved:?}"); + } + pointer(&mut s, PointerKind::Drag, (280.0, 330.0), shift); + let released = path(&s, id).subpaths[0].anchors[1]; + assert!( + released.p.distance(moved.p) < 1e-6 && released.h_in.distance(moved.h_in) < 1e-6 && released.h_out.distance(moved.h_out) < 1e-6, + "same-position Space release preserves the accepted constrained handle: {moved:?} -> {released:?}" + ); + pointer(&mut s, PointerKind::Up, (280.0, 330.0), shift); + assert_eq!(s.tool_id(), "pen"); +} + +#[test] +fn pen_space_set_handle_at_keeps_corner_and_unrelated_fractional_geometry() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let id = NodeId( + s.execute( + "path.create", + &json!({"anchors": [ + {"x": 100.25, "y": 100.5, "out": [130.75, 140.25]}, + {"x": 200, "y": 200, "in": [150, 200], "out": [250, 200]}, + {"x": 300.4, "y": 275.6, "in": [270.3, 280.2]} + ]}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + // Both segments are curved; Align to Pixel Grid retains the unrelated fractional geometry. + s.execute("object.setPixelAligned", &json!({"ids": [id.0], "on": true})).unwrap(); + s.execute("path.setHandle", &json!({"id": id.0, "anchor": 1, "which": "out", "x": 250, "y": 200, "independent": true})).unwrap(); + let original = path(&s, id); + assert!(s.doc().unwrap().doc.node(id).unwrap().extras().pixel_aligned); + assert_eq!(original.subpaths[0].anchors[1].kind, AnchorKind::Corner); + assert_eq!(original.subpaths[0].anchors[0].p, Point::new(100.25, 100.5)); + let before = history(&s); + // Omitted at preserves the existing no-op contract and the collinear Corner kind. + s.execute("path.setHandle", &json!({"id": id.0, "anchor": 1, "which": "out", "x": 250, "y": 200})).unwrap(); + assert_eq!(path(&s, id), original); + assert_eq!(history(&s), before); + s.execute("path.setHandle", &json!({"id": id.0, "anchor": 1, "which": "out", "at": [210.25, 205.5], "x": 260.25, "y": 205.5})).unwrap(); + let changed = path(&s, id); + let a = changed.subpaths[0].anchors[1]; + assert_eq!((a.kind, a.p, a.h_in, a.h_out), (AnchorKind::Corner, Point::new(210.25, 205.5), Point::new(160.25, 205.5), Point::new(260.25, 205.5))); + assert_eq!(changed.subpaths[0].anchors[0], original.subpaths[0].anchors[0]); + assert_eq!(changed.subpaths[0].anchors[2], original.subpaths[0].anchors[2]); + assert!(s.doc().unwrap().doc.node(id).unwrap().extras().pixel_aligned); + assert_eq!(history(&s), before + 1); + let node = s.doc().unwrap().doc.node(id).unwrap().clone(); + let before_bad = history(&s); + assert!(s.execute("path.setHandle", &json!({"id": id.0, "anchor": 1, "which": "out", "at": [220], "x": 270, "y": 210})).is_err()); + assert_eq!(s.doc().unwrap().doc.node(id).unwrap(), &node, "an invalid owner point does not apply the handle change first"); + assert_eq!(history(&s), before_bad); +} +fn noncollinear_smooth_path() -> (Session, NodeId) { + let (mut s, id) = open_pen_path(); + // Native files may retain a Smooth kind whose two stored handles are not collinear. + let data = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().path_data_mut().unwrap(); + data.subpaths[0].anchors[1].h_in = Point::new(200.0, 350.0); + assert_eq!(data.subpaths[0].anchors[1].kind, AnchorKind::Smooth); + (s, id) +} + +fn assert_noncollinear_space_translation(out: bool) { + let (mut s, id) = noncollinear_smooth_path(); + let original = path(&s, id); + let a = original.subpaths[0].anchors[1]; + let selected = if out { a.h_out } else { a.h_in }; + let delta = vectorcraft_geom::Vec2::new(10.0, 0.0); + let target = selected + delta; + let before = history(&s); + pointer(&mut s, PointerKind::Down, (selected.x, selected.y), command(false)); + pointer(&mut s, PointerKind::Drag, (target.x, target.y), command(true)); + let moved = path(&s, id).subpaths[0].anchors[1]; + assert_eq!(moved.kind, a.kind); + assert_eq!((moved.p, moved.h_in, moved.h_out), (a.p + delta, a.h_in + delta, a.h_out + delta), "Space preserves the loaded handle geometry"); + pointer(&mut s, PointerKind::Drag, (target.x, target.y), command(false)); + pointer(&mut s, PointerKind::Up, (target.x, target.y), command(false)); + let changed = path(&s, id); + assert_eq!(changed.subpaths[0].anchors[1], moved, "releasing Space at the same point does not reshape the anchor"); + assert_eq!(changed.subpaths[0].anchors[0], original.subpaths[0].anchors[0]); + assert_eq!(s.tool_id(), "pen"); + assert_eq!(history(&s), before + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&s, id), original); +} + +#[test] +fn pen_space_noncollinear_smooth_outgoing_handle_is_pure_translation() { + assert_noncollinear_space_translation(true); +} + +#[test] +fn pen_space_noncollinear_smooth_incoming_handle_is_pure_translation() { + assert_noncollinear_space_translation(false); +} + +#[test] +fn pen_space_noncollinear_existing_noop_and_independent_corner_controls() { + let (mut s, id) = noncollinear_smooth_path(); + let original = path(&s, id); + let a = original.subpaths[0].anchors[1]; + let before = history(&s); + for (which, h) in [("in", a.h_in), ("out", a.h_out)] { + s.execute("path.setHandle", &json!({"id":id.0,"anchor":1,"which":which,"x":h.x,"y":h.y})).unwrap(); + assert_eq!(path(&s, id), original); + assert_eq!(history(&s), before); + } + let delta = vectorcraft_geom::Vec2::new(10.0, 0.0); + let to = a.p + delta; + let h = a.h_out + delta; + s.execute("path.setHandle", &json!({"id":id.0,"anchor":1,"which":"out","at":[to.x,to.y],"x":h.x,"y":h.y,"independent":true})).unwrap(); + let moved = path(&s, id).subpaths[0].anchors[1]; + assert_eq!((moved.kind, moved.p, moved.h_in, moved.h_out), (AnchorKind::Corner, to, a.h_in + delta, h)); + assert_eq!(history(&s), before + 1, "an explicit independent edit still converts Smooth to Corner"); +} + +#[test] +fn pen_space_noncollinear_decimal_translation_keeps_shape_and_real_edits_work() { + let (mut s, id) = noncollinear_smooth_path(); + let a = Anchor { p: Point::new(0.2, 0.2), h_in: Point::new(50.0, 100.0), h_out: Point::new(0.1, 25.2), kind: AnchorKind::Smooth }; + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().path_data_mut().unwrap().subpaths[0].anchors[1] = a; + let original = path(&s, id); + let before = history(&s); + let delta = vectorcraft_geom::Vec2::new(0.1, 0.0); + let to = a.p + delta; + let handle = a.h_out + delta; + s.execute("path.setHandle", &json!({"id": id.0, "anchor": 1, "which": "out", "at": [to.x, to.y], "x": handle.x, "y": handle.y})).unwrap(); + let moved = path(&s, id).subpaths[0].anchors[1]; + assert_eq!( + (moved.kind, moved.p, moved.h_in, moved.h_out), + (a.kind, to, a.h_in + delta, handle), + "a decimal owner translation keeps the loaded shape and places the selected handle exactly" + ); + assert_eq!(history(&s), before + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&s, id), original); + // Moving the handle relative to its translated owner is still a Smooth handle edit. + let edited = handle + vectorcraft_geom::Vec2::new(3.0, 1.0); + s.execute("path.setHandle", &json!({"id": id.0, "anchor": 1, "which": "out", "at": [to.x, to.y], "x": edited.x, "y": edited.y})).unwrap(); + let moved = path(&s, id).subpaths[0].anchors[1]; + assert_eq!((moved.kind, moved.p, moved.h_out), (AnchorKind::Smooth, to, edited)); + let incoming = moved.h_in - moved.p; + let outgoing = moved.h_out - moved.p; + assert!(incoming.cross(outgoing).abs() < 1e-9 && incoming.dot(outgoing) < 0.0, "a real handle edit still aligns the opposite Smooth handle"); +} diff --git a/crates/engine/tests/preflight.rs b/crates/engine/tests/preflight.rs new file mode 100644 index 0000000000..08b7cf153b --- /dev/null +++ b/crates/engine/tests/preflight.rs @@ -0,0 +1,216 @@ +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +//! Production preflight must find actual delivery problems and clear them after repairs. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; +use vectorcraft_engine::Session; + +fn new() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({ "width": 500, "height": 400 })).unwrap(); + s +} + +fn check(s: &mut Session) -> Value { + s.execute("document.preflight", &json!({})).unwrap() +} + +fn codes(report: &Value) -> Vec<&str> { + report["findings"].as_array().unwrap().iter().map(|f| f["code"].as_str().unwrap()).collect() +} + +#[test] +fn preflight_finds_four_problems_and_repairs_clear_each_one() { + let dir = Folder::new("preflight-four"); + let path = dir.file("picture.png"); + let bytes = png(40, 40, [200, 50, 10]); + std::fs::write(&path, &bytes).unwrap(); + let mut s = new(); + let text = s.execute("text.create", &json!({ "x": 10, "y": 10, "text": "Ab\nCd\nEf\nGh", "font": "Preflight Missing Family 917", "size": 12, "area": { "width": 100, "height": 20 } })).unwrap()["id"].clone(); + let image = s.execute("file.place", &json!({ "path": path, "at": [200, 200], "link": true })).unwrap()["ids"][0].clone(); + std::fs::remove_file(&path).unwrap(); + let before_doc = s.doc().unwrap().doc.clone(); + let before_sel = s.doc().unwrap().selection.clone(); + let revision = s.doc().unwrap().revision; + let report = check(&mut s); + for code in ["missingFont", "overflow", "missingLink", "lowResolution"] { + assert!(codes(&report).contains(&code), "{code}: {report}"); + } + assert_eq!(*before_doc, *s.doc().unwrap().doc); + assert_eq!(before_sel, s.doc().unwrap().selection); + assert_eq!(revision, s.doc().unwrap().revision, "checking doesn't edit the document"); + for f in report["findings"].as_array().unwrap() { + assert!(f["ids"].as_array().unwrap().iter().all(|id| id == &text || id == &image), "{f}"); + } + s.execute("text.areaOptions", &json!({ "ids": [text], "height": 150 })).unwrap(); + assert!(!codes(&check(&mut s)).contains(&"overflow")); + std::fs::write(&path, &bytes).unwrap(); + s.execute("links.update", &json!({ "ids": [image] })).unwrap(); + assert!(!codes(&check(&mut s)).contains(&"missingLink")); + s.execute("select.set", &json!({ "ids": [image] })).unwrap(); + s.execute("object.setBounds", &json!({ "width": 7.2, "height": 7.2 })).unwrap(); + assert!(!codes(&check(&mut s)).contains(&"lowResolution")); + // Deleting the missing-font object fixes the final delivery issue on any machine, including + // builds with no optional craft-fonts checkout or installed fonts. + s.execute("select.set", &json!({ "ids": [text] })).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let clean = check(&mut s); + assert!(codes(&clean).is_empty(), "{clean}"); + assert!(clean["checks"].as_array().unwrap().iter().all(|c| c["status"] == "passed")); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(codes(&check(&mut s)).contains(&"missingFont"), "undo is checked too"); +} + +#[test] +fn preflight_reuses_link_probes_for_external_changes_without_an_edit() { + let dir = Folder::new("preflight-modified"); + let path = dir.file("picture.png"); + std::fs::write(&path, png(40, 40, [200, 50, 10])).unwrap(); + let mut s = new(); + let image = s.execute("file.place", &json!({ "path": path, "at": [200, 200] })).unwrap()["ids"][0].clone(); + let rev = s.doc().unwrap().revision; + std::fs::write(&path, png(41, 45, [10, 50, 200])).unwrap(); + assert!(codes(&check(&mut s)).contains(&"modifiedLink")); + assert_eq!(rev, s.doc().unwrap().revision); + s.execute("links.update", &json!({ "ids": [image] })).unwrap(); + assert!(!codes(&check(&mut s)).contains(&"modifiedLink")); +} + +#[test] +fn preflight_scopes_artboards_and_respects_hidden_and_nonprinting_layers() { + let mut s = new(); + let id = s.execute("text.create", &json!({ "x": 10, "y": 30, "text": "Label", "font": "Preflight Missing Scope 917" })).unwrap()["id"].clone(); + s.execute("artboard.new", &json!({ "x": 600, "y": 0, "width": 500, "height": 400 })).unwrap(); + let other = s.execute("document.preflight", &json!({ "artboards": [1] })).unwrap(); + assert!(codes(&other).is_empty(), "{other}"); + assert!(codes(&check(&mut s)).contains(&"missingFont")); + s.execute("object.setProps", &json!({ "ids": [id], "visible": false })).unwrap(); + assert!(codes(&check(&mut s)).is_empty()); + s.execute("object.setProps", &json!({ "ids": [id], "visible": true, "locked": true })).unwrap(); + assert!(codes(&check(&mut s)).contains(&"missingFont"), "locked artwork still exports"); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.setProps", &json!({ "id": layer.0, "printable": false })).unwrap(); + let print = s.execute("document.preflight", &json!({ "output": "print" })).unwrap(); + assert!(codes(&print).is_empty(), "{print}"); +} + +#[test] +fn preflight_resolution_follows_placed_size_and_both_axes() { + let dir = Folder::new("preflight-resolution"); + let path = dir.file("picture.png"); + std::fs::write(&path, png(100, 100, [200, 50, 10])).unwrap(); + let mut s = new(); + let id = s.execute("file.place", &json!({ "path": path, "link": false, "at": [200, 200] })).unwrap()["ids"][0].clone(); + s.execute("select.set", &json!({ "ids": [id] })).unwrap(); + s.execute("object.setBounds", &json!({ "width": 24, "height": 72 })).unwrap(); + let r = check(&mut s); + let f = r["findings"].as_array().unwrap().iter().find(|f| f["code"] == "lowResolution").unwrap(); + assert_eq!(f["effectivePpi"], json!([300.0, 100.0])); + let screen = s.execute("document.preflight", &json!({ "output": "screen" })).unwrap(); + assert_eq!(screen["minPpi"], 96.0); + assert!(codes(&screen).is_empty(), "{screen}"); +} + +#[test] +fn preflight_resolution_accepts_the_exact_threshold_but_rejects_a_real_shortfall() { + let dir = Folder::new("preflight-resolution-boundary"); + let path = dir.file("picture.png"); + std::fs::write(&path, png(40, 40, [200, 50, 10])).unwrap(); + let mut s = new(); + s.execute("file.place", &json!({ "path": path, "link": false, "at": [200, 200] })).unwrap(); + for threshold in [31.0, 59.0, 300.0, 600.0, 9600.0] { + let size = 40.0 * 72.0 / threshold; + s.execute("object.setBounds", &json!({ "width": size, "height": size })).unwrap(); + let exact = s.execute("document.preflight", &json!({ "minPpi": threshold })).unwrap(); + assert!(!codes(&exact).contains(&"lowResolution"), "exactly {threshold} ppi: {exact}"); + s.execute("object.setBounds", &json!({ "width": size * 1.000001, "height": size })).unwrap(); + let below = s.execute("document.preflight", &json!({ "minPpi": threshold })).unwrap(); + let f = below["findings"].as_array().unwrap().iter().find(|f| f["code"] == "lowResolution").unwrap(); + assert_eq!(f["threshold"], threshold); + } +} + +#[test] +fn preflight_resolution_includes_the_print_jobs_scale() { + let dir = Folder::new("preflight-print-scale"); + let path = dir.file("picture.png"); + std::fs::write(&path, png(100, 100, [200, 50, 10])).unwrap(); + let mut s = new(); + s.execute("file.place", &json!({ "path": path, "link": false, "at": [250, 200] })).unwrap(); + s.execute("object.setBounds", &json!({ "width": 24, "height": 24 })).unwrap(); + let doc = s.execute("document.preflight", &json!({ "minPpi": 200 })).unwrap(); + assert!(codes(&doc).is_empty(), "{doc}"); + s.execute("print.setup", &json!({ "settings": { "scaling": "custom", "scale": { "width": 200, "height": 200 } } })).unwrap(); + let print = s.execute("document.preflight", &json!({ "output": "print", "minPpi": 200 })).unwrap(); + let f = print["findings"].as_array().unwrap().iter().find(|f| f["code"] == "lowResolution").unwrap(); + assert_eq!(f["effectivePpi"], json!([150.0, 150.0])); +} + +#[test] +fn preflight_reports_a_frame_that_cannot_show_even_its_first_line() { + let mut s = new(); + let id = s.execute("text.create", &json!({ "x": 10, "y": 10, "text": "Abc", "size": 30, "area": { "width": 100, "height": 1 } })).unwrap()["id"] + .clone(); + let r = check(&mut s); + assert!(r["findings"].as_array().unwrap().iter().any(|f| f["code"] == "overflow" && f["ids"] == json!([id])), "{r}"); +} + +#[test] +fn preflight_reports_type_that_cannot_place_a_glyph_on_a_horizontal_path() { + let mut s = new(); + let path = s.execute("path.create", &json!({ "d": "M10 20 L11 20" })).unwrap()["id"].clone(); + let id = s.execute("text.createInPath", &json!({ "path": path, "mode": "onPath", "text": "Longer than the path" })).unwrap()["id"].clone(); + let r = check(&mut s); + assert!(r["findings"].as_array().unwrap().iter().any(|f| f["code"] == "overflow" && f["ids"] == json!([id])), "{r}"); +} + +#[test] +fn preflight_bad_options_leave_document_and_selection_unchanged() { + let mut s = new(); + let doc = s.doc().unwrap().doc.clone(); + for p in [ + json!({ "output": "unknown" }), + json!({ "output": 1 }), + json!({ "minPpi": 0 }), + json!({ "minPpi": "300" }), + json!({ "artboards": [] }), + json!({ "artboards": [0.5] }), + json!({ "artboards": [999] }), + ] { + assert!(s.execute("document.preflight", &p).is_err(), "{p}"); + assert_eq!(*doc, *s.doc().unwrap().doc); + } +} + +#[test] +fn preflight_resource_font_finding_locates_its_instance() { + let mut s = new(); + let text = s.execute("text.create", &json!({ "x": 10, "y": 30, "text": "Label", "font": "Preflight Missing Symbol 917" })).unwrap()["id"].clone(); + s.execute("select.set", &json!({ "ids": [text] })).unwrap(); + s.execute("symbol.new", &json!({ "name": "Label" })).unwrap(); + let r = check(&mut s); + let f = r["findings"].as_array().unwrap().iter().find(|f| f["code"] == "missingFont").unwrap(); + assert!(f["ids"].as_array().unwrap().iter().all(|id| s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).is_some()), "{r}"); +} + +struct Folder(std::path::PathBuf); +impl Folder { + fn new(name: &str) -> Self { + Self(vectorcraft_testkit::temp_dir(name)) + } + fn file(&self, name: &str) -> String { + self.0.join(name).to_string_lossy().into_owned() + } +} +impl Drop for Folder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} +fn png(w: u32, h: u32, rgb: [u8; 3]) -> Vec { + let pixels = (0..w * h).flat_map(|_| [rgb[0], rgb[1], rgb[2], 255]).collect(); + let image = + craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, pixels).unwrap(); + craft_image_codecs::encode(&image, craft_image_codecs::Format::Png, &Default::default()).unwrap() +} diff --git a/crates/engine/tests/scissors_snap.rs b/crates/engine/tests/scissors_snap.rs new file mode 100644 index 0000000000..f44b0e6f66 --- /dev/null +++ b/crates/engine/tests/scissors_snap.rs @@ -0,0 +1,156 @@ +//! Scissors receives the view's Smart Guides setting and keeps the split endpoint selected. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use serde_json::json; +use vectorcraft_doc::NodeId; +use vectorcraft_engine::{Session, ViewInfo}; +use vectorcraft_geom::{Affine, PathData, Point}; +use vectorcraft_tools::{Overlay, PointerEvent, PointerKind}; + +fn path(session: &Session, id: NodeId) -> PathData { + session.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone() +} + +/// Pixel Preview disables Smart Guides at the Session boundary, rather than asking the tool to +/// interpret that view option. A selected rectangle wins the cut over the crossing line above it. +#[test] +fn scissors_snap_follows_pixel_preview_and_restores_the_cut_selection() { + let mut observed = Vec::new(); + for pixel_preview in [false, true] { + let mut session = Session::new(); + session.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let rectangle = + NodeId(session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()); + let crossing = NodeId(session.execute("shape.line", &json!({"x1": 145, "y1": 90, "x2": 165, "y2": 130})).unwrap()["id"].as_u64().unwrap()); + session.execute("select.set", &json!({"ids": [rectangle.0]})).unwrap(); + let view = ViewInfo { pixel_preview, ..ViewInfo::default() }; + session.select_tool("scissors", view).unwrap(); + let original = path(&session, rectangle); + let line = path(&session, crossing); + let selection_before = session.doc().unwrap().selection.clone(); + let undo_before = session.doc().unwrap().history.undo.len(); + assert!(original.is_closed()); + + session.pointer(&PointerEvent::new(PointerKind::Move, 152.0, 101.5), view).unwrap(); + let intersection = session.overlays(view).iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "intersect")); + for kind in [PointerKind::Down, PointerKind::Up] { + session.pointer(&PointerEvent::new(kind, 152.0, 101.5), view).unwrap(); + } + + let opened = path(&session, rectangle); + assert_eq!(opened.subpaths.len(), 1); + assert!(!opened.is_closed()); + let anchors = &opened.subpaths[0].anchors; + assert_eq!(anchors.len(), 6); + let cut = anchors.first().unwrap().p; + assert_eq!(anchors.last().unwrap().p, cut, "the cut ends coincide"); + let selected = &session.doc().unwrap().selection; + assert_eq!(selected.objects, [rectangle]); + assert_eq!(selected.anchors.len(), 1); + assert_eq!(selected.partial(rectangle).unwrap().iter().copied().collect::>(), [(0, 0)]); + assert!(selected.segments.is_empty(), "one cut endpoint, not a segment, is selected"); + let selection_after = selected.clone(); + assert_eq!(path(&session, crossing), line); + assert_eq!(session.doc().unwrap().history.undo.len(), undo_before + 1); + + session.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&session, rectangle), original); + assert_eq!(path(&session, crossing), line); + assert_eq!(session.doc().unwrap().selection, selection_before); + assert_eq!(session.doc().unwrap().history.undo.len(), undo_before); + session.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(path(&session, rectangle), opened); + assert_eq!(path(&session, crossing), line); + assert_eq!(session.doc().unwrap().selection, selection_after); + assert_eq!(session.doc().unwrap().history.undo.len(), undo_before + 1); + observed.push((pixel_preview, cut, intersection)); + } + + // Observe both producer rows before checking the original failure: without Scissors snapping, + // Smart Guides on cuts at (152, 100), rather than the intersection at (150, 100). + for (pixel_preview, cut, intersection) in observed { + let expected = Point::new(if pixel_preview { 152.0 } else { 150.0 }, 100.0); + assert!(cut.distance(expected) < 1e-6, "Pixel Preview {pixel_preview}: cut {cut:?}, expected {expected:?}"); + assert_eq!(intersection, !pixel_preview, "Pixel Preview {pixel_preview}: intersection feedback"); + } +} + +/// A command that ends an actual drag must settle its deferred move before Scissors reads the +/// document. Real-time drawing is the control: both routes cut the same moved geometry. +#[test] +fn scissors_cuts_after_a_command_settles_a_deferred_move() { + for real_time_drawing in [true, false] { + let mut session = Session::new(); + session.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let rectangle = + NodeId(session.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()); + let crossing = NodeId(session.execute("shape.line", &json!({"x1": 185, "y1": 110, "x2": 205, "y2": 150})).unwrap()["id"].as_u64().unwrap()); + session.execute("select.set", &json!({"ids": [rectangle.0]})).unwrap(); + session.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": real_time_drawing})).unwrap(); + let drag_view = ViewInfo { smart_guides: false, snap_to_point: false, snap_to_grid: false, snap_to_pixel: false, ..ViewInfo::default() }; + session.select_tool("selection", drag_view).unwrap(); + let original = path(&session, rectangle); + let moved = original.transformed(Affine::translate((40.0, 20.0))); + let line = path(&session, crossing); + let undo_before = session.doc().unwrap().history.undo.len(); + + session.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 150.0), drag_view).unwrap(); + session.pointer(&PointerEvent::new(PointerKind::Drag, 190.0, 170.0), drag_view).unwrap(); + assert!(session.in_interaction(), "the pointer drag is still held"); + if real_time_drawing { + assert_eq!(path(&session, rectangle), moved); + assert!(!session.interaction_unapplied(), "the real-time preview is already applied"); + } else { + assert_eq!(path(&session, rectangle), original, "the non-real-time drag has not changed the stored geometry yet"); + assert!(session.interaction_unapplied(), "an actual Selection move is pending"); + let state = session.doc().unwrap(); + let (command, params) = state.interaction.as_ref().unwrap().preview.as_ref().unwrap(); + assert_eq!(command, "object.transform"); + let matrix: Vec = params["matrix"].as_array().unwrap().iter().map(|value| value.as_f64().unwrap()).collect(); + assert_eq!(matrix, [1.0, 0.0, 0.0, 1.0, 40.0, 20.0], "the pending move keeps its exact translation"); + } + // command.batch settles the interaction before its steps; selecting the same object + // changes no geometry and adds no separate undo step. + session + .execute( + "command.batch", + &json!({ + "label": "Keep selection", "commands": [{"command": "select.set", "params": {"ids": [rectangle.0]}}] + }), + ) + .unwrap(); + assert!(!session.in_interaction()); + assert_eq!(path(&session, rectangle), moved, "the command keeps the pending move: real-time={real_time_drawing}"); + assert!(path(&session, rectangle).is_closed()); + assert_eq!(path(&session, crossing), line); + assert_eq!(session.doc().unwrap().history.undo.len(), undo_before + 1); + + // Finish the physical gesture before changing tools. Releasing after the command has + // settled it must neither repeat the transform nor discard its committed geometry. + session.pointer(&PointerEvent::new(PointerKind::Up, 190.0, 170.0), drag_view).unwrap(); + assert!(!session.in_interaction()); + assert_eq!(path(&session, rectangle), moved, "release keeps exactly one move"); + assert_eq!(path(&session, crossing), line); + assert_eq!(session.doc().unwrap().history.undo.len(), undo_before + 1); + + let cut_view = ViewInfo::default(); + session.select_tool("scissors", cut_view).unwrap(); + session.pointer(&PointerEvent::new(PointerKind::Move, 192.0, 121.5), cut_view).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + session.pointer(&PointerEvent::new(kind, 192.0, 121.5), cut_view).unwrap(); + } + let opened = path(&session, rectangle); + assert!(!opened.is_closed()); + let anchors = &opened.subpaths[0].anchors; + let cut = anchors.first().unwrap().p; + assert!(cut.distance(Point::new(190.0, 120.0)) < 1e-6, "the current moved path snaps to its intersection"); + assert_eq!(anchors.last().unwrap().p, cut); + assert_eq!(path(&session, crossing), line); + assert_eq!(session.doc().unwrap().history.undo.len(), undo_before + 2); + session.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&session, rectangle), moved, "undoing the cut retains the earlier settled move"); + assert_eq!(path(&session, crossing), line); + assert_eq!(session.doc().unwrap().selection.objects, [rectangle]); + assert_eq!(session.doc().unwrap().history.undo.len(), undo_before + 1); + } +} diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 3c2b229e1f..22d3203e3b 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -10636,8 +10636,9 @@ fn a_brushs_mask_art_isnt_written_as_a_styled_object_with_its_id() { } /// Settings the other tests don't use come back: a Calligraphic brush varying with tilt and bearing, -/// a Scatter brush keeping its art's colors whose rotation doesn't follow the path, and brushes whose -/// modes aren't given (the reader gives them, the same ones). +/// a Scatter brush keeping its art's colors whose rotation doesn't follow the path, a Calligraphic +/// and a Scatter brush whose size follows an airbrush pen's finger wheel, and brushes whose modes +/// aren't given (the reader gives them, the same ones). #[test] fn more_brush_settings_are_read_back() { use vectorcraft_brush::{Brush, BrushKind, Calligraphic, Colorization, Scatter, Variation}; @@ -10662,8 +10663,20 @@ fn more_brush_settings_are_read_back() { let lib = vec![ Brush { name: "Tilted".into(), kind: BrushKind::Calligraphic(tilted.clone()) }, Brush { name: "Still".into(), kind: BrushKind::Scatter(scatter.clone()) }, - Brush { name: "Unset nib".into(), kind: BrushKind::Calligraphic(Calligraphic { modes: None, ..tilted }) }, - Brush { name: "Unset spray".into(), kind: BrushKind::Scatter(Scatter { modes: None, ..scatter }) }, + Brush { name: "Unset nib".into(), kind: BrushKind::Calligraphic(Calligraphic { modes: None, ..tilted.clone() }) }, + Brush { name: "Unset spray".into(), kind: BrushKind::Scatter(Scatter { modes: None, ..scatter.clone() }) }, + Brush { + name: "Wheel nib".into(), + kind: BrushKind::Calligraphic(Calligraphic { modes: Some([Variation::Fixed, Variation::Fixed, Variation::StylusWheel]), ..tilted }), + }, + Brush { + name: "Wheel spray".into(), + kind: BrushKind::Scatter(Scatter { + size: (40.0, 160.0), + modes: Some([Variation::StylusWheel, Variation::Fixed, Variation::Fixed, Variation::Fixed]), + ..scatter + }), + }, ]; let mut doc = Document::new(300.0, 200.0); vectorcraft_brush::store(&mut doc, &lib); diff --git a/crates/eps/src/ai_editing/writer/brushes.rs b/crates/eps/src/ai_editing/writer/brushes.rs index ac7ca48ac8..c24dbdf1d7 100644 --- a/crates/eps/src/ai_editing/writer/brushes.rs +++ b/crates/eps/src/ai_editing/writer/brushes.rs @@ -96,6 +96,7 @@ fn code(v: Variation) -> f64 { Variation::Fixed => 0.0, Variation::Random => 1.0, Variation::Pressure => 2.0, + Variation::StylusWheel => 3.0, Variation::Tilt => 4.0, Variation::Bearing => 5.0, Variation::Rotation => 6.0, diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index 5b170b239e..c630c9cf43 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -38,11 +38,13 @@ pub(crate) use blend::{MAX_BLEND_OBJECTS, MAX_KEYS as MAX_BLEND_KEYS, PLUGIN as pub(crate) use brush::{ BrushesRead, MANAGER_NAME as BRUSH_MANAGER, brushes_kept, plugin_name as brush_plugin_name, read_brush_object, turn_over as turn_brush_art_over, }; +#[cfg(test)] +pub(crate) use envelope::DASH_CHECKS_MADE; pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN; -pub(crate) use envelope::MAX_CHECKED; pub(crate) use envelope::TYPE_DRAWN as ENVELOPE_TYPE_DRAWN; pub(crate) use envelope::{GridPoint as EnvelopeGridPoint, PLUGIN as DEFORM_PLUGIN, outline as envelope_outline, upright as envelope_upright}; pub(crate) use envelope::{MAX_ANY as ENVELOPE_MAX_ANY, MAX_SOLID as ENVELOPE_MAX_SOLID}; +pub(crate) use envelope::{MAX_CHECKED, MAX_DASH_CHECKS}; pub(crate) use envelope::{WARPED_TYPE_DRAWN, WarpedType}; #[cfg(test)] pub(crate) use frames::TEXT_FRAME_SCANS; @@ -67,7 +69,7 @@ pub use read::{ #[cfg(test)] pub(crate) use style::ART_STYLE_PARSES; -pub(crate) use read::is_look_slot; +pub(crate) use read::{clip_by_type, is_look_slot}; pub(crate) use style::{MAX_LISTED, MAX_LISTED_NAME, warp_number}; #[cfg(test)] diff --git a/crates/eps/src/import/ai/blend.rs b/crates/eps/src/import/ai/blend.rs index d317164d3a..c1d80a1d63 100644 --- a/crates/eps/src/import/ai/blend.rs +++ b/crates/eps/src/import/ai/blend.rs @@ -10,7 +10,8 @@ //! locally, never committed): the blend's own art on `%_` lines, a group holding the key objects //! and the spine, each object's `/ArtDictionary` naming its part (`ShapeBlendPathType`: `K` a key, //! `S` the spine) and a key's id (`ShapeBlendPathID`); then the steps drawn, a group on plain -//! lines; then `(Adobe Path Blends) 1 0 n XP` and `n` bytes as hex on `%` lines. Those bytes +//! lines; then `(Adobe Path Blends) 1 0 n XP` and `n` bytes as hex on `%` lines (`%_%` lines +//! for a blend in hidden art, as an opacity mask's is: all of it is on `%_` lines). Those bytes //! start `DCBA`. A blend whose spine was never edited has no spine part: only its keys. //! //! The reader reads the words after `DCBA` (little endian) this way. Word 1 is the spacing: 0 is diff --git a/crates/eps/src/import/ai/brush.rs b/crates/eps/src/import/ai/brush.rs index da7f4c3576..ab2473ae4f 100644 --- a/crates/eps/src/import/ai/brush.rs +++ b/crates/eps/src/import/ai/brush.rs @@ -209,12 +209,13 @@ fn numbers(s: &str) -> Option> { s.split_whitespace().map(|w| w.parse::().ok().filter(|v| v.is_finite())).collect() } -/// How a value varies, by its code: `None` for the stylus wheel and codes that aren't known. +/// How a value varies, by its code: `None` for codes that aren't known. fn variation(code: f64) -> Option { match code { 0.0 => Some(Variation::Fixed), 1.0 => Some(Variation::Random), 2.0 => Some(Variation::Pressure), + 3.0 => Some(Variation::StylusWheel), 4.0 => Some(Variation::Tilt), 5.0 => Some(Variation::Bearing), 6.0 => Some(Variation::Rotation), diff --git a/crates/eps/src/import/ai/envelope.rs b/crates/eps/src/import/ai/envelope.rs index 501b9f4b00..4a5a11940c 100644 --- a/crates/eps/src/import/ai/envelope.rs +++ b/crates/eps/src/import/ai/envelope.rs @@ -59,6 +59,16 @@ pub(crate) fn drawn_note(typed: bool) -> &'static str { pub(super) const MAX_PENDING: usize = 64; /// The most envelopes and warped text objects one import draws to check; more keep their drawn art. pub(crate) const MAX_CHECKED: usize = 256; +/// The most strokes with dashes aligned to corners one import draws to check against their drawn +/// looks (apart from [`MAX_CHECKED`]); more keep their drawn looks. +pub(crate) const MAX_DASH_CHECKS: usize = 256; + +#[cfg(test)] +thread_local! { + /// How many strokes with dashes aligned to corners have been drawn on this thread to check them + /// against their looks. + pub(crate) static DASH_CHECKS_MADE: std::cell::Cell = const { std::cell::Cell::new(0) }; +} /// The most rows or columns of a mesh read (Make with Mesh's own limit). const MAX_GRID: u32 = 50; /// How far, in points over width and height together, a saved size may lie from the contents' @@ -692,6 +702,8 @@ pub struct WarpedType { pub(super) checks: usize, pub(super) spent: Spent, pub(super) page: Option, + /// [`super::Structure::type_clips`]: type in an envelope's contents clips its clipping group too. + pub(super) type_clips: HashMap, /// The envelopes of type that may open live in layers built without a page, by their place /// among them ([`Self::open_alone`]): none when `None`. pub(super) alone: Option>, @@ -811,8 +823,10 @@ impl WarpedType { texts.insert(slot, text); hidden.push(id); } + let typed = |slot: NodeId| texts.get(&slot).map(|t| t.id); for n in before.iter_mut().chain(inner.iter_mut()) { put_type(n, &texts); + super::clip_by_type(n, &self.type_clips, &typed, &mut |_| ()); } // A warp that VectorCraft's own warp doesn't draw as its drawn art may still draw as the // grid the file saves for it: then it opens as a mesh envelope on that grid. @@ -980,10 +994,11 @@ pub(super) fn warps(appearance: &Appearance) -> bool { appearance.effects.iter().any(warp) || appearance.items.iter().any(|i| i.visible() && i.effects().iter().any(warp)) } -/// Do `live` and `drawn` draw alike: few of the pixels either inks differ, and fewer still where a -/// whole patch differs; and, on `page` (when the file has one), do they differ little enough that -/// with the differences in `spent` the page check still takes the layers' art (it is added to -/// `spent` when they do)? Both are drawn on `layer`, a layer id no other node has. +/// Do `live` and `drawn` draw alike? Either neither has any paint ([`paints`]), or few of the +/// pixels either inks differ and fewer still where a whole patch differs, and, on `page` (when the +/// file has one), they differ little enough that with the differences in `spent` the page check +/// still takes the layers' art (it is added to `spent` when they do). Both are drawn on `layer`, a +/// layer id no other node has. pub(super) fn drawn_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Shared<'_>, page: Option, spent: &mut Spent) -> bool { alike_within(live, drawn, live.visual_bounds(), layer, shared, page, spent) } @@ -997,6 +1012,12 @@ pub(super) fn warped_alike(live: &Node, drawn: &Node, layer: NodeId, shared: &Sh /// [`drawn_alike`], with `live` measured as `reach`. fn alike_within(live: &Node, drawn: &Node, reach: Option, layer: NodeId, shared: &Shared<'_>, page: Option, spent: &mut Spent) -> bool { + // Neither has any paint (type with no fill and no stroke, its drawn art the outlines unpainted): + // both draw nothing, so they draw alike and add nothing to what the page check sees. Their + // shapes aren't compared. Art that paints, however faintly, is compared as before. + if !paints(live, 0) && !paints(drawn, 0) { + return true; + } let (Some(a), Some(b)) = (reach, drawn.visual_bounds()) else { return false }; let region = a.union(b).inflate(2.0, 2.0); if !(region.is_finite() && region.width() > 0.0 && region.height() > 0.0) || region.width().max(region.height()) > 1e6 { @@ -1029,6 +1050,26 @@ fn alike_within(live: &Node, drawn: &Node, reach: Option, layer: NodeId, s true } +/// Does `n`, shown, paint anything: a fill or stroke of its own or of its type with a paint, an +/// effect, or an object of another kind than a path, type or container (an image, a mesh, a symbol +/// instance…)? Hidden objects paint nothing. Past `depth` 64 it is taken to paint. +fn paints(n: &Node, depth: usize) -> bool { + if depth > 64 { + return true; + } + if !n.visible { + return false; + } + if n.appearance.items.iter().any(|i| i.visible() && !i.paint().is_none()) || n.appearance.effects.iter().any(|e| e.visible) { + return true; + } + match &n.kind { + NodeKind::Path { .. } => false, + NodeKind::Text(t) => t.runs.iter().any(|r| !r.style.fill.is_none() || !r.style.stroke.is_none()), + _ => n.children().is_none_or(|c| c.iter().any(|c| paints(c, depth + 1))), + } +} + #[cfg(test)] mod tests { use super::*; @@ -1056,6 +1097,41 @@ mod tests { } } + /// A 40 × 40 square at (10, 10) filled black at `opacity`, or with no fill when `None`. + fn square_node(id: u64, opacity: Option) -> Node { + let mut bp = BezPath::new(); + bp.move_to((10.0, 10.0)); + bp.line_to((50.0, 10.0)); + bp.line_to((50.0, 50.0)); + bp.line_to((10.0, 50.0)); + bp.close_path(); + let mut n = Node::new( + NodeId(id), + NodeKind::Path { path: PathData::from_bezpath(&bp), rule: Default::default(), live: None, clipping: false, guide: false }, + ); + let mut appearance = (*n.appearance).clone(); + appearance.items.clear(); + if let Some(o) = opacity { + appearance.items.push(AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK)))); + n.opacity = o; + } + n.appearance = appearance.into(); + n + } + + /// Two objects with no paint draw alike; two that paint too faintly to ink a pixel (an alpha of + /// 8 or less) aren't taken as alike, nor is one with paint against one without. + #[test] + fn art_with_no_paint_draws_alike_and_faint_art_is_still_compared() { + let shared = Shared { patterns: &[], images: &BTreeMap::new() }; + let alike = |a: &Node, b: &Node| drawn_alike(a, b, NodeId(999), &shared, None, &mut Spent::default()); + let (none, other_none) = (square_node(1, None), square_node(2, None)); + assert!(alike(&none, &other_none)); + let (faint, other_faint) = (square_node(1, Some(0.02)), square_node(2, Some(0.02))); + assert!(!alike(&faint, &other_faint)); + assert!(!alike(&none, &square_node(2, Some(1.0)))); + } + /// "AVA" at 40 points, at (10, 60). fn type_node(id: u64, style: CharStyle) -> Node { Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(Point::new(10.0, 60.0), "AVA", CharStyle { size: 40.0, ..style })))) diff --git a/crates/eps/src/import/ai/lex.rs b/crates/eps/src/import/ai/lex.rs index 810a01c3f2..a43166ccc9 100644 --- a/crates/eps/src/import/ai/lex.rs +++ b/crates/eps/src/import/ai/lex.rs @@ -5,7 +5,8 @@ //! - Any other line starting with `%` is a [`Tok::Comment`] (the section markers). //! - `%_` later in a line starts tokens too, hidden (a pseudo-comment operator after its //! operands, as a gradient stop's `… 50 100 %_Bs`: AI7 spec §1.4.3); any other `%` later in a -//! line starts a comment that is skipped. +//! line starts a comment that is skipped, but for a line of hex digits after `%_` (a hidden +//! blend's record), a hidden [`Tok::Comment`]. //! - The binary image data after `%%BeginData:` is one [`Tok::Data`]; the binary preview of a placed //! file is one [`Tok::Preview`]. //! - A document included whole (`%%BeginDocument:` … `%%EndDocument` lines, DSC 3.0 p. 68, nested @@ -222,6 +223,12 @@ impl<'a> Lexer<'a> { if prefixed && PLACE.iter().chain(&NOTES).chain(&RELATIVE).any(|m| line.starts_with(m)) { return Some(Token { tok: Tok::Comment(line.get(1..).unwrap_or_default()), hidden: true }); } + // And a line of hex digits, as a hidden blend's record is written (`%_%4443…` + // after its `XP`), like the plain one on `%` lines. + let digits = line.get(1..).unwrap_or_default(); + if prefixed && !digits.trim_ascii_end().is_empty() && digits.trim_ascii_end().iter().all(u8::is_ascii_hexdigit) { + return Some(Token { tok: Tok::Comment(digits), hidden: true }); + } // A comment later in a line. continue; } @@ -470,6 +477,10 @@ mod tests { let toks = all(b"1 % a note (\n2 %_Bs\n3 %_ 4\n"); let words: Vec<_> = toks.iter().map(|t| (t.tok.clone(), t.hidden)).collect(); assert_eq!(words, [(Tok::Num(1.0), false), (Tok::Num(2.0), false), (Tok::Word(b"Bs"), true), (Tok::Num(3.0), false)]); + // A hidden line of hex digits (a hidden blend's record) is a comment; other text after + // `%_%` stays skipped. + let toks = all(b"%_%44434241\n%_% not hex\n%_%\n1\n"); + assert_eq!(toks, [t(Tok::Comment(b"44434241"), true), t(Tok::Num(1.0), false)]); } #[test] diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index cc43157bcb..b354022258 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -195,6 +195,10 @@ pub struct Structure { pub unread_elsewhere: Vec<(NodeId, Rect)>, /// The names of text objects, by their slot's id. pub slot_names: HashMap, + /// The clipping groups whose type clips them, by the group's id: the text slot of that type, + /// the group's last object ([`Reader::end_container`]). Once the slot holds its type, the type + /// clips the group ([`clip_by_type`]). + pub type_clips: HashMap, /// Where the drawn looks lay that objects read with their art style took the place of (the /// document's coordinates): the page draws Illustrator's rendering of those styles there. pub restyled: Vec, @@ -595,6 +599,13 @@ struct Reader<'a> { envelope_checks: usize, /// How far the live envelopes read so far draw from their drawn art ([`super::envelope::Spent`]). envelope_spent: super::envelope::Spent, + /// How many more strokes with dashes aligned to corners this import may draw to check + /// ([`super::MAX_DASH_CHECKS`]). + dash_checks: usize, + /// Whether this reader reads only what comes before the first layer (swatches, brushes, styles, + /// symbols) for a file whose layers another reader reads: it makes no more checks once it + /// reaches the layers, so it spends none of theirs. + defs_only: bool, /// The text objects read with a Warp ([`super::envelope::WarpedType`]). warped_type: Vec, /// The envelopes of type read with their drawn art, settled once the type is laid out @@ -662,6 +673,8 @@ struct Reader<'a> { obj_hidden: bool, /// The names of text objects, by their slot's id. slot_names: HashMap, + /// [`Structure::type_clips`]. + type_clips: HashMap, /// [`Structure::xml_ids`]. xml_ids: HashMap>, /// The bytes of the ids in `xml_ids`. @@ -732,6 +745,40 @@ pub(crate) fn is_look_slot(name: Option<&str>) -> bool { name == Some(document::LOOK_SLOT) } +/// Make the clipping groups of [`Structure::type_clips`] in `n` and its groups clip by their type, +/// once their slots are filled: where a group's slot became one text object (`typed` gives its id by +/// the slot's) that is still the group's last object, that text object moves to the front as its +/// clipping path, and `clipping` is called on it. Where the slot was left empty or became several +/// objects, the group stays as read, unclipped. How many groups clip. +pub(crate) fn clip_by_type( + n: &mut Node, + clips: &HashMap, + typed: &impl Fn(NodeId) -> Option, + clipping: &mut impl FnMut(&mut Node), +) -> usize { + if clips.is_empty() || matches!(n.kind, NodeKind::Compound { .. }) { + return 0; + } + let mut made = 0; + if let Some(children) = n.children_mut() { + for c in children.iter_mut().filter(|c| c.children().is_some_and(|k| !k.is_empty())) { + made += clip_by_type(Arc::make_mut(c), clips, typed, clipping); + } + } + let Some(text) = clips.get(&n.id).and_then(|slot| typed(*slot)) else { return made }; + if let NodeKind::Group { children, clip } = &mut n.kind + && !*clip + && children.last().is_some_and(|last| last.id == text && matches!(last.kind, NodeKind::Text(_))) + && let Some(mut last) = children.pop() + { + clipping(Arc::make_mut(&mut last)); + children.insert(0, last); + *clip = true; + made += 1; + } + made +} + impl<'a> Reader<'a> { /// A reader of the editing data `data` as a whole, with the names its gradients and patterns /// get in the document and its art styles found first ([`swatch_names`]): the symbols defined @@ -824,6 +871,8 @@ impl<'a> Reader<'a> { envelopes: Vec::new(), envelope_checks: super::envelope::MAX_CHECKED, envelope_spent: super::envelope::Spent::default(), + dash_checks: super::MAX_DASH_CHECKS, + defs_only: false, warped_type: Vec::new(), typed_envelopes: Vec::new(), envelopes_drawn: Vec::new(), @@ -853,6 +902,7 @@ impl<'a> Reader<'a> { done: false, obj_hidden: false, slot_names: HashMap::new(), + type_clips: HashMap::new(), xml_ids: HashMap::new(), xml_id_bytes: 0, art_size: None, diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 9db1470093..46743e9d70 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -16,6 +16,9 @@ impl<'a> Reader<'a> { if matches!(kind, Kind::Layer(_)) { self.ensure_space(); self.check_symbols(); + if self.defs_only { + (self.envelope_checks, self.dash_checks) = (0, 0); + } } let base = if matches!(kind, Kind::Obj(_)) { self.stack.len() } else { self.frames.last().map_or(0, |f| f.base) }; self.frames.push(Frame { @@ -120,11 +123,13 @@ impl<'a> Reader<'a> { } // A group holding only clipping paths (`q … u W n U … Q`) doesn't clip on its own: `u`/`U` don't save // the graphics state as `q`/`Q` do, so its paths clip the clipping group around it, as the file's PDF part draws it. + // In a compound path (`*u u W n … U *U`, possibly nested in other groups) they are the compound + // path's subpaths, as its other grouped paths are: the compound clipping path, their union. if matches!(kind, Kind::Group) && unread.is_empty() && !clips.is_empty() && clips.len() == kids.len() - && matches!(self.frames.last(), Some(Frame { kind: Kind::Clip, .. })) + && (matches!(self.frames.last(), Some(Frame { kind: Kind::Clip, .. })) || self.in_compound()) { for kid in kids { if let Some(parent) = self.frames.last_mut() { @@ -134,6 +139,15 @@ impl<'a> Reader<'a> { } return Ok(()); } + // A clipping group (`q` … `Q`) with no clipping path whose last object is type: that type is + // its clipping path, as Illustrator writes a clipping mask of type made from the text + // document (`/AI11Text`), which has no `W`. The slot is filled later ([`clip_by_type`]). + let type_clip = match kids.last() { + Some(last) if matches!(kind, Kind::Clip) && clips.is_empty() && !super::is_look_slot(last.name.as_deref()) => { + slot_of(last.name.as_deref()).map(|_| last.id) + } + _ => None, + }; // A compound path of clipping paths clips its clipping group. let clipping = matches!(kind, Kind::Compound) && !clips.is_empty(); self.group_ended = !matches!(kind, Kind::Compound); @@ -179,6 +193,9 @@ impl<'a> Reader<'a> { if clipping && let Some(f) = self.frames.last_mut() { f.clips.push(f.children.len()); } + if let Some(slot) = type_clip { + self.type_clips.insert(node.id, slot); + } if compound_members { self.compound_groups.insert(node.id); } @@ -197,6 +214,18 @@ impl<'a> Reader<'a> { Ok(()) } + /// Is the innermost open frame a compound path (`*u`), or a group in one with only groups between them? + fn in_compound(&self) -> bool { + for f in self.frames.iter().rev() { + match f.kind { + Kind::Group => {} + Kind::Compound => return true, + _ => return false, + } + } + false + } + /// The compound path of `kids`, painted and made transparent as its subpaths say. fn compound(&mut self, mut kids: Vec, gs: &GState) -> Option { // The compound path's paint is its last path's (a gradient's instance wraps only diff --git a/crates/eps/src/import/ai/read/directives.rs b/crates/eps/src/import/ai/read/directives.rs index 8ca3781717..67b3e799e2 100644 --- a/crates/eps/src/import/ai/read/directives.rs +++ b/crates/eps/src/import/ai/read/directives.rs @@ -837,11 +837,13 @@ impl<'a> Reader<'a> { } /// Lend `sub`, a reader of a definition, what this import may still spend on laying out blends - /// and checking envelopes ([`Reader::take_back_budgets`] takes back what is left). + /// and checking envelopes and aligned dashes ([`Reader::take_back_budgets`] takes back what is + /// left). fn lend_budgets(&mut self, sub: &mut Reader<'_>) { sub.blend_budget = self.blend_budget; sub.envelope_checks = self.envelope_checks; sub.envelope_spent = std::mem::take(&mut self.envelope_spent); + sub.dash_checks = self.dash_checks; } /// Take back from `sub` what [`Self::lend_budgets`] lent it, less what it spent. @@ -849,6 +851,7 @@ impl<'a> Reader<'a> { self.blend_budget = sub.blend_budget; self.envelope_checks = sub.envelope_checks; self.envelope_spent = std::mem::take(&mut sub.envelope_spent); + self.dash_checks = sub.dash_checks; } /// In a pattern's definition, the operands of its first operator start with its head, diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index f3684f3882..2eee5a0a15 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -336,6 +336,7 @@ fn repoint(n: &mut Node, renamed: &std::collections::BTreeMap) { /// those the swatches take. pub fn palette(data: &[u8], patterns: &[PatternDef], names: &mut obj::Names) -> Option { let mut r = Reader::with_names(data, names.encoding); + r.defs_only = true; // The palette, the gradients and the patterns it names come before the art, so an error in the // art leaves them read. let _ = r.run(); @@ -396,6 +397,7 @@ pub fn brushes(data: &[u8], patterns: &[PatternDef], names: &mut obj::Names) -> // Brush objects are plug-in objects: data without one isn't read again. memchr::memmem::find(data, b"BeginPluginObject")?; let mut r = Reader::with_names(data, names.encoding); + r.defs_only = true; // The brushes come before the art, so an error in the art leaves them read. let _ = r.run(); let (mut lib, unread) = r.brush_library()?; @@ -449,6 +451,7 @@ pub fn graphic_styles(data: &[u8], large_canvas: bool, names: &mut obj::Names) - return (vec![], 1.0); } let mut r = Reader::with_names(data, names.encoding); + r.defs_only = true; r.large_canvas = large_canvas.then_some(1.0); // The styles come before the art, so an error in the art leaves them read. let _ = r.run(); @@ -482,6 +485,7 @@ pub struct Symbols { pub fn symbols(data: &[u8], names: &mut obj::Names) -> Option { crate::import::ai::find(data, b"BeginSymbol")?; let mut r = Reader::with_names(data, names.encoding); + r.defs_only = true; // The symbols come before the art, so an error in the art leaves them read. let _ = r.run(); r.check_symbols(); @@ -536,10 +540,20 @@ pub fn symbols(data: &[u8], names: &mut obj::Names) -> Option { Some(Symbols { symbols, images, swatches, canvas_scale: r.canvas_scale, own_size: r.symbols_own_size }) } +/// A reader of all of `data` for what doesn't depend on how its art draws (its artboards, its +/// variable library): it checks no envelope and no stroke with aligned dashes against its drawn +/// look, so it spends none of the import's checks ([`super::MAX_CHECKED`], +/// [`super::MAX_DASH_CHECKS`]), which are the layers' reader's. +fn reader_aside(data: &[u8]) -> Reader<'_> { + let mut r = Reader::new(data); + (r.envelope_checks, r.dash_checks) = (0, 0); + r +} + /// [`artboards`] as far as reading `data` from its start gets: those read before an error, and /// those of a `/Document` still open when it stopped (its art can be what stopped it). fn artboards_read(data: &[u8], names: &mut obj::Names) -> (Vec<(String, Rect)>, Option) { - let mut r = Reader::new(data); + let mut r = reader_aside(data); r.names = obj::Names::new(names.encoding); let _ = r.run(); let open: Vec = r.frames.iter().filter_map(|f| if let Kind::Obj(o) = &f.kind { Some((**o).clone()) } else { None }).collect(); @@ -608,7 +622,7 @@ pub fn variables(data: &[u8], names: &mut obj::Names) -> VariableRead { if crate::import::ai::find(data, b"variableSets").is_none() { return VariableRead::default(); } - let mut r = Reader::new(data); + let mut r = reader_aside(data); r.names = obj::Names::new(names.encoding); let _ = r.run(); if r.variables.present { @@ -1385,6 +1399,7 @@ impl<'a> Reader<'a> { unread: self.unread, unread_elsewhere: self.unread_elsewhere, slot_names: self.slot_names, + type_clips: self.type_clips.clone(), restyled: self.restyled, placeholders: self.placeholders, placed_elsewhere: self.placed_elsewhere, @@ -1397,6 +1412,7 @@ impl<'a> Reader<'a> { spent: self.envelope_spent, page, alone: None, + type_clips: self.type_clips, }, styles_read, text_patterns, @@ -1960,6 +1976,20 @@ impl LibraryWalk { } } +/// Whether an XML node in `o` or the dictionaries it holds has a value or a type +/// (`xmlnode-nodevalue`, `xmlnode-nodetype`). `seen` counts the dictionaries looked at; past +/// [`MAX_LIBRARY_NODES`] of them, or deeper than [`MAX_DEPTH`], the library is taken to hold some. +fn holds_values(o: &Obj, seen: &mut usize, depth: usize) -> bool { + *seen = seen.saturating_add(1); + if *seen > MAX_LIBRARY_NODES || depth > MAX_DEPTH { + return true; + } + if o.ty == "XMLNode" && (o.get("xmlnode-nodevalue").is_some() || o.get("xmlnode-nodetype").is_some()) { + return true; + } + o.items().any(|c| holds_values(c, seen, depth + 1)) +} + /// The library of the `variableSets` element `sets` (see [`variable_library`]). fn read_variable_sets(sets: &Obj) -> VariableRead { let mut walk = LibraryWalk::default(); @@ -1979,5 +2009,34 @@ fn read_variable_sets(sets: &Obj) -> VariableRead { if walk.nodes > MAX_LIBRARY_NODES { return VariableRead { variables: Variables::default(), bindings: vec![], bindings_skipped: 0, skipped: 1, present: true }; } + if vars == Variables::default() && walk.bindings.is_empty() && !holds_values(sets, &mut 0, 0) { + // The empty library a file can keep: nodes with names and nothing else (no value, no + // type). There is nothing in it to list, so nothing was left out. + walk.skipped = 0; + } VariableRead { variables: vars, bindings: walk.bindings, bindings_skipped: walk.bindings_skipped, skipped: walk.skipped, present: true } } + +#[cfg(test)] +mod tests { + use super::*; + use std::rc::Rc; + + /// An XML node holding `child` (when given) and nothing else: no value, no type. + fn node(child: Option) -> Obj { + let children = Obj { ty: "Array".into(), content: child.map(|c| V::Obj(Rc::new(c))).into_iter().collect(), ..Obj::default() }; + Obj { ty: "XMLNode".into(), entries: vec![(Some("xmlnode-children".into()), vec![V::Obj(Rc::new(children))])], ..Obj::default() } + } + + /// An empty library is taken to hold values past the caps on what is looked at: nested deeper + /// than [`MAX_DEPTH`], or once [`MAX_LIBRARY_NODES`] dictionaries have been looked at. + #[test] + fn an_empty_library_past_the_caps_is_taken_to_hold_values() { + let shallow = node(Some(node(None))); + assert!(!holds_values(&shallow, &mut 0, 0)); + let deep = (0..MAX_DEPTH).fold(node(None), |inner, _| node(Some(inner))); + assert!(holds_values(&deep, &mut 0, 0)); + let mut seen = MAX_LIBRARY_NODES; + assert!(holds_values(&shallow, &mut seen, 0)); + } +} diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 5283762a51..101d924d60 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -832,15 +832,32 @@ impl<'a> Reader<'a> { }) }); // An image with a Warp is the object only where its live warp draws as its drawn look, and - // while the import has a check left for it; otherwise its drawn look stays. + // while the import has a check left for it; otherwise its drawn look stays. So is a stroke + // with dashes aligned to corners and path ends, whose fitting is VectorCraft's own, within + // checks of its own ([`crate::import::ai::MAX_DASH_CHECKS`]) and without weighing the page: + // the envelopes' checks and share of the page check stay theirs alone. Type with such + // dashes keeps its drawn look, as before. let appearance = match appearance { + Some(ap) if aligns_dashes(&ap) && slot_of(object.name.as_deref()).is_some() => None, Some(ap) if matches!(object.kind, NodeKind::Image(_)) && ap.effects.iter().any(|e| e.id.starts_with("warp.")) => { let alike = self.envelope_checks > 0 && { self.envelope_checks -= 1; let layer = self.doc.alloc_id(); let shared = crate::import::ai::envelope::Shared { patterns: &self.doc.patterns, images: &self.doc.images }; let shown = !hidden && object.visible && look.visible; - image_warp_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, page.filter(|_| shown), &mut self.envelope_spent) + look_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, page.filter(|_| shown), &mut self.envelope_spent) + }; + alike.then_some(ap) + } + Some(ap) if aligns_dashes(&ap) => { + let alike = self.dash_checks > 0 && { + self.dash_checks -= 1; + #[cfg(test)] + crate::import::ai::DASH_CHECKS_MADE.set(crate::import::ai::DASH_CHECKS_MADE.get() + 1); + let layer = self.doc.alloc_id(); + let shared = crate::import::ai::envelope::Shared { patterns: &self.doc.patterns, images: &self.doc.images }; + let mut spent = crate::import::ai::envelope::Spent::default(); + look_alike(object, &ap, look, &self.hidden_ids, hidden, layer, &shared, None, &mut spent) }; alike.then_some(ap) } @@ -1062,23 +1079,35 @@ fn tick(vals: &[V]) -> Option<(Affine, Rect, String)> { } /// The gradients and patterns `look` paints with, placed as it draws them, by their swatch's name -/// (the first of each; a pattern's name after `PATTERN_KEY`). -fn placed_paints(look: &Node, out: &mut HashMap, depth: usize) { +/// (the first of each; a pattern's name after `PATTERN_KEY`). With `fill_patterns`, a pattern only +/// where the look fills with it: a style's pattern is a fill, so a path's stack takes it from the +/// look's fills alone (type keeps taking it from either). `moved` gets each pattern that the look +/// also places elsewhere than its first placement. +fn placed_paints(look: &Node, out: &mut HashMap, moved: &mut HashSet, fill_patterns: bool, depth: usize) { if depth > MAX_DEPTH { return; } for item in &look.appearance.items { let key = match item.paint() { Paint::Gradient(g) => g.swatch.clone(), - Paint::Pattern { pattern, .. } => Some(format!("{PATTERN_KEY}{pattern}")), + Paint::Pattern { pattern, .. } if item.is_fill() || !fill_patterns => Some(format!("{PATTERN_KEY}{pattern}")), _ => None, }; if let Some(key) = key { - out.entry(key).or_insert_with(|| item.paint().clone()); + match out.get(&key) { + Some(first) => { + if matches!(first, Paint::Pattern { .. }) && first != item.paint() { + moved.insert(key); + } + } + None => { + out.insert(key, item.paint().clone()); + } + } } } for c in look.children().into_iter().flatten() { - placed_paints(c, out, depth + 1); + placed_paints(c, out, moved, fill_patterns, depth + 1); } } @@ -1224,18 +1253,19 @@ fn moves_with(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool { /// Is `object` an image without an opacity mask, and `st` one Warp on it with nothing else that /// paints ([`crate::import::ai::style::ArtStyle::image_warp`])? Such an image is read with its Warp -/// live where that draws as its drawn look ([`image_warp_alike`]). +/// live where that draws as its drawn look ([`look_alike`]). fn image_warps(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool { matches!(object.kind, NodeKind::Image(_)) && object.extras().mask.is_none() && st.image_warp } -/// Does image `object` with `appearance` (its style's Warp) draw as `look`, its drawn look, compared -/// over all that the warp draws ([`crate::import::ai::envelope::warped_alike`]) on `layer`, a layer -/// id no other node has? Both are drawn shown, opaque and in the Normal mode; a hidden look is drawn -/// with every object in it shown, as the hidden object's look holds them. Unless the look is on -/// `%_` lines itself (`hidden`), the copies in it that are on `%_` lines (`hidden_ids`) are left out. +/// Does `object` with `appearance` (an image's Warp, or a stroke with dashes aligned to corners) +/// draw as `look`, its drawn look, compared over all that it draws, effects included +/// ([`crate::import::ai::envelope::warped_alike`]), on `layer`, a layer id no other node has? Both +/// are drawn shown, opaque and in the Normal mode; a hidden look is drawn with every object in it +/// shown, as the hidden object's look holds them. Unless the look is on `%_` lines itself +/// (`hidden`), the copies in it that are on `%_` lines (`hidden_ids`) are left out. #[allow(clippy::too_many_arguments)] -fn image_warp_alike( +fn look_alike( object: &Node, appearance: &Appearance, look: &Node, @@ -1261,6 +1291,11 @@ fn image_warp_alike( crate::import::ai::envelope::warped_alike(&live, &plain, layer, shared, page, spent) } +/// Does `appearance` stroke with dashes aligned to corners and path ends? +fn aligns_dashes(appearance: &Appearance) -> bool { + appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.dash.as_ref().is_some_and(|d| d.align_corners && d.is_dashed()))) +} + /// Show every object in container `n`, at any depth. fn show_members(n: &mut Node) { for c in n.children_mut().into_iter().flatten() { @@ -1282,7 +1317,7 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p let slot = slot_of(object.name.as_deref()).is_some(); // Several fills and strokes, on a path or a compound path. let stacked = !slot && !st.simple && st.stacked && matches!(object.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }); - // One Warp on an image, checked against its drawn look by the caller ([`image_warp_alike`]). + // One Warp on an image, checked against its drawn look by the caller ([`look_alike`]). let image_warp = !st.simple && image_warps(object, st); // A symbol instance draws its symbol's art: it keeps its drawn look. if !st.plain @@ -1301,15 +1336,22 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p let own_gradient = object.appearance.fill().filter(|f| matches!(f.paint, Paint::Gradient(_))); // A style's gradients are written in a space of the object's bounds that isn't documented; its // drawn look has each where the app placed it. - let mut placed = HashMap::new(); - placed_paints(look, &mut placed, 0); + let (mut placed, mut moved) = (HashMap::new(), HashSet::new()); + placed_paints(look, &mut placed, &mut moved, stacked, 0); // A stack's gradients are each its own swatch, placed where the drawn look has it: one fitted - // to the object's bounds instead could lie elsewhere, so such a stack keeps its drawn look. + // to the object's bounds instead could lie elsewhere, so such a stack keeps its drawn look. So + // are its patterns, each once, and each placed one way in the look: `placed_paints` keeps the + // first placement of each name, and which of several is the style's isn't known. The same + // placement again (a compound path's look fills each subpath) is still one. if stacked { - let mut seen = HashSet::new(); + let (mut seen, mut seen_patterns) = (HashSet::new(), HashSet::new()); let placed_apart = st.items.iter().all(|i| match i { StyleItem::Gradient { name: Some(n), .. } => seen.insert(n) && placed.contains_key(paints.names.get(Global::Gradient, n)), StyleItem::Gradient { name: None, .. } => false, + StyleItem::Pattern { name, .. } => { + let key = format!("{PATTERN_KEY}{}", paints.names.get(Global::Pattern, name)); + seen_patterns.insert(key.clone()) && placed.contains_key(&key) && !moved.contains(&key) + } _ => true, }); if !placed_apart { @@ -1382,7 +1424,134 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p } else { object.appearance.contents_index }; - Some(Appearance { items, effects: st.effects.clone(), contents_index }) + let appearance = Appearance { items, effects: st.effects.clone(), contents_index }; + // Zig Zag's ridges are placed by VectorCraft's own rule: on objects other than type it is kept + // only where they draw the outline the drawn look has. + if !slot && st.effects.iter().any(|e| e.id == "distort.zigZag") && !draws_look_outline(object, &appearance, look) { + return None; + } + Some(appearance) +} + +/// How far, in points, an outline drawn with a reshaping effect may lie from its drawn look's +/// ([`draws_look_outline`]): the look's coordinates are written to a few decimals. +const OUTLINE_TOLERANCE: f64 = 0.25; + +/// How far, in points, a flattened outline in [`draws_look_outline`] may lie from its curves. +const OUTLINE_FLATNESS: f64 = OUTLINE_TOLERANCE / 10.0; + +/// How far apart, in points, [`draws_look_outline`] checks points along each flattened segment. +const OUTLINE_SPACING: f64 = OUTLINE_TOLERANCE / 2.0; + +/// How close, in points, each checked point must lie to the other flattened outline: every point +/// between two checked ones is within half the spacing of one, and both outlines are within the +/// flatness of their curves, so the curves are then within [`OUTLINE_TOLERANCE`] of each other. +const OUTLINE_POINT_LIMIT: f64 = OUTLINE_TOLERANCE - 2.0 * OUTLINE_FLATNESS - OUTLINE_SPACING / 2.0; + +/// Most point-to-segment distances worked out for one object, over all its look's outlines. +const MAX_OUTLINE_PAIRS: usize = 4_000_000; + +/// Does path or compound path `object` with `appearance`'s effects draw every outline of its drawn look +/// `look`, as `look` draws its own (each within [`OUTLINE_TOLERANCE`] of the other)? `false` for +/// anything else: a look holding other than paths, outlines too detailed to compare. +fn draws_look_outline(object: &Node, appearance: &Appearance, look: &Node) -> bool { + fn leaves(n: &Node, out: &mut Vec, depth: usize) -> bool { + match &n.kind { + NodeKind::Path { path, .. } => { + out.push(path.clone()); + true + } + NodeKind::Compound { children, .. } => { + out.push(vectorcraft_geom::PathData::new( + children.iter().filter_map(|c| c.path_data()).flat_map(|p| p.subpaths.iter().cloned()).collect(), + )); + true + } + NodeKind::Group { clip: false, .. } if depth < MAX_DEPTH => n.children().into_iter().flatten().all(|c| leaves(c, out, depth + 1)), + _ => false, + } + } + /// The segments of `paths` flattened, at most `max` of them. + fn segments(paths: &[vectorcraft_geom::PathData], max: usize) -> Option> { + let mut out = vec![]; + let (mut start, mut last) = (None, None); + let mut over = false; + for p in paths { + vectorcraft_geom::flatten(p.to_bezpath(), OUTLINE_FLATNESS, |el| { + let mut add = |a: kurbo::Point, b: kurbo::Point| { + if out.len() < max { + out.push(kurbo::Line::new(a, b)); + } else { + over = true; + } + }; + match el { + kurbo::PathEl::MoveTo(q) => (start, last) = (Some(q), Some(q)), + kurbo::PathEl::LineTo(q) => { + if let Some(l) = last { + add(l, q); + } + last = Some(q); + } + kurbo::PathEl::ClosePath => { + if let (Some(l), Some(s)) = (last, start) { + add(l, s); + } + last = start; + } + _ => {} + } + }); + } + (!over && !out.is_empty()).then_some(out) + } + /// Does every point of segments `a` lie close enough to segments `b` ([`OUTLINE_POINT_LIMIT`])? + /// Each segment is checked at both ends (the last point of an open outline starts no segment) + /// and at points at most [`OUTLINE_SPACING`] apart between them (two outlines can share their + /// vertices and join them differently). Each point's distance to each segment of `b` (a + /// projection onto it) is taken from `budget`: `false` once that runs out. + fn near(a: &[kurbo::Line], b: &[kurbo::Line], budget: &mut usize) -> bool { + use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest}; + let close = |p: kurbo::Point| b.iter().any(|t| t.nearest(p, 1e-6).distance_sq <= OUTLINE_POINT_LIMIT * OUTLINE_POINT_LIMIT); + for s in a { + let steps = (s.arclen(1e-6) / OUTLINE_SPACING).ceil(); + let steps = if steps.is_finite() && steps >= 1.0 { steps as usize } else { 1 }; + let Some(left) = budget.checked_sub(steps.saturating_add(1).saturating_mul(b.len())) else { return false }; + *budget = left; + if !(0..=steps).all(|k| close(s.eval(k as f64 / steps as f64))) { + return false; + } + } + true + } + /// The box round segments `lines` (`None` without any). + fn bounds(lines: &[kurbo::Line]) -> Option { + let first = lines.first()?.p0; + Some(lines.iter().fold(kurbo::Rect::from_points(first, first), |r, l| r.union_pt(l.p0).union_pt(l.p1))) + } + let (mut ours, mut theirs) = (vec![], vec![]); + if !matches!(object.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) || !leaves(object, &mut ours, 0) || !leaves(look, &mut theirs, 0) { + return false; + } + // The object's outline reshaped as it is drawn: its effects from its own bounds. + for path in &mut ours { + let bounds = kurbo::Shape::bounding_box(&path.to_bezpath()); + *path = vectorcraft_effects::apply_geometry(&appearance.effects, path, bounds); + } + let max = MAX_OUTLINE_PAIRS.isqrt(); + let Some(ours) = segments(&ours, max) else { return false }; + let Some(ours_box) = bounds(&ours) else { return false }; + // Two outlines each within the tolerance of the other have boxes as close: the boxes are + // compared first, then the points, from one budget for the object. + let boxed = |t: &[kurbo::Line]| { + let Some(r) = bounds(t) else { return false }; + [r.x0 - ours_box.x0, r.y0 - ours_box.y0, r.x1 - ours_box.x1, r.y1 - ours_box.y1].iter().all(|d| d.abs() <= OUTLINE_TOLERANCE) + }; + let mut budget = MAX_OUTLINE_PAIRS; + // Each of the look's outlines (a fill and a stroke draw the same one) is the object's. + theirs + .iter() + .all(|t| segments(std::slice::from_ref(t), max).is_some_and(|t| boxed(&t) && near(&t, &ours, &mut budget) && near(&ours, &t, &mut budget))) } /// A graphic style's appearance from art style `st`, on no object: `None` when the style isn't one @@ -1673,6 +1842,50 @@ mod tests { Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(fill, Paint::None, 0.0))) } + /// The outline check works from one budget for the object: a look of the outline drawn twice + /// (a fill and a stroke) matches, one drawn thousands of times gives up and keeps the drawn + /// look instead of comparing every copy. + #[test] + fn the_outline_check_has_one_budget_for_the_object() { + let zig = vectorcraft_doc::Effect { + id: "distort.zigZag".into(), + params: serde_json::json!({"size": 3.0, "relative": false, "ridges": 4, "points": "corner"}), + visible: true, + }; + let path = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 60.0)); + let appearance = Appearance { effects: vec![zig.clone()], ..Appearance::basic(Paint::None, Paint::None, 0.0) }; + let object = Node::path(NodeId(1), path.clone(), appearance.clone()); + let outline = vectorcraft_effects::apply_geometry(std::slice::from_ref(&zig), &path, Rect::new(0.0, 0.0, 100.0, 60.0)); + let look = |copies: u64| { + let drawn = (0..copies).map(|i| Arc::new(Node::path(NodeId(10 + i), outline.clone(), Appearance::default()))).collect(); + Node::group(NodeId(2), drawn) + }; + assert!(draws_look_outline(&object, &appearance, &look(2))); + let started = std::time::Instant::now(); + assert!(!draws_look_outline(&object, &appearance, &look(5_000))); + assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed()); + } + + /// The outline check holds for every point of the outlines, not only the points it checks: a + /// 0.25 pt line whose look has only short pieces over its ends, 0.24 pt away, leaves the + /// line's middle about 0.27 pt from the look, so the drawn look stays. The line drawn 0.1 pt + /// away matches. + #[test] + fn the_outline_check_holds_between_the_points_it_checks() { + use kurbo::Point; + use vectorcraft_geom::{PathData, SubPath}; + let appearance = Appearance::basic(Paint::None, Paint::None, 0.0); + let line = PathData::new(vec![SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(0.25, 0.0)], false)]); + let object = Node::path(NodeId(1), line, appearance.clone()); + let look = |pieces: &[[Point; 2]]| { + let drawn = PathData::new(pieces.iter().map(|p| SubPath::polyline(p, false)).collect()); + Node::group(NodeId(2), vec![Arc::new(Node::path(NodeId(3), drawn, Appearance::default()))]) + }; + let ends = [[Point::new(0.0, 0.24), Point::new(0.01, 0.24)], [Point::new(0.24, 0.24), Point::new(0.25, 0.24)]]; + assert!(!draws_look_outline(&object, &appearance, &look(&ends))); + assert!(draws_look_outline(&object, &appearance, &look(&[[Point::new(0.0, 0.1), Point::new(0.25, 0.1)]]))); + } + /// An image draws no stroke, so an image with a brush in its art style keeps its drawn look. #[test] fn an_image_with_a_brush_keeps_its_drawn_look() { diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index 0d87028ec0..4941fd62b8 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -188,10 +188,11 @@ pub(super) struct ArtStyle { /// It would be [`Self::simple`] but for a Stroke Style filter's variable width written as one /// centered array ([`centered_widths`]): an object whose drawn look is empty takes it with its profile. pub uneven: bool, - /// It is several fills and strokes in solid colours or gradients (strokes without a brush), - /// each with its own visibility, opacity and blend mode but no effects of its own, under only - /// the effects any object takes that don't move the outline: what a path or compound path is - /// read with when each gradient is placed as its drawn look has it (`read::ops`' `styled`). + /// It is several fills and strokes in solid colours, gradients or patterns (strokes without a + /// brush), each with its own visibility, opacity and blend mode but no effects of its own, under + /// only the effects any object takes that don't move the outline, and under none when a pattern + /// paints: what a path or compound path is read with when each gradient and pattern is placed as + /// its drawn look has it (`read::ops`' `styled`). pub stacked: bool, /// It is one Warp on the whole object, under fills and strokes that paint nothing and have no /// effects of their own: what an image is read with when its live warp draws as its drawn look @@ -1469,11 +1470,10 @@ fn stroke_item(f: &Filter, align: StrokeAlign) -> Result, ()> if !f.paints.0 { return Ok(None); } - // Dashes aligned to corners and path ends draw as the look's pieces: a solid end at each end - // and the pattern, fitted, between them. - if f.params.get("BSDashAdj").is_some_and(|v| *v != 0.0) { - return Err(()); - } + // Dashes aligned to corners and path ends (the switch in the stroke's dictionary): the look + // draws them fitted between solid ends, which the reader checks the stroke against before it + // takes it. + let aligned = f.params.get("BSDashAdj").is_some_and(|v| *v != 0.0); match &f.stroke { Some(p) if !f.gradient && f.pattern.is_none() => Ok(Some(StyleItem::Stroke { paint: p.clone(), @@ -1481,7 +1481,7 @@ fn stroke_item(f: &Filter, align: StrokeAlign) -> Result, ()> cap: f.cap, join: f.join, miter: f.miter, - dash: f.dash.clone(), + dash: f.dash.clone().map(|d| Dash { align_corners: aligned, ..d }), profile: width_profile(&f.arrays), align, brush: None, @@ -1599,9 +1599,9 @@ const ART_SETTINGS: [(&str, Kind, Option); 14] = [ ]; /// An Art brush's filter `f` as the stroke it paints, with its settings: `None` when it isn't a -/// stroke in a color, names no Art brush, holds an entry that isn't read or a setting that isn't a -/// number of its kind, or tints its art with a swatch's color: its drawn look stays. Whether the -/// brush draws as these settings is [`super::brush::draws_as`]'s to say. +/// stroke in a color, names no Art brush, or holds an entry that isn't read or a setting that isn't +/// a number of its kind: its drawn look stays. Whether the brush draws as these settings is +/// [`super::brush::draws_as`]'s to say. fn art_stroke(f: &Filter) -> Option { if !f.paints.0 || f.gradient @@ -1620,11 +1620,9 @@ fn art_stroke(f: &Filter) -> Option { for (slot, (key, kind, missing)) in settings.iter_mut().zip(ART_SETTINGS) { *slot = entry(f, key, kind).ok()?.or(missing)?; } + // Under Tints, a stroke color linked to a swatch tints the art in that swatch (a spot color's + // tints stay on its plate: `vectorcraft_brush::colorize`). let paint = f.stroke.clone()?; - // The tinted pieces are process colors, so a swatch's ink would be lost. - if settings[0] == 1.0 && matches!(paint, Paint::Solid { swatch: Some(_), .. }) { - return None; - } Some(StyleItem::Stroke { paint, width: f.width, @@ -1744,8 +1742,9 @@ impl Builder<'_> { /// Is `e`, on the whole object, an effect any object is read with? Of the Distort & Transform /// effects: Transform without copies (Random is never read), Twist, a Tweak that moves nothing, -/// Pucker & Bloat at 0, and Free Distort when its corners make a parallelogram (an affine map). -/// Zig Zag is left to type. Which objects Transform, Twist and Free Distort are read on is +/// Pucker & Bloat at 0, Free Distort when its corners make a parallelogram (an affine map), and Zig +/// Zag (on objects other than type only where it draws its drawn look's outline: `read::ops`' +/// `styled`). Which objects Transform, Twist and Free Distort are read on is /// `read::ops`' `moves_with`. fn any_object_takes(e: &Effect) -> bool { match e.id.as_str() { @@ -1762,7 +1761,8 @@ fn any_object_takes(e: &Effect) -> bool { | "path.outlineObject" | "path.outlineStroke" | "distort.twist" - | "distort.tweak" => true, + | "distort.tweak" + | "distort.zigZag" => true, // Copies are drawn as one path, its fills under all its strokes, where the file paints each // copy's fill and stroke in turn. "distort.transform" => e.params["copies"].as_i64() == Some(0), @@ -1861,9 +1861,15 @@ fn style(filters: &[Filter]) -> ArtStyle { && st.plain && !st.pathfinder && !st.moves_outline() - && st.items.iter().all(|i| matches!(i, StyleItem::Fill(_) | StyleItem::Gradient { .. } | StyleItem::Stroke { brush: None, .. })) + && st.items.iter().all(|i| { + matches!(i, StyleItem::Fill(_) | StyleItem::Gradient { .. } | StyleItem::Pattern { .. } | StyleItem::Stroke { brush: None, .. }) + }) && st.looks.iter().all(|l| l.effects.is_empty()) - && st.effects.iter().all(any_object_takes); + && st.effects.iter().all(any_object_takes) + // A pattern fill under the object's effects keeps the drawn look, a conservative rule: in + // one file a Scribble over a pattern fill drew unlike its look, its tiles placed as the + // look's are (why isn't established). + && (st.effects.is_empty() || !st.items.iter().any(|i| matches!(i, StyleItem::Pattern { .. }))); st.image_warp = st.plain && matches!(st.effects.as_slice(), [e] if e.id.starts_with("warp.")) && st.items.iter().all(|i| matches!(i, StyleItem::Fill(p) | StyleItem::Stroke { paint: p, .. } if p.is_none())) diff --git a/crates/eps/src/import/ai/style/tests.rs b/crates/eps/src/import/ai/style/tests.rs index 2b48fd268b..066473d43e 100644 --- a/crates/eps/src/import/ai/style/tests.rs +++ b/crates/eps/src/import/ai/style/tests.rs @@ -61,13 +61,17 @@ fn a_uniform_or_unreadable_width_profile_stays_a_live_stroke() { } #[test] -fn dashes_aligned_to_corners_keep_the_drawn_look() { - // GUARDS: the look holds the fitted pattern and the solid ends the style's dash array doesn't. +fn dashes_aligned_to_corners_read_as_aligned_dashes() { + // The look holds the fitted pattern, which the style's dash array doesn't: the reader takes the + // stroke only where VectorCraft's own fitting draws as that look. let data = b"/KnownStyle :\n(Stitches) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ /BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n2 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n\ /Dictionary : /NotRecorded ,\n1 /Bool (BSDashAdj) ,\n; (kAIBeautifulStrokesParamsDictKey) ,\n\ /StrokeStyle : 0 R\n0 0 0 0 0 0 1 XA\n1 J 0 j 2 w 10 M [5 10 ]0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n;\n"; - assert!(!art_styles(data)["Stitches"].plain); + let style = &art_styles(data)["Stitches"]; + assert!(style.plain, "{style:?}"); + let [StyleItem::Stroke { dash: Some(dash), .. }] = style.items.as_slice() else { panic!("{:?}", style.items) }; + assert_eq!((dash.pattern.as_slice(), dash.align_corners), ([5.0, 10.0].as_slice(), true)); } /// The style `Shade`: a Drop Shadow whose dictionary holds `keys`. @@ -1023,7 +1027,8 @@ fn any_object_takes_the_distort_effects_that_draw_as_its_drawn_look() { assert!(simple("Adobe Free Distort", &corners(src, [[0.2, 0.0], [1.2, 0.0], [0.0, -1.0], [1.0, -1.0]]))); assert!(!simple("Adobe Free Distort", &corners(src, [[0.2, 0.0], [1.2, 0.1], [0.0, -1.0], [1.0, -1.0]]))); assert!(!simple("Adobe Punk and Bloat", "-35 /Real (d_factor) ,\n")); - assert!(!simple("Adobe Zigzag", "")); + // Zig Zag: objects other than type check it against their drawn look (`read::ops`). + assert!(simple("Adobe Zigzag", "")); assert!(!simple("Adobe Transform", &format!("1 /Int (numCopies) ,\n{SWITCHES}"))); // With another effect, only type takes it. let chain = [basic("Adobe Twirl", "45 /Real (angle) ,\n"), basic("Adobe Offset Path", "4 /Real (ofst) ,\n0 /Int (jntp) ,\n4 /Real (mlim) ,\n")]; diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index f9ed3601d2..1c9595ccee 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -1260,6 +1260,191 @@ fn a_style_pattern_fill_is_placed_as_a_direct_one() { } } +/// An art style `Stacked` whose stack holds `filters` (basic filters, top first). +fn stacked_style(filters: &[String]) -> String { + format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(Stacked) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n{}\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n;\n%AI9_EndArtStyles\n", + filters.concat() + ) +} + +/// A fill filter painting with `paint` (operators). +fn fill_filter(paint: &str) -> String { + format!( + "/BasicFilter :\n(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n{paint}\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n" + ) +} + +/// A black stroke filter `width` wide. +fn stroke_filter(width: f64) -> String { + format!( + "/BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n\ + /StrokeStyle : 0 R\n0 0 0 1 0 0 0 XA\n0 J 0 j {width} w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n" + ) +} + +/// The layers of a file whose object (`own`, on `%_` lines) has the style `Stacked` and the drawn +/// look `look`. +fn stacked_object(look: &str, own: &str) -> String { + let own: String = own.lines().map(|l| format!("%_{l}\n")).collect(); + layer(&format!("0 Ae\nu\n{look}U\n{own}1 (Stacked) XW\n")) +} + +/// The pattern placement of `n`'s fill painting with a pattern. +fn pattern_xf(n: &Node) -> [f64; 6] { + n.appearance + .items + .iter() + .find_map(|i| match i.paint() { + Paint::Pattern { xf, .. } => Some(xf.as_coeffs()), + _ => None, + }) + .unwrap_or_else(|| panic!("no pattern fill: {:?}", n.appearance.items)) +} + +/// A path or compound path whose art style fills it with a pattern (as a stack of fills and strokes +/// can) comes in as itself with that fill, the pattern placed where the drawn look places it (not +/// where the style's own operands would), among the style's other fills and strokes in their order. +#[test] +fn a_path_with_a_style_pattern_fill_comes_in_as_the_path_with_it() { + let rect = rect_path(10.0, 20.0, 70.0, 80.0); + let hole = rect_path(30.0, 40.0, 50.0, 60.0); + // The style's operands and the look's differ: the look's placement is taken. + let (style_ops, look_ops) = ("0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]", "25 30 1.5 .75 30 1 45 10 0 [.8 .1 -.2 1.1 4 -6]"); + let pattern = fill_filter(&format!("(Dots) {style_ops} p")); + let look_xf = |shape: &str| { + let direct = read_ok(&format!("{DOTS}{}", layer(&format!("(Dots) {look_ops} p\n{shape}f\n")))); + pattern_xf(&art(&direct.doc)[0]) + }; + let close = |a: [f64; 6], b: [f64; 6]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9); + // The style's operands alone would place it elsewhere. + let style_xf = pattern_xf(&art(&read_ok(&format!("{DOTS}{}", layer(&format!("(Dots) {style_ops} p\n{rect}f\n")))).doc)[0]); + assert!(!close(style_xf, look_xf(&rect)), "{style_xf:?}"); + // A path filled with the pattern alone. + let look = format!("(Dots) {look_ops} p\n{rect}f\n"); + let r = read_ok(&format!("{}{DOTS}{}", stacked_style(std::slice::from_ref(&pattern)), stacked_object(&look, &format!("{rect}n")))); + let a = art(&r.doc); + assert!(matches!(a.as_slice(), [n] if matches!(n.kind, NodeKind::Path { .. })), "the path: {a:#?} {:?}", r.warnings); + assert!(close(pattern_xf(&a[0]), look_xf(&rect)), "{:?} {:?}", pattern_xf(&a[0]), look_xf(&rect)); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + // A compound path, the pattern over a solid fill and under a 3 unit stroke. + let style = stacked_style(&[stroke_filter(3.0), pattern.clone(), fill_filter("0 1 1 0 1 0 0 Xa")]); + let look = format!("{RED}*u\n{rect}f\n{hole}f\n*U\n(Dots) {look_ops} p\n*u\n{rect}f\n{hole}f\n*U\n"); + let own = format!("*u\n{rect}n\n{hole}n\n*U"); + let r = read_ok(&format!("{style}{DOTS}{}", stacked_object(&look, &own))); + let a = art(&r.doc); + assert!(matches!(a.as_slice(), [n] if matches!(n.kind, NodeKind::Compound { .. })), "the compound path: {a:#?} {:?}", r.warnings); + let items: Vec = a[0] + .appearance + .items + .iter() + .map(|i| match (i, i.paint()) { + (AppearanceItem::Fill(_), Paint::Pattern { .. }) => "pattern fill".into(), + (AppearanceItem::Fill(_), p) => format!("fill {:?}", p.color()), + (AppearanceItem::Stroke(s), _) => format!("stroke {}", s.width), + }) + .collect(); + assert_eq!(items, [format!("fill {:?}", Some(Color::rgb(1.0, 0.0, 0.0))), "pattern fill".into(), "stroke 3".into()]); + assert!(close(pattern_xf(&a[0]), look_xf(&format!("*u\n{rect}f\n{hole}f\n*U\n")))); +} + +/// A stack's pattern fill keeps the drawn look where the look doesn't fill with that pattern: its +/// placement isn't known. A look that only strokes with it doesn't place the fill either. +#[test] +fn a_style_pattern_fill_the_look_doesnt_paint_keeps_the_drawn_look() { + let rect = rect_path(10.0, 20.0, 70.0, 80.0); + let ops = "0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]"; + let pattern = fill_filter(&format!("(Dots) {ops} p")); + for (why, look) in + [("a look without the pattern", format!("{RED}{rect}f\n")), ("a look that strokes with it", format!("(Dots) {ops} P\n{rect}S\n"))] + { + let r = read_ok(&format!("{}{DOTS}{}", stacked_style(std::slice::from_ref(&pattern)), stacked_object(&look, &format!("{rect}n")))); + let a = art(&r.doc); + assert!(matches!(a.as_slice(), [n] if matches!(n.kind, NodeKind::Group { .. })), "{why}: the drawn look: {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{why}: {:?}", r.warnings); + } +} + +/// A stack that fills with one pattern twice keeps the drawn look: which of the look's placements is +/// whose isn't known. +#[test] +fn a_stack_with_one_pattern_twice_keeps_the_drawn_look() { + let rect = rect_path(10.0, 20.0, 70.0, 80.0); + let ops = "0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]"; + let pattern = fill_filter(&format!("(Dots) {ops} p")); + let look = format!("(Dots) {ops} p\n{rect}f\n(Dots) {ops} p\n{rect}f\n"); + let r = read_ok(&format!("{}{DOTS}{}", stacked_style(&[pattern.clone(), pattern]), stacked_object(&look, &format!("{rect}n")))); + let a = art(&r.doc); + assert!(matches!(a.as_slice(), [n] if matches!(n.kind, NodeKind::Group { .. })), "the drawn look: {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); +} + +/// A stack that fills with a pattern once, whose drawn look fills with it twice at different +/// placements, keeps the drawn look: which placement is the style's isn't known. A look filling with +/// it twice at the same placement still comes in as the path with that fill. +#[test] +fn a_look_placing_a_stacks_pattern_twice_keeps_the_drawn_look() { + let rect = rect_path(10.0, 20.0, 70.0, 80.0); + let ops = "0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]"; + let other = "25 30 1.5 .75 30 1 45 10 0 [.8 .1 -.2 1.1 4 -6]"; + let pattern = fill_filter(&format!("(Dots) {ops} p")); + let read = |second: &str| { + let look = format!("(Dots) {ops} p\n{rect}f\n(Dots) {second} p\n{rect}f\n"); + read_ok(&format!("{}{DOTS}{}", stacked_style(std::slice::from_ref(&pattern)), stacked_object(&look, &format!("{rect}n")))) + }; + let r = read(other); + let a = art(&r.doc); + assert!(matches!(a.as_slice(), [n] if matches!(n.kind, NodeKind::Group { .. })), "the drawn look: {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + let r = read(ops); + let a = art(&r.doc); + assert!(matches!(a.as_slice(), [n] if matches!(n.kind, NodeKind::Path { .. })), "the path: {a:#?} {:?}", r.warnings); +} + +/// A style's pattern fill under an effect on the object keeps the drawn look, a conservative rule +/// (in one file a Scribble over a pattern fill drew unlike its look; why isn't established). +#[test] +fn a_path_with_a_style_pattern_fill_under_an_effect_keeps_its_drawn_look() { + let rect = rect_path(10.0, 20.0, 70.0, 80.0); + let hidden = rect.replace('\n', "\n%_"); + let ops = "0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]"; + let shadow = "/BasicFilter :\n(Adobe Drop Shadow) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n2 /Int (blnd) ,\n0.43 /Real (opac) ,\n\ + 37 /Real (dark) ,\n-13 /Real (vert) ,\n11 /Real (horz) ,\n17 /Real (blur) ,\n\ + /FillStyle : 0 O\n0 0 0 0 0 1 0 Xa\n0 1 0 0 0 Xy\n0 J 0 j 1 w 10 M []0 d\n0 XR\n0 1 Xd\n/Def ;\n (sclr) ,\n0 /Int (csrc) ,\n; /Dict ;\n /Part ,\n"; + let style = tiled_style("Dots", ops); + // After the stack, in the object's chain. + let end = ";\n /Part ,\n;\n%AI9_EndArtStyles"; + assert!(style.contains(end)); + let style = style.replace(end, &format!(";\n /Part ,\n{shadow};\n%AI9_EndArtStyles")); + // The style reads, with its pattern fill and the shadow: what keeps the look is the rule. + let st = crate::import::ai::style::art_styles(style.as_bytes()); + let tiled = &st["Tiled"]; + assert!(tiled.plain && tiled.effects.len() == 1, "{tiled:?}"); + let look = format!("0 Ae\nu\n(Dots) {ops} p\n{rect}f\nU\n"); + let r = read_ok(&format!("{style}{DOTS}{}", layer(&format!("{look}%_{hidden}n\n1 (Tiled) XW\n")))); + let a = art(&r.doc); + assert!(matches!(a.as_slice(), [n] if matches!(n.kind, NodeKind::Group { .. })), "the drawn look: {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); +} + +/// Type whose style fills it with a pattern takes the placement from its drawn look wherever the look +/// paints with that pattern, a stroke of it too (as before paths took such styles): the look's +/// fills-only rule is the path stack's. +#[test] +fn type_with_a_style_pattern_fill_takes_a_stroke_only_looks_placement() { + let rect = rect_path(10.0, 20.0, 70.0, 80.0); + let (style_ops, look_ops) = ("0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]", "25 30 1.5 .75 30 1 45 10 0 [.8 .1 -.2 1.1 4 -6]"); + let look = format!("0 Ae\nu\n/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n(Dots) {look_ops} P\n{rect}S\nU\n"); + let own = "%_/AI11Text :\n%_0 /FreeUndo ,\n%_0 /FrameIndex ,\n%_0 /StoryIndex ,\n%_;\n"; + let styled = read_ok(&format!("{}{DOTS}{}", tiled_style("Dots", style_ops), layer(&format!("{look}{own}1 (Tiled) XW\n")))); + let stroked = read_ok(&format!("{DOTS}{}", layer(&format!("(Dots) {look_ops} P\n{rect}S\n")))); + let Paint::Pattern { xf: got, .. } = fill(&art(&styled.doc)[0]) else { panic!("{:?} {:?}", art(&styled.doc), styled.warnings) }; + let want = pattern_xf(&art(&stroked.doc)[0]); + assert!(got.as_coeffs().iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-9), "{got:?} {want:?}"); +} + /// An art style's pattern fill paints with the pattern under the name it is shown with. #[test] fn a_style_pattern_fill_paints_with_the_shown_name() { @@ -1549,6 +1734,42 @@ fn a_clipping_path_alone_in_a_group_clips_its_clipping_group() { assert_eq!(fill(&children[1]).color(), Some(Color::rgb(1.0, 0.0, 0.0))); } +/// Clipping paths grouped in a compound path (`*u u W n … U *U`, possibly nested in other groups) are +/// the compound path's subpaths, as its other grouped paths are: the compound clipping path, their union, clips its +/// clipping group, however many there are and wherever in the group it is written. +#[test] +fn clipping_paths_grouped_in_a_compound_path_are_its_subpaths() { + let square = rect_path(0.0, 0.0, 80.0, 80.0); + let (a, b, c) = (rect_path(0.0, 0.0, 10.0, 10.0), rect_path(30.0, 0.0, 40.0, 10.0), rect_path(60.0, 0.0, 70.0, 10.0)); + let clip = |p: &str| format!("{p}h\nW\nn\n"); + let bodies = [ + // One group of them, after the art. + format!("0 Ae\nq\n{RED}{square}f\n*u\n0 Ae\nu\n{}{}{}U\n*U\nQ\n", clip(&a), clip(&b), clip(&c)), + // Groups in a group, and one path straight in the compound path, before the art. + format!("0 Ae\nq\n*u\n0 Ae\nu\n0 Ae\nu\n{}{}U\n0 Ae\nu\n{}U\nU\n*U\n{RED}{square}f\nQ\n", clip(&a), clip(&b), clip(&c)), + format!("0 Ae\nq\n*u\n0 Ae\nu\n{}{}U\n{}*U\n{RED}{square}f\nQ\n", clip(&a), clip(&b), clip(&c)), + ]; + for body in &bodies { + let doc = read_ok(&layer(body)).doc; + let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{body}: {:?}", art(&doc)[0].kind) }; + assert_eq!(children.len(), 2, "{body}: {children:?}"); + let NodeKind::Compound { children: subpaths, .. } = &children[0].kind else { panic!("{body}: {:?}", children[0].kind) }; + assert_eq!(subpaths.len(), 3, "{body}: {subpaths:?}"); + assert!(subpaths.iter().all(|p| matches!(p.kind, NodeKind::Path { clipping: true, .. })), "{body}: {subpaths:?}"); + assert_eq!(fill(&children[1]).color(), Some(Color::rgb(1.0, 0.0, 0.0)), "{body}"); + } + // Hundreds of them, one union: not clipping groups nested past the document's depth limit. + let many = format!("0 Ae\nq\n{RED}{square}f\n*u\n0 Ae\nu\n{}U\n*U\nQ\n", clip(&a).repeat(300)); + let doc = read_ok(&layer(&many)).doc; + let NodeKind::Group { children, clip: true } = &art(&doc)[0].kind else { panic!("{:?}", art(&doc)[0].kind) }; + let NodeKind::Compound { children: subpaths, .. } = &children[0].kind else { panic!("{:?}", children[0].kind) }; + assert_eq!(subpaths.len(), 300); + // A group of clipping paths outside a compound path or a clipping group is read as before: a clipping group. + let alone = format!("0 Ae\nu\n{}{}U\n{RED}{square}f\n", clip(&a), clip(&b)); + let doc = read_ok(&layer(&alone)).doc; + assert!(matches!(art(&doc)[0].kind, NodeKind::Group { clip: true, .. }), "{:?}", art(&doc)[0].kind); +} + /// #1410: a compound path shows its last path's paint, and paths grouped in it stay its paths. #[test] fn compound_path_takes_its_last_paths_paint() { @@ -2507,6 +2728,37 @@ fn ai_variable_library_edge_cases() { assert_eq!(notes, ["the file's variable library couldn't be read: the Variables panel doesn't list it"]); } +/// The empty library a file can keep, its nodes named and nothing else (no value, no type, empty +/// attributes), has nothing to list: it comes in without a note. A node that has a value or a type +/// isn't empty, so the same skeleton with a value, or with a type, still gets the note. +#[test] +fn an_empty_variable_library_gives_no_note() { + // A node with a name and nothing else: its children, then its attributes, as `%_` lines. + fn bare(name: &str, attributes: &[&str], children: &[String]) -> String { + let close = |n: &str, key: &str| format!("{}%_; {key},\n", n.strip_suffix("%_;\n").unwrap_or(n)); + let attributes: String = attributes.iter().map(|a| close(&bare(a, &[], &[]), &format!("({a}) "))).collect(); + let children: String = children.iter().map(|c| close(c, "")).collect(); + format!( + "%_/XMLNode :\n%_/Dictionary :\n{attributes}%_; (xmlnode-attributes) ,\n%_/Array :\n{children}%_; (xmlnode-children) ,\n%_({name}) /String (xmlnode-nodename) ,\n%_;\n" + ) + } + let data_sets = bare("v:sampleDataSets", &["xmlns:v", "xmlns"], &[]); + let skeleton = bare("variableSets", &[], &[bare("variableSet", &["varSetName"], std::slice::from_ref(&data_sets))]); + let (vars, notes) = read_library(&skeleton); + assert_eq!(vars, vectorcraft_doc::Variables::default()); + assert!(notes.is_empty(), "{notes:?}"); + let unread = ["the file's variable library couldn't be read: the Variables panel doesn't list it"]; + // The same skeleton but for one entry of the data sets node: a value, then a type. + let with = |entry: &str| { + let data_sets = data_sets.replace("(xmlnode-nodename) ,\n", &format!("(xmlnode-nodename) ,\n{entry}")); + bare("variableSets", &[], &[bare("variableSet", &["varSetName"], &[data_sets])]) + }; + for entry in ["%_(x) /String (xmlnode-nodevalue) ,\n", "%_1 /Int (xmlnode-nodetype) ,\n"] { + let (_, notes) = read_library(&with(entry)); + assert_eq!(notes, unread, "{entry}"); + } +} + /// When the layers can't be read, or reading stops before the library, [`variables`] still reads /// it, for the file read from its PDF part. #[test] @@ -3741,6 +3993,70 @@ fn placed_files_are_linked_images_showing_their_preview() { assert!(read(stream(&layer("~\n")).as_bytes()).unwrap_err().contains("`~`")); } +/// Type made a clipping mask: a clipping group (`q` … `Q`) with no clipping path, whose last object +/// is a text object, is clipped by that type once its slot holds it, the type first as its +/// clipping path. Anything else stays as it was read. +#[test] +fn type_that_ends_a_clipping_group_without_a_clipping_path_clips_it() { + let text = |story: u32| format!("/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n{story} /StoryIndex ,\n;\n"); + let square = format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let clipper = format!("{RED}{}h W n\n", rect_path(2.0, 2.0, 8.0, 8.0)); + let r = read_ok(&layer(&format!("q\n{square}{}Q\n", text(4)))); + let a = art(&r.doc); + let [group] = a.as_slice() else { panic!("{a:#?}") }; + let slot = group.children().and_then(|c| c.last()).map(|n| n.id).unwrap(); + assert!(matches!(group.kind, NodeKind::Group { clip: false, .. }), "read as it is, until the slot holds its type"); + assert_eq!(r.type_clips.get(&group.id), Some(&slot)); + assert_eq!(r.warped_type.type_clips, r.type_clips, "envelopes' contents are clipped by their type too"); + // Filled with one text object, the slot's type clips the group. + let typed = |doc: &Document, one: bool| { + let mut layer = (*doc.layers[0]).clone(); + let mut n = 0; + let put = |n: &mut Node| { + if let NodeKind::Group { children, .. } = &mut n.kind + && let Some(last) = children.last_mut() + && last.id == slot + { + let t = Node::new( + vectorcraft_doc::NodeId(9_000), + NodeKind::Text(Box::new(vectorcraft_doc::TextObject::point(kurbo::Point::ZERO, "M", Default::default()))), + ); + if one { + *last = Arc::new(t); + } else { + let mut stroke = t.clone(); + stroke.id = vectorcraft_doc::NodeId(9_001); + *last = Arc::new(t); + children.push(Arc::new(stroke)); + } + } + }; + layer.children_mut().unwrap().iter_mut().for_each(|c| put(Arc::make_mut(c))); + let clipped = clip_by_type(&mut layer, &r.type_clips, &|s| (s == slot).then_some(vectorcraft_doc::NodeId(9_000)), &mut |_| n += 1); + (layer, clipped, n) + }; + let (layer_one, clipped, called) = typed(&r.doc, true); + assert_eq!((clipped, called), (1, 1)); + let g = &layer_one.children().unwrap()[0]; + let NodeKind::Group { children, clip: true } = &g.kind else { panic!("{g:#?}") }; + assert!(matches!(children[0].kind, NodeKind::Text(_)) && matches!(children[1].kind, NodeKind::Path { .. }), "{children:#?}"); + // Several objects in its place (the type and strokes round it): the group stays unclipped. + let (layer_two, clipped, _) = typed(&r.doc, false); + assert_eq!(clipped, 0); + assert!(matches!(layer_two.children().unwrap()[0].kind, NodeKind::Group { clip: false, .. })); + // A clipping path in the group clips it, not the type; type that isn't last doesn't; nor does a + // group (`u` … `U`) or the type a look draws. + for body in [ + format!("q\n{square}{clipper}{}Q\n", text(4)), + format!("q\n{}{square}Q\n", text(4)), + format!("u\n{square}{}U\n", text(4)), + format!("q\n{square}/AI11Text :\n1 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\nQ\n"), + ] { + let r = read_ok(&layer(&body)); + assert!(r.type_clips.is_empty(), "{body}: {:?}", r.type_clips); + } +} + #[test] fn text_objects_are_slots_named_after_their_story() { let words = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n3 /StoryIndex ,\n;\n%_/ArtDictionary :\n%_/XMLUID : (Title) ; (AI10_ArtUID) ,\n%_;\n"; @@ -6272,21 +6588,13 @@ fn a_stroke_offset_filter_keeps_its_strokes_style() { } /// A Stroke Offset stroke this doesn't read as a stroke keeps the object's drawn look: a switch -/// written as another kind, dashes aligned to corners and path ends, a gradient. +/// written as another kind, a gradient. #[test] fn a_stroke_offset_filter_with_a_stroke_this_does_not_read_keeps_the_drawn_look() { let outside = "0 /Bool (StrokeOffsetInside) ,\n"; let gradient = "0 R\nBb\n0 0 0 0 Bh\n2 (Red ramp) 0 0 90 1 1 0 0 1 0 0 1 Bg\n0 BB\n0 J 0 j 2 w 10 M []0 d\n0 XR\n1 0 Xd"; let cases = [ ("a switch written as a number", offset_stroke_style_with("Edge", "1 /Int (StrokeOffsetInside) ,\n", OFFSET_STROKE)), - ( - "dashes aligned to corners", - offset_stroke_style_with( - "Edge", - &format!("{outside}/Dictionary : /NotRecorded ,\n1 /Bool (BSDashAdj) ,\n; (kAIBeautifulStrokesParamsDictKey) ,\n"), - &OFFSET_STROKE.replace("[]0 d", "[5 10 ]0 d"), - ), - ), ("a gradient", offset_stroke_style_with("Edge", outside, gradient)), ]; for (why, style) in cases { @@ -6295,6 +6603,26 @@ fn a_stroke_offset_filter_with_a_stroke_this_does_not_read_keeps_the_drawn_look( } } +/// A Stroke Offset stroke with dashes aligned to corners and path ends reads as such a stroke, +/// outside the path; the object takes it only where it draws as its drawn look. Here the look (a +/// filled square) draws otherwise, so the look check keeps the drawn look. +#[test] +fn a_stroke_offset_with_dashes_aligned_to_corners_unlike_its_look_keeps_the_look() { + use crate::import::ai::style::StyleItem; + use vectorcraft_doc::StrokeAlign; + let keys = "0 /Bool (StrokeOffsetInside) ,\n/Dictionary : /NotRecorded ,\n1 /Bool (BSDashAdj) ,\n; (kAIBeautifulStrokesParamsDictKey) ,\n"; + let style = offset_stroke_style_with("Edge", keys, &OFFSET_STROKE.replace("[]0 d", "[5 10 ]0 d")); + let styles = crate::import::ai::style::art_styles(style.as_bytes()); + let Some(StyleItem::Stroke { dash: Some(dash), align, .. }) = styles["Edge"].items.iter().find(|i| matches!(i, StyleItem::Stroke { .. })) else { + panic!("{:?}", styles["Edge"]) + }; + assert_eq!((dash.pattern.as_slice(), dash.align_corners, *align), ([5.0, 10.0].as_slice(), true, StrokeAlign::Outside)); + let r = read_ok(&format!("%AI9_BeginArtStyles\n{style}%AI9_EndArtStyles\n{}", layer(&styled_square("Edge")))); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + let a = art(&r.doc); + assert!(matches!(a.as_slice(), [n] if matches!(n.kind, NodeKind::Group { .. })), "the drawn look: {a:#?}"); +} + /// A listed `[Default]` style whose stroke is aligned outside comes in as the default graphic /// style with that stroke. #[test] @@ -7338,6 +7666,96 @@ fn an_object_with_a_distort_effect_drawn_another_way_keeps_its_drawn_look() { } } +#[test] +fn a_path_with_zig_zag_comes_in_as_itself_where_its_look_has_that_outline() { + // GUARDS: Zig Zag on a path came in as its drawn look even where the live effect draws the same outline. + let keys = "3 /Real (amount) ,\n1 /Real (absoluteness) ,\n2 /Real (ridges) ,\n0 /Real (roundness) ,\n"; + let zig = vectorcraft_doc::Effect { + id: "distort.zigZag".into(), + params: serde_json::json!({"size": 3.0, "relative": false, "ridges": 2, "points": "corner"}), + visible: true, + }; + // The square as the document has it (y up in the file, down in the document). + let plain = read_ok(&layer(&format!("{RED}{}f\n", rect_path(20.0, 20.0, 60.0, 50.0)))); + let square = art(&plain.doc)[0].path_data().unwrap().clone(); + let to_file = |p: Point| { + let start = square.subpaths[0].anchors[0].p; + Point::new(p.x - start.x + 20.0, start.y - p.y + 20.0) + }; + let outline = vectorcraft_effects::apply_geometry(std::slice::from_ref(&zig), &square, square.bounds().unwrap()); + // The look: the outline the effect draws, as straight segments. + let ops = |shift: f64| -> String { + let mut out = String::new(); + for sp in &outline.subpaths { + for (i, a) in sp.anchors.iter().enumerate() { + let p = to_file(a.p); + out.push_str(&format!("{:.4} {:.4} {}\n", p.x + shift, p.y, if i == 0 { "m" } else { "L" })); + } + } + out + }; + let hidden_rect = rect_path(20.0, 20.0, 60.0, 50.0).replace('\n', "\n%_"); + let object = |look: &str| format!("0 Ae\nu\n0 0 0 0 0 0 1 Xa\n{look}f\nU\n%_{hidden_rect}f\n1 (Bent) XW\n"); + let r = read_ok(&format!("{}{}", distort_styles("Adobe Zigzag", keys, BLUE_FILL), layer(&object(&ops(0.0))))); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the object, not its look: {a:#?}"); + let e = &a[0].appearance.effects; + assert_eq!(e.len(), 1, "{e:?}"); + assert_eq!( + (e[0].id.as_str(), &e[0].params), + ("distort.zigZag", &serde_json::json!({"size": 3.0, "relative": false, "ridges": 2, "points": "corner"})) + ); + // A look whose ridges lie elsewhere (here 1 pt to the right) keeps the drawn look. + let r = read_ok(&format!("{}{}", distort_styles("Adobe Zigzag", keys, BLUE_FILL), layer(&object(&ops(1.0))))); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + assert!(matches!(art(&r.doc)[0].kind, NodeKind::Group { .. })); + // An open path (filled without closing it, `F`): its look's outline matches, and a look whose + // last point lies 3 pt away from where the effect ends it keeps the drawn look. + let open_path = "20 20 m\n60 20 L\n60 50 L\n"; + let plain = read_ok(&layer(&format!("{RED}{open_path}F\n"))); + let open = art(&plain.doc)[0].path_data().unwrap().clone(); + assert!(!open.subpaths[0].closed); + let start = open.subpaths[0].anchors[0].p; + let outline = vectorcraft_effects::apply_geometry(std::slice::from_ref(&zig), &open, open.bounds().unwrap()); + let ops = |last_shift: f64| -> String { + let mut out = String::new(); + for sp in &outline.subpaths { + for (i, a) in sp.anchors.iter().enumerate() { + let shift = if i + 1 == sp.anchors.len() { last_shift } else { 0.0 }; + let p = Point::new(a.p.x - start.x + 20.0 + shift, start.y - a.p.y + 20.0); + out.push_str(&format!("{:.4} {:.4} {}\n", p.x, p.y, if i == 0 { "m" } else { "L" })); + } + } + out + }; + let hidden_open = open_path.replace('\n', "\n%_"); + let object = |look: &str| format!("0 Ae\nu\n0 0 0 0 0 0 1 Xa\n{look}F\nU\n%_{hidden_open}F\n1 (Bent) XW\n"); + let r = read_ok(&format!("{}{}", distort_styles("Adobe Zigzag", keys, BLUE_FILL), layer(&object(&ops(0.0))))); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + let r = read_ok(&format!("{}{}", distort_styles("Adobe Zigzag", keys, BLUE_FILL), layer(&object(&ops(3.0))))); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + // A Zig Zag of no size on an open path through the corners of its look's square, joined + // across it: the vertices match, the segments between them don't, so the drawn look stays. + let flat = "0 /Real (amount) ,\n1 /Real (absoluteness) ,\n0 /Real (ridges) ,\n0 /Real (roundness) ,\n"; + let bowtie = "%_20 20 m\n%_60 50 L\n%_60 20 L\n%_20 50 L\n%_F\n"; + let crossed = format!("0 Ae\nu\n0 0 0 0 0 0 1 Xa\n{}f\nU\n{bowtie}1 (Bent) XW\n", rect_path(20.0, 20.0, 60.0, 50.0)); + let r = read_ok(&format!("{}{}", distort_styles("Adobe Zigzag", flat, BLUE_FILL), layer(&crossed))); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + // A look worked out by hand rather than by the effect: Zig Zag of 3 pt with one ridge per + // segment and corner points, on a line from (20, 20) to (60, 20), puts the line's ends 3 pt up + // the page and its middle 3 pt down. The same look mirrored keeps the drawn look. + let one = "3 /Real (amount) ,\n1 /Real (absoluteness) ,\n1 /Real (ridges) ,\n0 /Real (roundness) ,\n"; + let line = "20 20 m\n60 20 L\n".replace('\n', "\n%_"); + let object = |look: &str| format!("0 Ae\nu\n0 0 0 0 0 0 1 Xa\n{look}F\nU\n%_{line}F\n1 (Bent) XW\n"); + let r = read_ok(&format!("{}{}", distort_styles("Adobe Zigzag", one, BLUE_FILL), layer(&object("20 23 m\n40 17 L\n60 23 L\n")))); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + assert!(matches!(art(&r.doc)[0].kind, NodeKind::Path { .. }), "{:#?}", art(&r.doc)); + let r = read_ok(&format!("{}{}", distort_styles("Adobe Zigzag", one, BLUE_FILL), layer(&object("20 17 m\n40 23 L\n60 17 L\n")))); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); +} + /// The gradient `G`, white to black, defined for a document. const GRADIENT_G: &str = "%AI5_BeginGradient: (G)\n(G) 0 2 Bd\n[\n%_1 0 50 0 Bs\n%_0 0 50 100 Bs\nBD\n%AI5_EndGradient\n"; @@ -8746,7 +9164,7 @@ fn warped_type_on_the_page_spends_what_is_left_of_the_budget() { let copy = |w: &super::envelope::WarpedLook| super::envelope::WarpedLook { slot: w.slot, look: w.look.clone(), left_out: None }; let page = Some(Rect::new(0.0, 60.0, 60.0, 100.0)); let settle = |w: &super::envelope::WarpedLook, spent| { - let warped = super::envelope::WarpedType { looks: vec![copy(w)], envelopes: vec![], checks: 1, spent, page, alone: None }; + let warped = super::envelope::WarpedType { looks: vec![copy(w)], checks: 1, spent, page, ..Default::default() }; warped.settle(&mut doc.clone(), Some, &Default::default(), &mut vec![]) }; let spent = || super::envelope::Spent { any: MAX_DIFFERENCE / 2.0, solid: MAX_SOLID_DIFFERENCE / 2.0 }; @@ -9519,6 +9937,22 @@ fn a_blend_comes_in_as_a_live_blend() { assert!(!s.warnings.iter().any(|w| w == super::blend::DRAWN), "{:?}", s.warnings); } +/// A blend in an opacity mask's art is written on `%_` lines, its record's hex digits on `%_%` +/// lines: it comes in live there too. +#[test] +fn a_blend_in_an_opacity_mask_comes_in_live() { + let body = blend_file("%_10 50 m\n%_110 50 L\n", [Some("A"), Some("B")], &blend_record(&['A', 'B'])); + let mask_art: String = body.lines().map(|l| if l.starts_with("%_") { format!("{l}\n") } else { format!("%_{l}\n") }).collect(); + assert!(mask_art.contains("\n%_%44434241"), "{mask_art}"); + let mask = format!("%_/ArtDictionary :\n%_/Mask :\n%_X=\n%_u\n{mask_art}%_U\n%_X+\n%_(Art) ,\n%_; (AI9_Mask) ,\n%_;\n"); + let s = read_ok(&layer(&format!("{RED}0 0 m\n0 80 L\n80 80 L\n80 0 L\nf\n{mask}"))); + let m = art(&s.doc)[0].extras().mask.clone().expect("a mask"); + let blend = m.art.children().and_then(|c| c.first()).cloned().unwrap_or(m.art.clone()); + let NodeKind::Blend { children, spec } = &blend.kind else { panic!("a live blend: {:?} {:?}", blend.kind, s.warnings) }; + assert_eq!((children.len(), spec.spacing), (2, vectorcraft_doc::live::BlendSpacing::Steps(3))); + assert!(!s.warnings.iter().any(|w| w == super::blend::DRAWN), "{:?}", s.warnings); +} + /// A blend whose spine was never edited has no spine written, only its keys: its spine is the /// straight line between the keys' centers, in the record's order, and the blend comes in live. /// With the record naming the keys in their order (here the left key, named `B`, first) the blend @@ -10727,11 +11161,11 @@ fn a_gradients_br_is_not_a_brush() { /// The Brush Options codes for how a Calligraphic brush's values vary: Tilt, Bearing and Rotation /// are the pen's other channels (#372: a 6D Art Pen brush varies its diameter with the pressure, -/// its roundness with the bearing and its angle with the barrel's rotation). The stylus wheel isn't -/// read: it varies at random, as an unknown code does. +/// its roundness with the bearing and its angle with the barrel's rotation), and code 3 is an +/// airbrush pen's finger wheel. An unknown code varies at random. #[test] fn a_calligraphic_brushs_pen_channels_come_in_by_their_codes() { - use vectorcraft_brush::Variation::{Bearing, Fixed, Pressure, Random, Rotation, Tilt}; + use vectorcraft_brush::Variation::{Bearing, Fixed, Pressure, Random, Rotation, StylusWheel, Tilt}; let modes = |params: &str| { let d = brush::parse_tool_object(brush::Tool::Calligraphic, "Pen", params).unwrap(); let brush::DraftKind::Calligraphic(c) = d.kind else { panic!("{d:?}") }; @@ -10739,8 +11173,9 @@ fn a_calligraphic_brushs_pen_channels_come_in_by_their_codes() { }; assert_eq!(modes("1 51 69 13 57 -346 14 2 5 6 0"), [Rotation, Bearing, Pressure]); assert_eq!(modes("1 2 6 40 60 -30 10 4 4 4 0"), [Tilt, Tilt, Tilt]); - assert_eq!(modes("1 2 6 40 60 -30 10 3 3 3 0"), [Random, Random, Random], "the stylus wheel"); - assert_eq!(modes("1 4 4 50 50 10 10 3 9 9 0"), [Fixed, Fixed, Fixed], "nothing to vary"); + assert_eq!(modes("1 2 6 40 60 -30 10 3 3 3 0"), [StylusWheel, StylusWheel, StylusWheel], "the stylus wheel"); + assert_eq!(modes("1 2 6 40 60 -30 10 7 9 7 0"), [Random, Random, Random], "unknown codes"); + assert_eq!(modes("1 4 4 50 50 10 10 7 9 9 0"), [Fixed, Fixed, Fixed], "nothing to vary"); } /// A 6D Art Pen brush: diameter 4 to 8 with the pressure, roundness 30 to 50 with the bearing and @@ -11160,6 +11595,39 @@ fn an_art_brush_with_options_comes_in_brushed_with_them() { assert!(filled(&along, 50.0, -2.0) && filled(&along, 90.0, 2.0) && !filled(&along, 10.0, 2.0), "along: the narrow block at the end"); } +/// A path whose Art brush tints its art with a stroke color linked to a swatch (Tints, a spot +/// color) comes in brushed: the brush draws the art in tints of that swatch, linked to it, so the +/// spot ink stays on its plate. +#[test] +fn an_art_brush_tinting_with_a_spot_color_comes_in_brushed_in_tints_of_it() { + let def = format!("{}{}", lopsided_art("Ribbon art"), plugin_object(ART_BRUSH, "Ribbon", RIBBON)); + let style = art_style("Ribbon", 1.0, &STRETCHED, "").replace("0 1 1 0 1 0 0 XA", "0 0 0 0 1 0.5 0 (Brand orange) 0 1 XK"); + let r = read_ok(&format!("{def}{style}{}", layer(&brushed_path()))); + let a = art(&r.doc); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the path, not its look: {a:#?}"); + let st = a[0].appearance.stroke().cloned().unwrap(); + assert_eq!(st.brush.as_deref(), Some("Ribbon")); + let Paint::Solid { swatch: Some(swatch), .. } = &st.paint else { panic!("a swatch: {:?}", st.paint) }; + assert_eq!(swatch, "Brand orange"); + let lib = vectorcraft_brush::library(&r.doc); + let ribbon = lib.iter().find(|b| b.name == "Ribbon").unwrap(); + let line = kurbo::BezPath::from_vec(vec![kurbo::PathEl::MoveTo(Point::new(0.0, 0.0)), kurbo::PathEl::LineTo(Point::new(100.0, 0.0))]); + let mut fills = vec![]; + for n in vectorcraft_brush::stroke_pieces(&r.doc, ribbon, &line, &st) { + n.walk(&mut |c| { + if let Some(f) = c.appearance.fill() { + fills.push(f.paint.clone()); + } + }); + } + // The art is black: each piece is the swatch at the stroke's own tint. + assert!(!fills.is_empty()); + for p in &fills { + assert!(matches!(p, Paint::Solid { swatch: Some(s), tint, .. } if s == "Brand orange" && (*tint - 1.0).abs() < 1e-6), "{p:?}"); + } + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); +} + /// An Art brushed path keeps its drawn look when the brush wouldn't draw it the way the file does: /// its settings differ from the brush's, the brush's are ones VectorCraft doesn't draw as the file /// does, its art isn't read, or the brush isn't one the panel keeps. @@ -11187,7 +11655,6 @@ fn an_art_brushed_path_the_brush_cant_draw_keeps_its_drawn_look() { let cases = [ ("a switch written as another kind", good.clone(), art_style("Ribbon", 1.0, &malformed, "")), ("art in a pattern", format!("{dots}{patterned}{}", plugin_object(ART_BRUSH, "Ribbon", RIBBON)), plain_style.clone()), - ("tints of a swatch's ink", good.clone(), plain_style.replace("0 1 1 0 1 0 0 XA", "0 0 0 0 1 0.5 0 (Brand orange) 0 1 XK")), ( "art with no length", format!( diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index 96a408ae7d..ef765c5909 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -1189,6 +1189,12 @@ impl Story { self.text.len() } + /// Is frame `frame` of the story point type with nothing but spaces and line ends (its last + /// `\r` left out), which [`Self::node`] doesn't make: it draws nothing. + pub(super) fn blank_point(&self, frame: usize) -> bool { + frame == 0 && matches!(self.frames.first(), Some(FrameKind::Point(_))) && self.is_blank() + } + /// The point frame's matrix (the first frame's, when it is one), else the identity. fn matrix(&self) -> [f64; 6] { match self.frames.first() { @@ -1260,6 +1266,24 @@ impl Story { /// document), or `None` for type that is mirrored, has no size, or a frame past the first of /// threaded type (the first frame holds the whole story). pub(super) fn node(&self, id: NodeId, frame: usize, template: (f64, f64), to_doc: Affine) -> Option { + self.made_node(id, frame, template, to_doc, false) + } + + /// For a blank story (nothing but spaces and line ends) in an area frame or on a path, an empty + /// text object with that frame or path, as [`Self::node`] would make it, as VectorCraft's Type + /// tool keeps such an empty frame (#85, #154). Its text is the story's, spaces kept. `None` for + /// any other story or frame. + pub(super) fn blank_frame_node(&self, id: NodeId, frame: usize, template: (f64, f64), to_doc: Affine) -> Option { + self.is_blank().then(|| self.made_node(id, frame, template, to_doc, true)).flatten() + } + + /// Is the story's text nothing but spaces and line ends (`\r`, and `\x03`, a line break)? + pub(super) fn is_blank(&self) -> bool { + self.text.chars().all(|c| c.is_whitespace() || c == '\x03') + } + + /// [`Self::node`]; with `blank_frame`, a blank story in an area frame or on a path is made too. + fn made_node(&self, id: NodeId, frame: usize, template: (f64, f64), to_doc: Affine, blank_frame: bool) -> Option { let kind = self.frames.get(frame)?; let threaded = frame > 0; let (scale, xf, kind) = match kind { @@ -1301,7 +1325,9 @@ impl Story { }) .collect() }; - if text.trim().is_empty() && !threaded { + // A blank story isn't made here: the page may still have type for its object. What is left + // of one, an area frame or a path, is made by [`Self::blank_frame_node`]. + if text.trim().is_empty() && !threaded && !(blank_frame && !matches!(kind, TextKind::Point)) { return None; } // The text document measures in the art's units too: the document's scale carries its diff --git a/crates/eps/src/import/graphics/ops.rs b/crates/eps/src/import/graphics/ops.rs index 78a214b410..1afd09eae2 100644 --- a/crates/eps/src/import/graphics/ops.rs +++ b/crates/eps/src/import/graphics/ops.rs @@ -1,4 +1,4 @@ -use super::paint::is_mesh; +use super::paint::{is_mesh, polygon, shading_extent}; use super::state::{GState, Space}; use super::{ Affine, Color, FillRule, Interp, Key, LineCap, LineJoin, MAX_DASH_ENTRIES, MAX_DASHES, MAX_GSAVE, MAX_PATH, Obj, Op, Paint, Point, PsError, Rc, @@ -519,29 +519,43 @@ impl Interp<'_> { } self.stroke_path(bp)?; } - ShFill => { - let d = self.pop_dict()?; - if self.g.null { - return Ok(()); - } - if is_mesh(&d) { - let m = self.xf(); - return self.mesh_fill(&d, m); - } - let m = self.xf(); - if let Some(g) = self.gradient(&d, m)? { - let area = self.clip_bounds()?; - let paint = Paint::Gradient(Box::new(g)); - let clips = self.g.clips.clone(); - self.out.fill(area.to_path(0.1), FillRule::NonZero, paint, self.g.overprint, &clips); - if let Some((_, n)) = self.out.drawn.last() { - let id = n.id; - self.out.shadings.insert(id); - } - } - } + ShFill => self.shfill()?, _ => self.data_op(op)?, } Ok(()) } + + /// `shfill`: shading `sh` over the clip, as a gradient mesh or a gradient fill. + fn shfill(&mut self) -> Res { + let d = self.pop_dict()?; + if self.g.null { + return Ok(()); + } + if is_mesh(&d) { + let m = self.xf(); + return self.mesh_fill(&d, m); + } + let m = self.xf(); + if let Some(g) = self.gradient(&d, m)? { + let area = self.clip_bounds()?; + // Not extended, it paints only between its ends. + let extent = shading_extent(&d, m, area); + let path = match &extent { + Some(pts) if pts.len() < 3 => return Ok(()), + Some(pts) => polygon(pts), + None => area.to_path(0.1), + }; + let paint = Paint::Gradient(Box::new(g)); + let clips = self.g.clips.clone(); + self.out.fill(path, FillRule::NonZero, paint, self.g.overprint, &clips); + // Only a fill of the whole clip can stand in for the clip's shape. + if extent.is_none() + && let Some((_, n)) = self.out.drawn.last() + { + let id = n.id; + self.out.shadings.insert(id); + } + } + Ok(()) + } } diff --git a/crates/eps/src/import/graphics/paint.rs b/crates/eps/src/import/graphics/paint.rs index 156b6e421e..037cf1d213 100644 --- a/crates/eps/src/import/graphics/paint.rs +++ b/crates/eps/src/import/graphics/paint.rs @@ -450,6 +450,135 @@ fn is_gradient(sh: &DictRef) -> bool { matches!(sh.borrow().get(&Key::name("ShadingType")).and_then(Obj::as_num), Some(2.0 | 3.0)) } +/// How far (points) the sides of the polygon a radial shading's circle is cut to may lie inside it. +const RING_TOLERANCE: f64 = 0.01; +/// Most sides of that polygon. +const MAX_RING: usize = 1024; + +/// The part of `area` (in the document) that axial or radial shading `sh`, mapped into the +/// document by `m`, paints, as a convex polygon; `None` when it paints all of it. Without +/// `Extend` an axial shading paints only between the lines through its ends across its axis, and +/// a radial one only over its circles (PLRM 3rd ed. §4.9.3, shading types 2 and 3: `Extend` +/// defaults to `[false false]`). A radial shading extended at one end only, or starting from a +/// circle with a radius, is not bounded here (it paints all of `area`). +pub(super) fn shading_extent(sh: &DictRef, m: Affine, area: Rect) -> Option> { + let d = sh.borrow(); + let nums = |k: &str| -> Vec { + d.get(&Key::name(k)).and_then(Obj::items).map(|i| i.borrow().iter().filter_map(Obj::as_num).collect()).unwrap_or_default() + }; + let extend: Vec = d + .get(&Key::name("Extend")) + .and_then(Obj::items) + .map(|i| i.borrow().iter().map(|o| matches!(o, Obj::Bool(true))).collect()) + .unwrap_or_default(); + let (e0, e1) = (extend.first().copied().unwrap_or(false), extend.get(1).copied().unwrap_or(false)); + if (e0 && e1) || area.width() <= 0.0 || area.height() <= 0.0 || m.determinant().abs() < 1e-12 || !m.as_coeffs().iter().all(|v| v.is_finite()) { + return None; + } + let inv = m.inverse(); + // `area` in the shading's own space, where its axis and circles are. + let corners: Vec = + [(area.x0, area.y0), (area.x1, area.y0), (area.x1, area.y1), (area.x0, area.y1)].map(|(x, y)| inv * Point::new(x, y)).to_vec(); + let mut poly = corners.clone(); + let c = nums("Coords"); + let at = |i: usize| c.get(i).copied().filter(|v| v.is_finite()).unwrap_or(0.0); + match d.get(&Key::name("ShadingType")).and_then(Obj::as_num) { + Some(2.0) => { + let (p0, p1) = (Point::new(at(0), at(1)), Point::new(at(2), at(3))); + let axis = p1 - p0; + if axis.hypot2() < 1e-18 { + return None; + } + if !e0 { + poly = clip_half(&poly, |p| (p - p0).dot(axis)); + } + if !e1 { + poly = clip_half(&poly, |p| (p1 - p).dot(axis)); + } + } + Some(3.0) if !e0 && !e1 && at(2) <= 0.0 && at(5) > 0.0 => { + // The circles from a point to a circle cover the hull of that point and circle. + let (p0, c1, r1) = (Point::new(at(0), at(1)), Point::new(at(3), at(4)), at(5)); + // Enough sides that each lies within `RING_TOLERANCE` of the circle in the document + // (the radius scaled by the most `m` stretches any direction), from 64 to `MAX_RING`. + let [a, b, c, d, ..] = m.as_coeffs(); + let (sum, det) = (a * a + b * b + c * c + d * d, a * d - b * c); + let stretch = ((sum + (sum * sum - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt(); + let r = r1 * stretch; + let sides = (std::f64::consts::PI / (1.0 - RING_TOLERANCE / r).clamp(-1.0, 1.0).acos()).ceil(); + let sides = if sides.is_finite() { (sides as usize).clamp(64, MAX_RING) } else { MAX_RING }; + let ring: Vec = (0..sides).map(|i| c1 + Vec2::from_angle(i as f64 * std::f64::consts::TAU / sides as f64) * r1).collect(); + for edge in hull(&[ring, vec![p0]].concat()).windows(2) { + if let [a, b] = edge { + let (a, b) = (*a, *b); + poly = clip_half(&poly, |p| (b - a).cross(p - a)); + } + } + } + _ => return None, + } + // Nothing cut: it paints the whole area. + if poly.len() == 4 && poly.iter().zip(&corners).all(|(a, b)| (*a - *b).hypot2() < 1e-18) { + return None; + } + Some(poly.into_iter().map(|p| m * p).collect()) +} + +/// Convex polygon `poly` cut to where `f` (a linear function) is zero or more. +fn clip_half(poly: &[Point], f: impl Fn(Point) -> f64) -> Vec { + let mut out = Vec::with_capacity(poly.len() + 1); + for (i, &a) in poly.iter().enumerate() { + let Some(&b) = poly.get((i + 1) % poly.len()) else { continue }; + let (fa, fb) = (f(a), f(b)); + if fa >= 0.0 { + out.push(a); + } + if (fa >= 0.0) != (fb >= 0.0) { + out.push(a.lerp(b, fa / (fa - fb))); + } + } + out +} + +/// The convex hull of `pts`, counter-clockwise, its first point repeated at the end. +fn hull(pts: &[Point]) -> Vec { + let mut p = pts.to_vec(); + p.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y))); + let mut h: Vec = Vec::with_capacity(p.len() * 2); + let turn = |h: &[Point], q: Point| match h { + [.., a, b] => (*b - *a).cross(q - *a) <= 0.0, + _ => false, + }; + for &q in &p { + while turn(&h, q) { + h.pop(); + } + h.push(q); + } + let lower = h.len() + 1; + for &q in p.iter().rev().skip(1) { + while h.len() >= lower && turn(&h, q) { + h.pop(); + } + h.push(q); + } + h +} + +/// A closed path through `pts`. +pub(super) fn polygon(pts: &[Point]) -> kurbo::BezPath { + let mut bp = kurbo::BezPath::new(); + for (i, p) in pts.iter().enumerate() { + if i == 0 { + bp.move_to(*p); + } else { + bp.line_to(*p); + } + } + bp.close_path(); + bp +} + /// Is shading `sh` one [`Interp::mesh_fill`] paints? pub(super) fn is_mesh(sh: &DictRef) -> bool { matches!(sh.borrow().get(&Key::name("ShadingType")).and_then(Obj::as_num), Some(1.0 | 4.0 | 5.0 | 6.0 | 7.0)) diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 86d6976d89..2cba146548 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -329,6 +329,7 @@ pub(super) fn build_weighing( unread, unread_elsewhere, slot_names, + type_clips, restyled, placeholders, placed_elsewhere, @@ -527,14 +528,15 @@ pub(super) fn build_weighing( let mut made = vec![]; let mut filled = std::collections::HashMap::new(); fill_slots(&mut doc, &mut layers, &mut content.into_iter(), &slot_names, &mut empty, &mut made, &mut vec![], &mut filled); + clip_by_type(&mut layers, &type_clips, &filled); doc.layers = layers; made.sort(); - let threaded_frames: BTreeSet = - made.chunk_by(|a, b| a.0 == b.0).filter(|thread| thread.len() > 1).flatten().map(|(_, _, id)| *id).collect(); + let threads = threads_of(&made); + let threaded_frames: BTreeSet = threads.iter().flat_map(|(_, ids)| ids.iter().copied()).collect(); if !unread.is_empty() { let Some(frame) = frame.as_ref() else { return Err(unread_error(&unread)) }; let mut copied = BTreeSet::new(); - let kinds = replace_unread(&mut doc, frame, &unread, &unread_elsewhere, &threaded_frames, &mut copied)?; + let kinds = replace_unread(&mut doc, frame, &unread, &unread_elsewhere, &held_frames(&infos, &stories, &threads), &mut copied)?; // With the text objects filled, the page art chosen can differ from the first try's: the // page's type set aside for it, and no other, must be in it. let all_copied = |o: &Vec>| !o.is_empty() && o.iter().all(|n| copied.contains(&n.id)); @@ -543,12 +545,8 @@ pub(super) fn build_weighing( } notes.push(format!("{}: they came in as the page's art", kinds.join(", "))); } - // A story in several frames is threaded type: its frames in order (the first holds the story). - for thread in made.chunk_by(|a, b| a.0 == b.0) { - if thread.len() > 1 { - doc.text_threads.push(thread.iter().map(|(_, _, id)| *id).collect()); - } - } + // The frames still threaded: a blank story's frame an unread object left alone isn't. + let threaded_frames = add_threads(&mut doc, threads, &threaded_frames, !unread.is_empty()); // Area type flows around the wrap objects above it before it is compared with the page. resolve_text_wrap(&mut doc)?; let bound_text = bound_slots(&doc, &bindings, &xml_ids, VariableKind::Text); @@ -1483,7 +1481,9 @@ fn slot_content( ) -> Result<(Vec, bool), String> { let made = make_slots(infos, stories, template, to_doc, notes); if let Some(own) = own.filter(|_| readable_all(infos, &made)) { - return Ok((made_only(infos, made, [own, pages[1]], notes), true)); + let mut content = made_only(infos, stories, made, [own, pages[1]], notes); + settle_blank_stories(infos, stories, template, to_doc, &mut content, notes); + return Ok((content, true)); } // The page's type is matched with every text object whose type isn't made, and weighed against // where every made one draws: that has its limits (the slots of type that looks draw are within @@ -1492,7 +1492,100 @@ fn slot_content( if open > MAX_SLOTS || infos.len().saturating_mul(pages[0].len()) > MAX_PAIRS { return Err("it has too many text objects".into()); } - Ok((plan(infos, stories, made, template, to_doc, pages, notes), false)) + let mut content = plan(infos, stories, made, template, to_doc, pages, notes); + settle_blank_stories(infos, stories, template, to_doc, &mut content, notes); + Ok((content, false)) +} + +/// The threads of the text objects `made` (story, frame and id of each, sorted): each story in +/// several frames, with its frames in order (the first holds the story). +fn threads_of(made: &[(u32, usize, NodeId)]) -> Vec<(u32, Vec)> { + made.chunk_by(|a, b| a.0 == b.0) + .filter(|thread| thread.len() > 1) + .map(|thread| (thread[0].0, thread.iter().map(|(_, _, id)| *id).collect())) + .collect() +} + +/// The frames of `threads` that an unread object can't take with it: those of a blank story's thread +/// hold no type, so they may go. +fn held_frames(infos: &[SlotInfo], stories: &[Option>], threads: &[(u32, Vec)]) -> BTreeSet { + let blank: BTreeSet = + infos.iter().zip(stories).filter(|(_, s)| s.as_ref().is_some_and(|s| s.is_blank())).filter_map(|(i, _)| i.story).collect(); + threads.iter().filter(|(story, _)| !blank.contains(story)).flat_map(|(_, ids)| ids.iter().copied()).collect() +} + +/// `threads` as `doc`'s text threads, and the frames of the threads added. With `replaced` (unread +/// objects were replaced by page art), the frames they took with them (`frames` that `doc` no longer +/// has, only a blank story's) are left out, and so is a thread left with one frame. +fn add_threads(doc: &mut Document, threads: Vec<(u32, Vec)>, frames: &BTreeSet, replaced: bool) -> BTreeSet { + let present = replaced.then(|| doc.index_paths(frames.iter().copied())); + let mut threaded = BTreeSet::new(); + for (_, mut ids) in threads { + if let Some(present) = &present { + ids.retain(|id| present.contains_key(id)); + } + if ids.len() > 1 { + threaded.extend(ids.iter().copied()); + doc.text_threads.push(ids); + } + } + threaded +} + +/// The slots of blank stories (nothing but spaces and line ends) that neither the text document nor +/// the page fills: blank point type draws nothing and has nothing to keep, so it is left out without +/// a note, as VectorCraft's Type tool discards empty point type (#85, #154); blank area type and +/// type on a path come in as an empty text object with their frame or path, as the Type tool keeps +/// such an empty frame, also where the page's type went to another text object (`Merged`). An empty +/// frame draws nothing, so the page can't show it: it is kept without being weighed against the +/// page (`prune_unseen` would take it out), and so are the later frames of its thread, which the +/// text document makes empty. Type that a look draws is left as it is. +fn settle_blank_stories( + infos: &[SlotInfo], + stories: &[Option>], + template: Option<(f64, f64)>, + to_doc: Affine, + content: &mut [Content], + notes: &mut Vec, +) { + // The stories whose first frame came in as an empty frame: their later frames stay with it. + let mut kept = BTreeSet::new(); + for ((story, info), c) in stories.iter().zip(infos).zip(content.iter_mut()) { + let Some(story) = story.as_ref().filter(|s| s.is_blank() && info.look.is_none()) else { continue }; + let unfilled = match c { + Content::Empty => true, + Content::Page(parts) => parts.is_empty(), + _ => false, + }; + if story.blank_point(info.frame) { + if unfilled { + *c = Content::Merged; + } + } else if (unfilled || matches!(c, Content::Merged)) + && let Some((node, region)) = template.and_then(|t| super::plan::blank_frame(info, story, t, to_doc)) + { + *c = Content::Made(node, region.filter(|_| info.shown), true); + kept.extend(info.story); + // Its paragraphs' settings are read as made type's are, with the same notes. + for (left_out, note) in [ + (story.tabs_left_out(), crate::import::ate::TABS_LEFT_OUT), + (story.kinsoku_sets_left_out(), crate::import::ate::KINSOKU_SETS_LEFT_OUT), + ] { + if left_out && !notes.iter().any(|n| n == note) { + notes.push(note.into()); + } + } + } + } + for (info, c) in infos.iter().zip(content.iter_mut()) { + if let Content::Made(_, _, seen) = c + && info.frame > 0 + && info.look.is_none() + && info.story.is_some_and(|s| kept.contains(&s)) + { + *seen = true; + } + } } /// The layers `doc` don't draw as the page (`why`), `unseen` text objects of them taken out: the @@ -2155,6 +2248,30 @@ fn unmark(nodes: &mut [Arc], shown: bool, prints: bool, found: &mut Vec<(N } } +/// Make the clipping groups in `layers` that their type clips ([`Structure::type_clips`]) clip by it, +/// where its slot became one text object (`filled`). The page shows that type by what it clips, so +/// it is never weighed as type the page doesn't draw ([`prune_unseen`]). +fn clip_by_type( + layers: &mut [Arc], + type_clips: &std::collections::HashMap, + filled: &std::collections::HashMap, +) { + let one = |slot: NodeId| { + filled.get(&slot).and_then(|f| match f.objects.as_slice() { + [id] => Some(*id), + _ => None, + }) + }; + let mut seen = |n: &mut Node| { + if let Some(name) = n.name.as_deref().and_then(|m| m.strip_prefix(MADE)) { + n.name = (!name.is_empty()).then(|| name.to_string()); + } + }; + for l in layers { + ai::clip_by_type(Arc::make_mut(l), type_clips, &one, &mut seen); + } +} + /// Take object `id` out of `nodes` (`hide`: leave it, hidden); whether it was there. fn take_out(nodes: &mut Vec>, id: NodeId, hide: bool) -> bool { if let Some(i) = nodes.iter().position(|n| n.id == id) { diff --git a/crates/eps/src/import/native/plan.rs b/crates/eps/src/import/native/plan.rs index 005b89397e..17107dded9 100644 --- a/crates/eps/src/import/native/plan.rs +++ b/crates/eps/src/import/native/plan.rs @@ -66,17 +66,10 @@ pub(super) fn make_slots( .map(|(k, info)| { let t = template?; let story = stories.get(k)?.as_ref()?; - let mut node = story.node(NodeId(0), info.frame, t, to_doc)?; + let node = story.node(NodeId(0), info.frame, t, to_doc)?; tabs_left_out |= story.tabs_left_out(); kinsoku_left_out |= story.kinsoku_sets_left_out(); - let mut region = story.region(t, to_doc); - // The first line where the file has it, in the text document's frame (that of a - // copied object is its original's, as its lines are). - story.place_first_line(&mut node, info.frame, t, to_doc); - // Area type and type on a path in the object's own frame: the text document's frame - // of a copied object keeps its original's path. - frame_text_from_art(info, &mut node, &mut region); - story.flip_on_path(&mut node, info.frame); + let (mut node, region) = placed(info, story, node, t, to_doc); if let NodeKind::Text(text) = &mut node.kind && story.fit_first_line(text) { @@ -109,6 +102,28 @@ pub(super) fn make_slots( made } +/// The empty text object a slot of a blank story in an area frame or on a path comes in as, placed +/// as [`make_slots`] places made type: its frame or path, the object's own where it has one +/// ([`Story::blank_frame_node`]). `None` for any other slot. +pub(super) fn blank_frame(info: &SlotInfo, story: &Story, template: (f64, f64), to_doc: Affine) -> Option { + let node = story.blank_frame_node(NodeId(0), info.frame, template, to_doc)?; + let (node, region) = placed(info, story, node, template, to_doc); + Some((Box::new(node), region)) +} + +/// `node`, made from `story` for slot `info`, placed where the file has it, with the region it +/// draws in: the first line where the file has it, in the text document's frame (that of a copied +/// object is its original's, as its lines are); area type and type on a path in the object's own +/// frame (the text document's frame of a copied object keeps its original's path); type on a path +/// flipped as its frame keeps it. +fn placed(info: &SlotInfo, story: &Story, mut node: Node, template: (f64, f64), to_doc: Affine) -> (Node, Option) { + let mut region = story.region(template, to_doc); + story.place_first_line(&mut node, info.frame, template, to_doc); + frame_text_from_art(info, &mut node, &mut region); + story.flip_on_path(&mut node, info.frame); + (node, region) +} + /// Does the file's text document make the type of every slot that shows (at least one does)? Type /// that a look draws doesn't count: only the page has it. pub(super) fn readable_all(infos: &[SlotInfo], made: &[Option]) -> bool { @@ -122,7 +137,13 @@ pub(super) fn readable_all(infos: &[SlotInfo], made: &[Option]) -> bool { /// that no made type takes, shown or not, is left out with a note in `warn`. Slots that don't show /// and whose type isn't made take the page's type that doesn't show (`pages`: the page's text /// objects that show and that don't), by painting order. -pub(super) fn made_only(infos: &[SlotInfo], made: Vec>, pages: [&[Vec>]; 2], warn: &mut Vec) -> Vec { +pub(super) fn made_only( + infos: &[SlotInfo], + stories: &[Option>], + made: Vec>, + pages: [&[Vec>]; 2], + warn: &mut Vec, +) -> Vec { let [shown, hidden] = pages; let mut content = made_content(infos, made); // The page's type where no made type draws, in the copies that looks draw, is theirs (past @@ -154,7 +175,7 @@ pub(super) fn made_only(infos: &[SlotInfo], made: Vec>, pages: [&[V None => warn.push(PAGE_TYPE_UNCHECKED.into()), } drop_look_slots(infos, &mut content); - fill_hidden(infos, &mut content, hidden); + fill_hidden(infos, stories, &mut content, hidden); content } @@ -421,8 +442,10 @@ pub(super) fn plan( } fill_look_slots(infos, &mut content, &mut spare); // What is left of the page goes by painting order into the shown slots the file can't say. - let loose: Vec = - infos.iter().enumerate().filter(|(k, i)| i.shown && matches!(content.get(*k), Some(Content::Empty))).map(|(k, _)| k).collect(); + let loose = readable_first( + stories, + infos.iter().enumerate().filter(|(k, i)| i.shown && matches!(content.get(*k), Some(Content::Empty))).map(|(k, _)| k).collect(), + ); if loose.is_empty() { // Type of the page that no text object says it owns goes with the nearest text object that has // type of the page (never into made type); with none, it is left out. @@ -466,17 +489,28 @@ pub(super) fn plan( warn.push("the text is on the layers in the order the page paints it, so a text object may be in another group than it was".into()); } } - fill_hidden(infos, &mut content, hidden); + fill_hidden(infos, stories, &mut content, hidden); content } +/// The slots `open` that are to take the page's type left over, by painting order: those of blank +/// stories (nothing but spaces and line ends) only when no other slot is open, as such a story has +/// no type of its own; the blank ones left out come in empty or not at all (see +/// `settle_blank_stories`). +fn readable_first(stories: &[Option>], open: Vec) -> Vec { + let blank = |k: &usize| stories.get(*k).and_then(Option::as_ref).is_some_and(|s| s.is_blank()); + if open.iter().all(blank) { open } else { open.into_iter().filter(|k| !blank(k)).collect() } +} + /// The page's type that doesn't show (`hidden`) goes by painting order into the slots that don't -/// show and have nothing yet, but for what is the type of made type that doesn't show: a page object +/// show and have nothing yet ([`readable_first`]), but for what is the type of made type that doesn't show: a page object /// with words and at least half of it where such type draws, while the type has all its words left /// (each word an object takes is the type's no longer). Past `MAX_PAIRS` comparisons all of it goes. -fn fill_hidden(infos: &[SlotInfo], content: &mut [Content], hidden: &[Vec>]) { - let unread: Vec = - infos.iter().enumerate().filter(|(k, i)| !i.shown && matches!(content.get(*k), Some(Content::Empty))).map(|(k, _)| k).collect(); +fn fill_hidden(infos: &[SlotInfo], stories: &[Option>], content: &mut [Content], hidden: &[Vec>]) { + let unread = readable_first( + stories, + infos.iter().enumerate().filter(|(k, i)| !i.shown && matches!(content.get(*k), Some(Content::Empty))).map(|(k, _)| k).collect(), + ); if unread.is_empty() { return; } diff --git a/crates/eps/src/import/native/slots.rs b/crates/eps/src/import/native/slots.rs index bce43140d1..ebd6deef88 100644 --- a/crates/eps/src/import/native/slots.rs +++ b/crates/eps/src/import/native/slots.rs @@ -2,7 +2,7 @@ use super::build::MADE; use super::{AppearanceItem, Arc, BTreeSet, BlendMode, Document, Node, NodeId, NodeKind, PathData, Point, Rect, ai, slot_of}; /// The notes that say the import left out something the file has (see [`is_loss`]). -pub(super) const TEXT_LEFT_OUT: &str = "text objects on hidden layers or hidden objects couldn't be read, so they are left out"; +pub(super) const TEXT_LEFT_OUT: &str = "text objects whose type couldn't be read from the file's text document or its page are left out"; /// The same for a file without a page to take shown type from. pub(super) const TYPE_LEFT_OUT: &str = "text objects of kinds VectorCraft doesn't read from the file's text document yet are left out"; @@ -230,7 +230,8 @@ pub(super) enum Content { /// Text objects (with the strokes round them) of the page. Page(Vec>), /// A text object made from the file's text document, where it draws on the document (when it - /// shows), and whether the page has type where it is. + /// shows), and whether it is kept without being weighed against the page: the page has type + /// where it is, or it draws nothing (an empty frame of a blank story). Made(Box, Option, bool), /// Nothing the file lets this read. Empty, diff --git a/crates/eps/src/import/tests_generators.rs b/crates/eps/src/import/tests_generators.rs index 270a1a3aa4..63859b3e52 100644 --- a/crates/eps/src/import/tests_generators.rs +++ b/crates/eps/src/import/tests_generators.rs @@ -1180,6 +1180,96 @@ fn filter_output_counts_against_the_memory_budget() { assert!(err.contains("too much memory"), "{err}"); } +/// A shading painted with `shfill` and not extended paints only between its ends: an axial one +/// between the lines through them across its axis, a radial one from a point over its circles +/// (PLRM 3rd ed. §4.9.3: `Extend` is `[false false]` by default). Extended both ways it paints +/// the whole clip. +#[test] +fn shadings_not_extended_paint_only_between_their_ends() { + let shade = |kind: u8, coords: &str, extend: &str| { + let r = read(&format!( + "<< /ShadingType {kind} /ColorSpace /DeviceRGB /Coords [{coords}] {extend} \ + /Function << /FunctionType 2 /Domain [0 1] /C0 [1 0 0] /C1 [0 0 1] /N 1 >> >> shfill" + )); + let n = all(&r.document).into_iter().find(|n| matches!(fill(n), Some(Paint::Gradient(_)))).expect("a gradient fill"); + bounds(&n) + }; + // Axial, from x 10 to 90 (and its reflection in y: the document's y runs down). + let b = shade(2, "10 0 90 0", ""); + assert!(near(b, Rect::new(10.0, 0.0, 90.0, 100.0)), "{b:?}"); + let b = shade(2, "10 0 90 0", "/Extend [false true]"); + assert!(near(b, Rect::new(10.0, 0.0, 100.0, 100.0)), "{b:?}"); + let b = shade(2, "10 0 90 0", "/Extend [true true]"); + assert!(near(b, Rect::new(0.0, 0.0, 100.0, 100.0)), "{b:?}"); + // Radial from the centre point to a circle of radius 30. + let b = shade(3, "50 50 0 50 50 30", ""); + assert!((b.width() - 60.0).abs() < 0.5 && (b.height() - 60.0).abs() < 0.5 && (b.center().x - 50.0).abs() < 0.5, "{b:?}"); + // Its circle is cut to a polygon whose sides lie within 0.01 pt of it, also for a large one. + let r = read( + "<< /ShadingType 3 /ColorSpace /DeviceRGB /Coords [50 50 0 50 50 45] \ + /Function << /FunctionType 2 /Domain [0 1] /C0 [1 0 0] /C1 [0 0 1] /N 1 >> >> shfill", + ); + let n = all(&r.document).into_iter().find(|n| matches!(fill(n), Some(Paint::Gradient(_)))).expect("a gradient fill"); + let NodeKind::Path { path, .. } = &n.kind else { panic!("{n:?}") }; + let ring: Vec = path.subpaths.iter().flat_map(|s| s.anchors.iter().map(|a| a.p)).collect(); + let centre = Point::new(50.0, 50.0); + for (a, b) in ring.iter().zip(ring.iter().cycle().skip(1)) { + assert!((a.distance(centre) - 45.0).abs() < 1e-6, "{a:?}"); + assert!(a.midpoint(*b).distance(centre) > 45.0 - 0.01, "{a:?} {b:?}"); + } + // Stretched 4 times across and squashed to a quarter down (areas unchanged), the sides still + // lie within 0.01 pt of the ellipse it becomes. + let r = read( + "50 50 translate 4 0.25 scale << /ShadingType 3 /ColorSpace /DeviceRGB /Coords [0 0 0 0 0 10] \ + /Function << /FunctionType 2 /Domain [0 1] /C0 [1 0 0] /C1 [0 0 1] /N 1 >> >> shfill", + ); + let n = all(&r.document).into_iter().find(|n| matches!(fill(n), Some(Paint::Gradient(_)))).expect("a gradient fill"); + let NodeKind::Path { path, .. } = &n.kind else { panic!("{n:?}") }; + let sides = path.subpaths.iter().map(|s| s.anchors.len()).sum::(); + // A side of a regular polygon in the circle lies 1 - cos(pi / sides) of the radius inside it; + // stretched to 40 pt across, that is at most 0.01 pt. + assert!(40.0 * (1.0 - (std::f64::consts::PI / sides as f64).cos()) <= 0.01 + 1e-9, "{sides} sides"); + let b = shade(3, "50 50 0 50 50 30", "/Extend [true true]"); + assert!(near(b, Rect::new(0.0, 0.0, 100.0, 100.0)), "{b:?}"); + + // Axial along y, and extended at its start only. + let b = shade(2, "0 20 0 70", ""); + assert!(near(b, Rect::new(0.0, 30.0, 100.0, 80.0)), "{b:?}"); + let b = shade(2, "10 0 90 0", "/Extend [true false]"); + assert!(near(b, Rect::new(0.0, 0.0, 90.0, 100.0)), "{b:?}"); + // Diagonal: from (60, 60) to (90, 90) it paints where x + y lies from 120 to 180, a strip + // across the square's top-right corner whose own corners are cut off. + let r = read( + "<< /ShadingType 2 /ColorSpace /DeviceRGB /Coords [60 60 90 90] \ + /Function << /FunctionType 2 /Domain [0 1] /C0 [1 0 0] /C1 [0 0 1] /N 1 >> >> shfill", + ); + let n = all(&r.document).into_iter().find(|n| matches!(fill(n), Some(Paint::Gradient(_)))).expect("a gradient fill"); + assert!(near(bounds(&n), Rect::new(20.0, 0.0, 100.0, 80.0)), "{:?}", bounds(&n)); + let NodeKind::Path { path, .. } = &n.kind else { panic!("{n:?}") }; + for a in path.subpaths.iter().flat_map(|s| s.anchors.iter()) { + // Back in PostScript's y-up space. + let s = a.p.x + (100.0 - a.p.y); + assert!((120.0 - 1e-6..=180.0 + 1e-6).contains(&s), "{a:?}"); + } + // The current transformation turns the axis: rotated a quarter turn about the centre, an axis + // from -40 to 40 along x runs up the page from y 10 to 90. + let r = read( + "50 50 translate 90 rotate << /ShadingType 2 /ColorSpace /DeviceRGB /Coords [-40 0 40 0] \ + /Function << /FunctionType 2 /Domain [0 1] /C0 [1 0 0] /C1 [0 0 1] /N 1 >> >> shfill", + ); + let n = all(&r.document).into_iter().find(|n| matches!(fill(n), Some(Paint::Gradient(_)))).expect("a gradient fill"); + assert!(near(bounds(&n), Rect::new(0.0, 10.0, 100.0, 90.0)), "{:?}", bounds(&n)); + // Radial from a point off the circle's centre covers the hull of that point and the circle. + let b = shade(3, "20 50 0 60 50 30", ""); + assert!((b.x0 - 20.0).abs() < 0.5 && (b.x1 - 90.0).abs() < 0.5 && (b.y0 - 20.0).abs() < 0.5 && (b.y1 - 80.0).abs() < 0.5, "{b:?}"); + // Radial shadings this doesn't bound (extended at one end, or starting from a circle) still + // paint the whole area. + for (coords, extend) in [("50 50 0 50 50 30", "/Extend [true false]"), ("50 50 0 50 50 30", "/Extend [false true]"), ("50 50 10 50 50 30", "")] { + let b = shade(3, coords, extend); + assert!(near(b, Rect::new(0.0, 0.0, 100.0, 100.0)), "{coords} {extend}: {b:?}"); + } +} + /// A sampled function of one input in an axial shading: interpolated linearly, its gradient has a /// stop at every sample (exact, not sampled evenly); with `Order 3` it is a cubic through the /// samples (PLRM 3rd ed. §3.10.1, Table 3.36), kept in its range. diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index dbac845dad..f809141202 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -3830,7 +3830,7 @@ fn type_with_a_frame_it_cant_read_is_left_out_with_a_note() { let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Spare", false, &text_object(0))), &doc); let r = import(&eps(&page_square(10, 10), &art)).unwrap(); assert!(text_of(&r.document.layers[1]).is_empty()); - assert!(r.warnings.iter().any(|w| w.contains("1 text objects on hidden layers")), "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.contains("1 text objects whose type couldn't be read")), "{:?}", r.warnings); assert!(crate::is_loss(r.warnings.iter().find(|w| w.contains("couldn't be read")).unwrap())); } @@ -5030,6 +5030,274 @@ fn area_type_keeps_its_area_type_options() { assert_eq!(texts[2].area, vectorcraft_doc::AreaOptions::default()); } +/// A blank story in an area frame, hidden or shown, comes in as a text object that keeps its frame +/// and draws nothing (its spaces kept), as VectorCraft's Type tool keeps an empty frame (#85, #154). +/// As point type, hidden or shown, it draws nothing and has nothing to keep: it is left out, without +/// a note that something wasn't read. +#[test] +fn blank_stories_keep_their_area_frame_and_leave_point_type_out_quietly() { + let frames = [area_frame(10.0, 50.0, 90.0, 90.0), point_frame(20.0, 20.0), point_frame(30.0, 30.0), area_frame(60.0, 10.0, 90.0, 40.0)]; + let stories = [ + story("\\r", &[0], "/0 0", "/1 6.0"), + story("\\r", &[1], "/0 0", "/1 6.0"), + story(" \\r", &[2], "/0 0", "/1 6.0"), + story(" \\r", &[3], "/0 0", "/1 6.0"), + ]; + let doc = document_of(&frames, &stories); + // A shown blank area frame too: it draws nothing, so the page can't show it, and it stays. + let shown = square(10, 10) + &text_object(2) + &text_object(3); + let art = native_with_text(&(layer("Back", true, &shown) + &layer("Spare", false, &(text_object(0) + &text_object(1)))), &doc); + let r = import(&eps(&page_square(10, 10), &art)).unwrap(); + let texts = text_of(&r.document.layers[1]); + assert_eq!(texts.len(), 1, "{:?}", r.warnings); + assert_eq!(texts[0].plain_text(), ""); + let vectorcraft_doc::TextKind::Area { frame } = &texts[0].kind else { panic!("area type: {:?}", texts[0].kind) }; + // Art y 50..90 is 10..50 down the 100 pt page. + let b = frame.bounds().unwrap(); + assert!((b.x0 - 10.0).abs() < 1e-6 && (b.y0 - 10.0).abs() < 1e-6 && (b.x1 - 90.0).abs() < 1e-6 && (b.y1 - 50.0).abs() < 1e-6, "{b:?}"); + let shown = text_of(&r.document.layers[0]); + assert_eq!(shown.len(), 1, "{:?}", r.warnings); + assert_eq!(shown[0].plain_text(), " "); + let vectorcraft_doc::TextKind::Area { frame } = &shown[0].kind else { panic!("area type: {:?}", shown[0].kind) }; + // Art y 10..40 is 60..90 down the page. + let b = frame.bounds().unwrap(); + assert!((b.x0 - 60.0).abs() < 1e-6 && (b.y0 - 60.0).abs() < 1e-6 && (b.x1 - 90.0).abs() < 1e-6 && (b.y1 - 90.0).abs() < 1e-6, "{b:?}"); + assert!(!r.warnings.iter().any(|w| w.contains("couldn't be read")), "{:?}", r.warnings); +} + +/// A blank story whose object the page still draws type for takes the page's type, as before: the +/// empty frame is only for a slot nothing else fills. +#[test] +fn a_blank_area_story_the_page_draws_type_for_takes_the_pages_type() { + let doc = document_of(&[area_frame(10.0, 50.0, 90.0, 90.0)], &[story("\\r", &[0], "/0 0", "/1 6.0")]); + let art = native_with_text(&layer("Art", true, &text_object(0)), &doc); + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 14 scalefont setfont 20 75 moveto (Hi there) show"; + let r = import(&eps(page, &art)).unwrap(); + let mut all = vec![]; + r.document.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + all.push(t.plain_text()); + } + }); + assert_eq!(all, ["Hi there".to_string()], "{:?}", r.warnings); +} + +/// The text objects of `d`: each one's text and kind, in the layers' order. +fn text_kinds(d: &Document) -> Vec<(String, &'static str)> { + let mut out = vec![]; + d.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + let kind = match t.kind { + vectorcraft_doc::TextKind::Area { .. } => "area", + vectorcraft_doc::TextKind::OnPath { .. } => "path", + _ => "point", + }; + out.push((t.plain_text(), kind)); + } + }); + out +} + +/// A blank story threaded through two shown area frames comes in as both frames, empty and still +/// one thread: the later frame the text document makes empty stays with the first. +#[test] +fn a_blank_story_threaded_through_two_shown_frames_keeps_both() { + let frames = [area_frame(10.0, 60.0, 40.0, 80.0), area_frame(50.0, 60.0, 80.0, 80.0)]; + let doc = document_of(&frames, &[story("\\r", &[0, 1], "/0 0", "/1 10.0")]); + let art = native_with_text(&layer("Art", true, &(square(10, 10) + &frame_object(0, 0) + &frame_object(0, 1))), &doc); + let r = import(&eps(&page_square(10, 10), &art)).unwrap(); + // The thread names only text objects the document has. + assert!(r.document.text_threads.iter().flatten().all(|id| r.document.node(*id).is_some()), "{:?} {:?}", r.document.text_threads, r.warnings); + assert_eq!(text_kinds(&r.document), [("".to_string(), "area"), ("".to_string(), "area")], "{:?}", r.warnings); + let ids: Vec<_> = r.document.layers[0].children().unwrap().iter().filter(|n| matches!(n.kind, NodeKind::Text(_))).map(|n| n.id).collect(); + assert_eq!(r.document.text_threads, [ids]); +} + +/// A blank story threaded from a hidden frame into a shown one: both frames come in, one thread. +#[test] +fn a_blank_story_threaded_from_a_hidden_frame_into_a_shown_one_keeps_both() { + let frames = [area_frame(10.0, 60.0, 40.0, 80.0), area_frame(50.0, 60.0, 80.0, 80.0)]; + let doc = document_of(&frames, &[story("\\r", &[0, 1], "/0 0", "/1 10.0")]); + let art = native_with_text(&(layer("Back", true, &(square(10, 10) + &frame_object(0, 1))) + &layer("Spare", false, &frame_object(0, 0))), &doc); + let r = import(&eps(&page_square(10, 10), &art)).unwrap(); + assert!(r.document.text_threads.iter().flatten().all(|id| r.document.node(*id).is_some()), "{:?} {:?}", r.document.text_threads, r.warnings); + assert_eq!(text_kinds(&r.document), [("".to_string(), "area"), ("".to_string(), "area")], "{:?}", r.warnings); + assert_eq!(r.document.text_threads.len(), 1, "{:?}", r.warnings); + assert_eq!(r.document.text_threads[0].len(), 2, "{:?}", r.warnings); +} + +/// An unread group holding a frame of a blank story's thread is replaced by its page art as for +/// any other text object (the frame holds no type): the layers are read, and the thread, left with +/// one frame, isn't one any more. +#[test] +fn unread_group_holding_a_blank_threaded_frame_is_replaced() { + let frames = [ + format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 >> >> >>", canvas_rect(50.0, 10.0, 54.0, 14.0)), + format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 >> >> >>", canvas_rect(70.0, 10.0, 74.0, 14.0)), + ]; + let text = document_of(&frames, &[story("\\r", &[0, 1], "/0 0", "/1 10.0")]); + for removed in [0, 1] { + let grouped = os1_group(&format!("{}\n{}\nZZ", square(if removed == 0 { 50 } else { 70 }, 10), frame_object(0, removed))); + let other = frame_object(0, 1 - removed); + let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Mixed", true, &format!("{grouped}\n{other}"))), &text); + let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_three_squares(), vec![], false, true, 1.0); + assert!(read, "removed frame {removed}: {notes:?}"); + assert!(doc.text_threads.is_empty(), "removed frame {removed}: {:?} {notes:?}", doc.text_threads); + assert_eq!(text_kinds(&doc), [("".to_string(), "area")], "removed frame {removed}: {notes:?}"); + } +} + +/// A blank story on a path comes in as empty type on that path. +#[test] +fn a_blank_story_on_a_path_keeps_its_path() { + let (a, b, c) = (canvas(10.0, 70.0), canvas(30.0, 70.0), canvas(50.0, 70.0)); + let path = format!( + "<< /0 << /0 [ 0 0 ] /1 << /0 [ {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} ] >> /2 << /0 2 /6 [ 0.5 2.0 ] >> >> >>", + a.0, a.1, a.0, a.1, b.0, b.1, b.0, b.1, b.0, b.1, b.0, b.1, c.0, c.1, c.0, c.1 + ); + let doc = document_of(&[path], &[story("\\r", &[0], "/0 0", "/1 8.0")]); + let art = native_with_text(&layer("Art", true, &(square(10, 10) + &text_object(0))), &doc); + let r = import(&eps(&page_square(10, 10), &art)).unwrap(); + assert_eq!(text_kinds(&r.document), [("".to_string(), "path")], "{:?}", r.warnings); + let mut on_path = vec![]; + r.document.walk(|n| { + if let NodeKind::Text(t) = &n.kind + && let vectorcraft_doc::TextKind::OnPath { path, start, end } = &t.kind + { + on_path.push((path.bounds(), *start, *end)); + } + }); + // The path as `area_type_and_type_on_a_path_come_from_the_text_document` reads it: 40 pt long, + // the type from a quarter of the way along. + let [(Some(b), start, end)] = on_path.as_slice() else { panic!("{on_path:?}") }; + assert!((b.width() - 40.0).abs() < 1e-6 && (start - 0.25).abs() < 1e-3 && end.is_none(), "{b:?} {start} {end:?}"); +} + +/// Where every shown text object's type comes from the text document (the page isn't matched with +/// them), a hidden blank area story still comes in as its empty frame, and blank point type is left +/// out without a note. +#[test] +fn blank_stories_beside_type_the_text_document_makes() { + let frames = [point_frame(20.0, 20.0), area_frame(10.0, 50.0, 90.0, 90.0), point_frame(30.0, 30.0)]; + let stories = [story("Hi there\\r", &[0], "/0 0", "/1 6.0"), story("\\r", &[1], "/0 0", "/1 6.0"), story("\\r", &[2], "/0 0", "/1 6.0")]; + let doc = document_of(&frames, &stories); + let art = native_with_text( + &(layer("Back", true, &(square(10, 10) + &text_object(0))) + &layer("Spare", false, &(text_object(1) + &text_object(2)))), + &doc, + ); + // The page draws the square and "Hi there" where the text document sets it. + let page = format!("{}\n0 0 0 1 setcmykcolor /Helvetica findfont 6 scalefont setfont 20 20 moveto (Hi there) show", page_square(10, 10)); + let r = import(&eps(&page, &art)).unwrap(); + assert_eq!(text_kinds(&r.document), [("Hi there".to_string(), "point"), ("".to_string(), "area")], "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("couldn't be read")), "{:?}", r.warnings); +} + +/// Without a page (the editing data alone), a blank area story comes in as its empty frame and +/// blank point type is left out, without the note for type of kinds that aren't read. +#[test] +fn blank_stories_without_a_page() { + let frames = [area_frame(10.0, 50.0, 90.0, 90.0), point_frame(30.0, 30.0)]; + let doc = document_of(&frames, &[story("\\r", &[0], "/0 0", "/1 6.0"), story(" \\r", &[1], "/0 0", "/1 6.0")]); + let art = native_with_text(&layer("Art", true, &(text_object(0) + &text_object(1))), &doc); + let (d, notes) = crate::ai_alone(&private(&art)).unwrap(); + assert_eq!(text_kinds(&d), [("".to_string(), "area")], "{notes:?}"); + assert!(!notes.iter().any(|w| w.contains("left out")), "{notes:?}"); +} + +/// The page's spare type goes to a shown text object the text document can't make, not to a blank +/// story beside it, whichever the page paints first: the blank area story comes in as its empty +/// frame. A blank slot takes the page's type only where no other slot is open. +#[test] +fn spare_page_type_goes_to_the_unread_object_not_the_blank_one() { + // Story 0's frame is of a kind this doesn't read, so neither shown object is made: the page's + // one piece of type is spare. + let frames = [point_frame(20.0, 20.0).replace("/2 << /2 [", "/2 << /0 9 /2 ["), area_frame(10.0, 50.0, 90.0, 90.0)]; + let doc = document_of(&frames, &[story("Hi there\\r", &[0], "/0 0", "/1 6.0"), story("\\r", &[1], "/0 0", "/1 6.0")]); + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 6 scalefont setfont 20 20 moveto (Hi there) show"; + for (order, body) in [("blank first", text_object(1) + &text_object(0)), ("blank last", text_object(0) + &text_object(1))] { + let art = native_with_text(&layer("Art", true, &body), &doc); + let r = import(&eps(page, &art)).unwrap(); + let mut texts = text_kinds(&r.document); + texts.sort(); + assert_eq!(texts, [("".to_string(), "area"), ("Hi there".to_string(), "point")], "{order}: {:?}", r.warnings); + } +} + +/// Two shown blank area stories and one piece of the page's type that no text object owns: with no +/// other slot open, the blank ones take it by painting order; the one left without type comes in as +/// its empty frame, not dropped as merged type. +#[test] +fn a_blank_area_story_the_spare_page_type_skips_keeps_its_frame() { + let frames = [area_frame(10.0, 50.0, 90.0, 90.0), area_frame(10.0, 5.0, 40.0, 30.0)]; + let doc = document_of(&frames, &[story("\\r", &[0], "/0 0", "/1 6.0"), story("\\r", &[1], "/0 0", "/1 6.0")]); + let art = native_with_text(&layer("Art", true, &(text_object(0) + &text_object(1))), &doc); + // Away from both frames, so neither owns it. + let page = "0 0 0 1 setcmykcolor /Helvetica findfont 6 scalefont setfont 60 40 moveto (Hi there) show"; + let r = import(&eps(page, &art)).unwrap(); + let mut texts = text_kinds(&r.document); + texts.sort(); + assert_eq!(texts, [("".to_string(), "area"), ("Hi there".to_string(), "point")], "{:?}", r.warnings); +} + +/// A warp or an envelope holding the second frame of a blank story threaded from a frame outside +/// it: a thread names only text objects the document has. The warped frame stays type, and the +/// thread stays whole, as for other threaded type, whatever the warp's look draws; the frame in the +/// envelope comes in as the envelope's drawn art, and no thread is left. +#[test] +fn a_warp_or_an_envelope_holding_a_frame_of_a_blank_thread_keeps_its_thread_of_text() { + let frames = [area_frame(10.0, 5.0, 40.0, 30.0), area_frame(20.0, 40.0, 80.0, 70.0)]; + let doc = document_of(&frames, &[story("\\r", &[0, 1], "/0 0", "/1 10.0")]); + let envelope = type_envelope_of(0, &arc_keys(0.3), &format!("{}\n", square(30, 50)), "").replace("%_0 /FrameIndex ,", "%_1 /FrameIndex ,"); + assert!(envelope.contains("%_1 /FrameIndex ,")); + let warp: String = frame_object(0, 1).lines().map(|l| format!("%_{l}\n")).collect(); + let warped = format!("u\n0 1 1 0 1 0 0 Xa\n2 2 m\n9 2 L\n9 9 L\n2 9 L\nf\nU\n9 () XW\n{warp}1 (Warped) XW\n"); + let check = |what: &str, d: &Document, notes: &[String]| { + assert!( + d.text_threads.iter().flatten().all(|id| d.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Text(_)))), + "{what}: {:?} {notes:?}", + d.text_threads + ); + }; + let art = native_with_text(&layer("Art", true, &format!("{}\n{}\n{envelope}", square(10, 10), frame_object(0, 0))), &doc); + // The page draws the envelope's drawn art. + let r = import(&eps(&format!("{}\n{}", page_square(10, 10), page_square(30, 50)), &art)).unwrap(); + check("envelope, with the page", &r.document, &r.warnings); + assert!(r.document.text_threads.is_empty(), "{:?} {:?}", r.document.text_threads, r.warnings); + let (d, notes) = crate::ai_alone(&private(&art)).unwrap(); + check("envelope, editing data alone", &d, ¬es); + assert!(d.text_threads.is_empty(), "{:?} {notes:?}", d.text_threads); + let art = native_with_text(&(warped_style(40.0, WarpOn::Object) + &layer("Art", true, &format!("{}\n{warped}", frame_object(0, 0)))), &doc); + let (d, notes) = crate::ai_alone(&private(&art)).unwrap(); + check("warp", &d, ¬es); + assert_eq!(d.text_threads.len(), 1, "{notes:?}"); + assert!(!notes.iter().any(|w| w.starts_with(crate::import::ai::WARPED_TYPE_DRAWN)), "{notes:?}"); +} + +/// A blank story's thread whose first frame an unread group takes with it leaves its other frame +/// alone, no longer threaded: in a warp, that frame is weighed against its look as any warped text +/// object is (the look draws a square the empty frame doesn't, so the look takes its place). +#[test] +fn a_blank_frame_an_unread_group_leaves_alone_in_a_warp_is_weighed_as_lone_type() { + let frames = [ + format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 >> >> >>", canvas_rect(50.0, 10.0, 54.0, 14.0)), + format!("<< /0 << /0 [ 0 0 ] /1 << /0 [ {} ] >> /2 << /0 1 >> >> >>", canvas_rect(70.0, 10.0, 74.0, 14.0)), + ]; + let text = document_of(&frames, &[story("\\r", &[0, 1], "/0 0", "/1 10.0")]); + let grouped = os1_group(&format!("{}\n{}\nZZ", square(50, 10), frame_object(0, 0))); + let own: String = frame_object(0, 1).lines().map(|l| format!("%_{l}\n")).collect(); + let warped = format!("u\n0 1 1 0 1 0 0 Xa\n70 10 m\n74 10 L\n74 14 L\n70 14 L\nf\nU\n9 () XW\n{own}1 (Warped) XW\n"); + let art = native_with_text( + &(warped_style(40.0, WarpOn::Object) + &layer("Back", true, &square(10, 10)) + &layer("Mixed", true, &format!("{grouped}\n{warped}"))), + &text, + ); + let (doc, notes, read) = crate::layered_ai(&private(&art), pdf_three_squares(), vec![], false, true, 1.0); + assert!(read, "{notes:?}"); + assert!(doc.text_threads.is_empty(), "{:?} {notes:?}", doc.text_threads); + assert!(notes.iter().any(|w| w.starts_with(crate::import::ai::WARPED_TYPE_DRAWN)), "{notes:?}"); + // The look took the frame's place: no text object is left. + assert!(text_kinds(&doc).is_empty(), "{:?} {notes:?}", text_kinds(&doc)); +} + /// A point type frame at the point (`x`, `y`) of the art. fn point_frame(x: f64, y: f64) -> String { let (cx, cy) = canvas(x, y); @@ -5887,12 +6155,18 @@ fn type_envelope_on(keys: &str, shape: &str, drawn: &str, after: &str) -> String /// [`type_envelope_on`] around the type of story `story`. fn type_envelope_on_story(story: u32, keys: &str, shape: &str, drawn: &str, after: &str) -> String { + type_envelope_holding(keys, shape, &format!("{}{after}", text_object(story)), drawn) +} + +/// [`type_envelope_on`] whose contents are `contents` (on plain lines, written on `%_` ones), which +/// hold its text objects. +fn type_envelope_holding(keys: &str, shape: &str, contents: &str, drawn: &str) -> String { let hidden = |s: &str| -> String { s.lines().map(|l| format!("%_{l}\n")).collect() }; format!( "{}{}%_X=\n{}%_X+\n%_ (AIDeformArtKey) ,\n%_1 /Int (AIDeformStyle) ,\n%_;\n%_\n%_9 () XW\nu\n{drawn}U\n9 () XW\n(Adobe Deform Plugin) 1 0 0 XP\n", hidden(&format!("u\n{shape}U\n")), hidden(&format!("/ArtDictionary :\n{keys}")), - hidden(&format!("u\n{}{after}U\n9 () XW\n", text_object(story))), + hidden(&format!("u\n{contents}U\n9 () XW\n")), ) } @@ -5998,6 +6272,32 @@ fn an_envelope_of_type_that_draws_as_its_drawn_art_opens_live() { assert!(super::tests::program_warnings(&r.warnings).is_empty(), "{:?}", r.warnings); } +/// An envelope of type with no fill and no stroke, its drawn art the bent outlines unpainted, opens +/// live: neither draws a pixel, so they draw alike, and the type stays editable. +#[test] +fn an_envelope_of_unpainted_type_whose_drawn_art_paints_nothing_opens_live() { + let Some(family) = installed_family() else { return }; + // The outlines come from the type filled; the file's type has its fill turned off (`/56 false`). + let filled = type_envelope_text(&family, None); + let mut doc = text_document(&[("FLUX\r", 0, (8170.0, 8180.0), (0.0, 0.0), 0.0)]) + .replace("(Helvetica)", &format!("({family})")) + .replace("/53 <<", "/56 false /53 <<"); + while ascii85(doc.as_bytes()).len() % 60 == 1 { + doc.push('\n'); + } + assert_eq!(text_fill(&made_envelope_type(&doc)), None); + let (drawn, _) = drawn_envelope(&arc_envelope(&made_envelope_type(&filled), 30.0)); + assert!(drawn.contains("f\n"), "{drawn}"); + let unpainted = drawn.replace("f\n", "n\n"); + let art = native_with_text(&layer("Art", true, &format!("{}\n{}", square(10, 10), type_envelope(&arc_keys(0.3), &unpainted))), &doc); + let r = import(&eps(&page_square(10, 10), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let (envelopes, loose) = envelopes_and_type(&r.document); + assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{:?}", r.warnings); + assert!(loose.is_empty(), "{loose:?}"); + assert!(super::tests::program_warnings(&r.warnings).is_empty(), "{:?}", r.warnings); +} + /// An envelope of type whose live envelope draws apart from its drawn art (the file's art bends the /// other way) keeps its drawn art and its type, hidden, with a note. #[test] @@ -6556,6 +6856,86 @@ fn a_warp_of_type_opens_as_a_mesh_on_its_saved_grid_and_keeps_its_shape_when_its } } +/// In the layers, type from the text document made a clipping mask (a clipping group with no +/// clipping path, the type last) clips the group's art as the page draws it: the type comes in as +/// the group's clipping path, editable, and the art doesn't paint past it. +#[test] +fn type_made_a_clipping_mask_clips_its_group_in_the_layers() { + use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions, envelope_content_bounds}; + let Some(family) = installed_family() else { return }; + let doc = type_envelope_text(&family, None); + // The page: the type's glyphs in the yellow of the square they clip, which covers the page, and + // drawn through a flat mesh over their box, which leaves them where they are. + let mut yellow = made_envelope_type(&type_envelope_text(&family, Some("/0 << /0 2 /1 [ 1.0 0.0 0.0 1.0 0.0 ] >>"))); + yellow.visible = true; + let content = vec![std::sync::Arc::new(yellow)]; + let g = envelope_content_bounds(&content).unwrap(); + let points = vec![kurbo::Point::new(g.x0, g.y0), kurbo::Point::new(g.x1, g.y0), kurbo::Point::new(g.x0, g.y1), kurbo::Point::new(g.x1, g.y1)]; + let kind = Box::new(EnvelopeKind::Mesh { rows: 1, cols: 1, points, handles: vec![[kurbo::Vec2::ZERO; 4]; 4] }); + let options = EnvelopeOptions::NEW; + let flat = Node::new( + vectorcraft_doc::NodeId(1_000_000), + NodeKind::Envelope { content, kind, fidelity: 50.0, editing: false, options, frame: Box::default() }, + ); + let (_, page) = drawn_envelope(&flat); + let clipped = format!("q\n0 0 1 0 k\n0 0 m\n100 0 L\n100 100 L\n0 100 L\nf\n{}Q\n", text_object(0)); + let art = native_with_text(&layer("Art", true, &clipped), &doc); + let r = import(&eps(&page, &art)).unwrap(); + // The layers are used, none of their art replaced with the page's (the note on how the type + // differs from the page is about the edges of its glyphs). + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("came in as its art") || w.contains("weren't read")), "{:?}", r.warnings); + let children = r.document.layers[0].children().unwrap(); + let [group] = children.as_slice() else { panic!("{children:#?}") }; + let NodeKind::Group { children, clip: true } = &group.kind else { panic!("not clipped: {group:#?}") }; + let (NodeKind::Text(t), NodeKind::Path { .. }) = (&children[0].kind, &children[1].kind) else { panic!("{children:#?}") }; + assert_eq!(t.plain_text(), "FLUX"); +} + +/// Type made a clipping mask in an envelope's contents (a clipping group with no clipping path, the +/// type last) clips the art under it there, as the drawn art shows: the envelope opens live, its +/// type editable as the group's clipping path. The art it clips covers the type's glyphs and stays +/// inside their box, so the envelope maps from that box however the art past the type would count. +#[test] +fn an_envelope_whose_type_clips_its_contents_opens_live_with_the_type_clipping_them() { + let Some(family) = installed_family() else { return }; + let doc = type_envelope_text(&family, None); + // What it draws: the type in the yellow of the square it clips, which covers it. + let yellow = made_envelope_type(&type_envelope_text(&family, Some("/0 << /0 2 /1 [ 1.0 0.0 0.0 1.0 0.0 ] >>"))); + let shaped = |text: Node| { + let mut text = text; + text.visible = true; + let options = vectorcraft_doc::live::EnvelopeOptions::NEW; + let content = vec![std::sync::Arc::new(text)]; + Node::new( + vectorcraft_doc::NodeId(1_000_000), + NodeKind::Envelope { content, kind: Box::new(rising_kind()), fidelity: 50.0, editing: false, options, frame: Box::default() }, + ) + }; + let glyphs = vectorcraft_doc::live::envelope_content_bounds(&[std::sync::Arc::new(yellow.clone())]).unwrap(); + let (drawn, page) = drawn_envelope(&shaped(yellow)); + // A yellow square over the glyphs' box, just inside it. + let (x0, y0) = to_art(kurbo::Point::new(glyphs.x0 + 0.01, glyphs.y1 - 0.01)); + let (x1, y1) = to_art(kurbo::Point::new(glyphs.x1 - 0.01, glyphs.y0 + 0.01)); + let contents = format!("q\n0 0 1 0 k\n{x0} {y0} m\n{x1} {y0} L\n{x1} {y1} L\n{x0} {y1} L\nf\n{}Q\n", text_object(0)); + let envelope = type_envelope_holding(&arc_keys(0.3), &rising_grid(), &contents, &drawn); + let art = native_with_text(&layer("Art", true, &format!("{}\n{envelope}", square(10, 10))), &doc); + let r = import(&eps(&format!("{}\n{page}", page_square(10, 10)), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + assert!(super::tests::program_warnings(&r.warnings).is_empty(), "{:?}", r.warnings); + let mut live = vec![]; + r.document.walk(|n| { + if let NodeKind::Envelope { content, .. } = &n.kind { + live.push(content.clone()); + } + }); + let [content] = live.as_slice() else { panic!("{:?}", r.warnings) }; + let [group] = content.as_slice() else { panic!("{content:#?}") }; + let NodeKind::Group { children, clip: true } = &group.kind else { panic!("not clipped: {group:#?}") }; + let (NodeKind::Text(t), NodeKind::Path { .. }) = (&children[0].kind, &children[1].kind) else { panic!("{children:#?}") }; + assert_eq!(t.plain_text(), "FLUX"); +} + /// A warp of stroked type with Distort Appearance whose drawn art maps the type's bounds with its /// strokes onto the grid the file saves (not its glyphs' bounds alone) opens live as a mesh envelope /// mapping from that box (#3179). The drawn art strokes the bent outlines at the stroke's own weight, @@ -7198,6 +7578,147 @@ fn warped_type_that_draws_apart_from_its_look_comes_in_as_the_look() { } } +/// An art style section with style `Dashed`: a black stroke 2 units wide with butt caps, miter joins +/// and dashes of 6 and gaps of 4, aligned to corners and path ends (`BSDashAdj`). +fn aligned_dash_style() -> String { + "%AI9_BeginArtStyles\n/KnownStyle :\n(Dashed) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n2 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n\ + /Dictionary : /NotRecorded ,\n1 /Bool (BSDashAdj) ,\n; (kAIBeautifulStrokesParamsDictKey) ,\n\ + /StrokeStyle : 0 R\n0 0 0 1 0 0 0 XA\n0 J 0 j 2 w 10 M [6 4 ]0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n;\n%AI9_EndArtStyles\n" + .to_string() +} + +/// The open path of [`aligned_dash_file`], a corner at (80, 20), in the document's coordinates. +fn aligned_dash_path() -> kurbo::BezPath { + let mut bp = kurbo::BezPath::new(); + bp.move_to((20.0, 20.0)); + bp.line_to((80.0, 20.0)); + bp.line_to((80.0, 70.0)); + bp +} + +/// What [`aligned_dash_style`] draws along [`aligned_dash_path`], with its dashes aligned to corners +/// and path ends by VectorCraft or (`aligned` false) not, as look operators in black. +fn aligned_dash_look(aligned: bool) -> String { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{Dash, LineCap, LineJoin, StrokeLayer}; + let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0); + (stroke.cap, stroke.join, stroke.miter_limit) = (LineCap::Butt, LineJoin::Miter, 10.0); + stroke.dash = Some(Dash { pattern: vec![6.0, 4.0], offset: 0.0, align_corners: aligned }); + let outline = vectorcraft_effects::stroke::line_outline(&aligned_dash_path(), &stroke, 2.0, 0.01); + assert!(!outline.elements().is_empty()); + drawn_as_operators(&outline).replace("0 1 1 0 1 0 0 Xa", "0 0 0 1 0 0 0 Xa") +} + +/// The editing copy of [`aligned_dash_path`] under [`aligned_dash_style`], with the look `drawing`. +fn aligned_dash_file(drawing: &str) -> String { + aligned_dash_files(drawing, 1) +} + +/// [`aligned_dash_file`] with `n` such paths. +fn aligned_dash_files(drawing: &str, n: usize) -> String { + let own = "%_0 0 0 1 0 0 0 XA\n%_2 w\n%_20 80 m\n%_80 80 L\n%_80 30 L\n%_S\n"; + let one = format!("u\n{drawing}\nU\n9 () XW\n{own}1 (Dashed) XW\n"); + native(&(aligned_dash_style() + &layer("Art", true, &one.repeat(n)))) +} + +/// The paths of `d` that stroke with dashes, each with whether its dashes are aligned to corners. +fn dashed_paths(d: &Document) -> Vec { + let mut out = vec![]; + d.walk(|n| { + if matches!(n.kind, NodeKind::Path { .. }) { + for i in &n.appearance.items { + if let vectorcraft_doc::AppearanceItem::Stroke(s) = i + && let Some(dash) = &s.dash + { + out.push(dash.align_corners); + } + } + } + }); + out +} + +/// A stroke whose dashes are aligned to corners and path ends comes in as the path with that stroke, +/// editable, where VectorCraft's fitting draws as its drawn look. +#[test] +fn dashes_aligned_to_corners_that_draw_as_the_look_come_in_live() { + let (d, notes) = crate::ai_alone(&private(&aligned_dash_file(&aligned_dash_look(true)))).unwrap(); + assert_eq!(dashed_paths(&d), [true], "{notes:?}"); + assert!(!notes.iter().any(|w| w.contains("drawn look")), "{notes:?}"); +} + +/// Where the look draws the dashes elsewhere (here, not fitted), the path keeps its drawn look. +#[test] +fn dashes_aligned_to_corners_that_draw_apart_from_the_look_keep_it() { + let (d, notes) = crate::ai_alone(&private(&aligned_dash_file(&aligned_dash_look(false)))).unwrap(); + assert!(dashed_paths(&d).is_empty(), "{notes:?}"); + let looks = d.layers[0].children().unwrap(); + assert!(matches!(looks.as_slice(), [l] if matches!(l.kind, NodeKind::Group { .. }) && l.visual_bounds().is_some()), "{looks:#?}"); +} + +/// The strokes with aligned dashes one import checks against their looks are limited +/// ([`crate::import::ai::MAX_DASH_CHECKS`]), apart from the envelopes' checks: past the +/// limit, a path that would draw as its look keeps the look. +#[test] +fn dashes_aligned_to_corners_past_their_checks_keep_the_look() { + let n = crate::import::ai::MAX_DASH_CHECKS; + let (d, notes) = crate::ai_alone(&private(&aligned_dash_files(&aligned_dash_look(true), n + 1))).unwrap(); + assert_eq!(dashed_paths(&d).len(), n, "{notes:?}"); + let looks = d.layers[0].children().unwrap().iter().filter(|c| matches!(c.kind, NodeKind::Group { .. })).count(); + assert_eq!(looks, 1); +} + +/// The reads of a file apart from its layers check no stroke with dashes aligned to corners in its +/// layers against its look: the import's checks ([`crate::import::ai::MAX_DASH_CHECKS`]) are its +/// layers' reader's, though those reads go over all of the data. Its artboards and variable library +/// are read with no checks at all, and its swatches (and so its brushes, styles and symbols, read +/// the same way) with none once their reader reaches the layers. The layers' reader still checks +/// the one such stroke. +#[test] +fn the_reads_apart_from_the_layers_check_no_aligned_dashes() { + use vectorcraft_testkit::ai::{sample_variable_sets, variable_library_data}; + let library = variable_library_data(&sample_variable_sets("variableAndTypes", &[])); + let own = "%_0 0 0 1 0 0 0 XA\n%_2 w\n%_20 80 m\n%_80 80 L\n%_80 30 L\n%_S\n"; + let one = format!("u\n{}\nU\n9 () XW\n{own}1 (Dashed) XW\n", aligned_dash_look(true)); + let data = native(&(library + &aligned_dash_style() + &layer("Art", true, &one))); + let checks = |f: &dyn Fn()| { + crate::import::ai::DASH_CHECKS_MADE.set(0); + f(); + crate::import::ai::DASH_CHECKS_MADE.get() + }; + let names = crate::import::ai::Names::default; + assert_eq!(checks(&|| drop(crate::ai_alone(&private(&data)))), 1); + assert_eq!(checks(&|| drop(crate::import::ai::artboards(data.as_bytes(), &mut names()))), 0); + assert_eq!(checks(&|| assert!(crate::import::ai::variables(data.as_bytes(), &mut names()).present)), 0); + assert_eq!(checks(&|| drop(crate::import::ai::palette(data.as_bytes(), &[], &mut names()))), 0); +} + +/// Type under a style with dashes aligned to corners keeps its drawn look, as before, and takes no +/// such stroke: the look check isn't made for type. +#[test] +fn type_with_dashes_aligned_to_corners_keeps_its_drawn_look() { + let doc = text_document(&[("TILT\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + let own: String = text_object(0).lines().map(|l| format!("%_{l}\n")).collect(); + let look = format!("u\n{}\nU\n9 () XW\n", aligned_dash_look(true)); + let file = native_with_text(&(aligned_dash_style() + &layer("Art", true, &format!("{look}{own}1 (Dashed) XW\n"))), &doc); + let (d, notes) = crate::ai_alone(&private(&file)).unwrap(); + // The look stays, and the type takes no stroke with aligned dashes. + let kids = d.layers[0].children().unwrap(); + assert!(kids.iter().any(|c| matches!(c.kind, NodeKind::Group { .. }) && c.visual_bounds().is_some()), "{notes:?}"); + let mut aligned = false; + d.walk(|n| { + if matches!(n.kind, NodeKind::Text(_)) { + aligned |= n + .appearance + .items + .iter() + .any(|i| matches!(i, vectorcraft_doc::AppearanceItem::Stroke(s) if s.dash.as_ref().is_some_and(|d| d.align_corners))); + } + }); + assert!(!aligned, "{notes:?}"); +} + /// Warped type that a text variable binds stays type with the effect live and keeps its binding, /// though its live warp draws apart from its look. #[test] diff --git a/crates/eps/src/print.rs b/crates/eps/src/print.rs index 0ccd7a6331..1c85e2cf9c 100644 --- a/crates/eps/src/print.rs +++ b/crates/eps/src/print.rs @@ -70,7 +70,7 @@ fn sheet(p: &PrintPage, job: &PrintJob) -> Result<(String, Vec), String> { } let opts = |region: Rect| EpsOptions { level: job.level, region, ..EpsOptions::default() }; let art_opts = opts(r); - let art = Scene::new(p.doc, &art_opts).run(); + let art = Scene::new(p.doc, &art_opts).on_plate(p.ink.is_some()).run(); // The marks' area: the drawing space the page shows (within the tile). let paper = Rect::new(0.0, 0.0, w, h); let shown = if p.view.determinant().abs() > 1e-12 { p.view.inverse().transform_rect_bbox(paper) } else { paper }; diff --git a/crates/eps/src/print/tests.rs b/crates/eps/src/print/tests.rs index 29e7ca0536..1aaa0866f8 100644 --- a/crates/eps/src/print/tests.rs +++ b/crates/eps/src/print/tests.rs @@ -1,9 +1,12 @@ //! PostScript print jobs: DSC page comments, the setup of each sheet, and a file the PostScript //! reader reads back. -use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{Appearance, Document, Node, NodeId}; -use vectorcraft_geom::{Affine, Rect, shapes}; +use vectorcraft_color::{ + Color, Freeform, FreeformPoint, Gradient, GradientGeom, GradientKind, GradientPaint, GradientSpread, GradientStop, Paint, Swatch, +}; +use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeId, NodeKind, StrokeGradientMode, TextObject}; +use vectorcraft_geom::{Affine, Point, Rect, Vec2, shapes}; +use vectorcraft_testkit::raster::{Image, render_region}; use super::*; @@ -110,3 +113,267 @@ fn separations_screens_flatness_negatives_and_tiles() { assert!(print(&[], &[], &job).is_err()); assert!(print(&[PrintPage { size: (f64::NAN, 1.0), ..page(&d, None) }], &[0], &job).is_err()); } + +/// A 200 × 100 pt CMYK document with spot swatch `Ink` (100% K): a rectangle over the whole page +/// painted `under`, when there is one, then `art`. +fn over(under: Option, art: &[Node]) -> Document { + let mut d = Document::new(200.0, 100.0); + d.color_mode = vectorcraft_doc::ColorMode::Cmyk; + d.swatches.push(Swatch { name: "Ink".into(), paint: Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)), global: true, spot: true }); + let layer = d.layers[0].id; + let under = under.map(|p| Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 100.0)), Appearance::basic(p, Paint::None, 0.0))); + for mut n in under.into_iter().chain(art.iter().cloned()) { + n.id = d.alloc_id(); + d.insert(Some(layer), usize::MAX, n).unwrap(); + } + d +} + +/// Ink `ink`'s plate of `d` as the print plan separates it for PostScript, and as a PostScript +/// separation at `level` read back, both drawn at 1 px a point. +fn plate_of(d: &Document, ink: &str, level: Level) -> (Image, Image) { + let area = Rect::new(0.0, 0.0, 200.0, 100.0); + let settings = serde_json::from_value(serde_json::json!({"output": {"mode": "separations"}})).unwrap(); + let plan = vectorcraft_pdf::plan(d, &vectorcraft_pdf::PrintOptions { settings, postscript: true, ..Default::default() }).unwrap(); + let i = plan.sheets.iter().find(|s| s.ink.as_ref().is_some_and(|p| p.name == ink)).and_then(|s| s.plate).unwrap(); + let plate = &plan.plates[i]; + let page = PrintPage { + doc: plate, + size: (200.0, 100.0), + view: Affine::IDENTITY, + window: None, + place: Affine::IDENTITY, + copies: &[], + area, + marks: None, + negative: false, + ink: Some((ink, 85.0, 15.0)), + }; + let out = print(&[page], &[0], &PrintJob { level, ..PrintJob::default() }).unwrap(); + assert!(level == Level::Three || !text(&out).contains("shfill"), "Level 2 has no smooth shadings"); + let back = crate::import(&out.bytes).unwrap().document; + (render_region(plate, area, 1.0), render_region(&back, area, 1.0)) +} + +/// Ink `ink`'s PostScript plate of `art` over a page of 100% `ink` (`under`), checked against the +/// plate of `art` alone (drawn from the print plan, or with `postscript` from its PostScript +/// plate): where `art` puts none of the ink down, the ink under it prints, and where it puts ink +/// down, its own amount prints. The pixels of the page where `art` alone puts no ink, those of +/// them where the ink under it does not print, and the pixels where `art` puts ink down that do +/// not print its amount. +fn keeps_the_ink_below(art: &[Node], under: &Paint, ink: &str, level: Level, postscript: bool) -> (usize, usize, usize) { + let (plan, own) = plate_of(&over(None, art), ink, level); + let alone = if postscript { own } else { plan }; + let (_, printed) = plate_of(&over(Some(under.clone()), art), ink, level); + // Pixels whose neighbors all have paper (or all have ink) on the plate of `art` alone: an + // edge falls on either side of a pixel's center, and the edge of the inked part is lightest. + let around = |x: u32, y: u32, paper: bool| { + (x.saturating_sub(1)..=(x + 1).min(alone.width - 1)) + .all(|i| (y.saturating_sub(1)..=(y + 1).min(alone.height - 1)).all(|j| (alone.over_white(i, j)[0] >= 254) == paper)) + }; + let (mut paper, mut knocked_out, mut wrong) = (0, 0, 0); + for y in 0..alone.height { + for x in 0..alone.width { + let (a, p) = (alone.over_white(x, y)[0], printed.over_white(x, y)[0]); + if around(x, y, true) { + paper += 1; + knocked_out += usize::from(p > 60); + } else if around(x, y, false) { + wrong += usize::from(a.abs_diff(p) > 48); + } + } + } + (paper, knocked_out, wrong) +} + +/// A rectangle from (20, 10) to (180, 90) with `fill` and `stroke` (16 pt), each set to +/// overprint. +fn overprinting(fill: Paint, stroke: Paint) -> Node { + let mut n = Node::path(NodeId(0), shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Appearance::basic(fill, stroke, 16.0)); + for it in &mut n.appearance.items { + *it.overprint_mut() = true; + } + n +} + +/// `stops` (offset, color) as a `kind` gradient placed at `geom`, spreading as `spread`. +fn gradient(kind: GradientKind, stops: &[(f32, Color)], geom: GradientGeom, spread: GradientSpread) -> Paint { + let stops = stops.iter().map(|(o, c)| GradientStop::new(*o, *c)).collect(); + let mut g = GradientPaint::new(Gradient { spread, repeats: 2, ..Gradient::new(kind, stops) }); + g.geom = Some(geom); + Paint::Gradient(Box::new(g)) +} + +#[test] +fn an_overprinting_gradient_keeps_the_ink_below_where_it_puts_none_on_a_postscript_plate() { + // Cyan in the outer stops, none from 0.3 to 0.6 (magenta only there). + let (inked, none) = (Color::cmyk(0.6, 0.3, 0.0, 0.0), Color::cmyk(0.0, 0.3, 0.0, 0.0)); + let stops = [(0.0, inked), (0.3, none), (0.6, none), (1.0, inked)]; + let c = Point::new(100.0, 50.0); + let around = GradientGeom { start: c, end: c + Vec2::new(70.0, -20.0), aspect: 0.7, focal: None }; + let across = GradientGeom { start: Point::new(30.0, 40.0), end: Point::new(170.0, 60.0), aspect: 1.0, focal: None }; + let pad = GradientSpread::Pad; + let fills = [ + ("linear", gradient(GradientKind::Linear, &stops, across, pad)), + ("radial", gradient(GradientKind::Radial, &stops, around, pad)), + ("off-center radial", gradient(GradientKind::Radial, &stops, GradientGeom { focal: Some(c + Vec2::new(-20.0, 10.0)), ..around }, pad)), + ("conic", gradient(GradientKind::Conic, &stops, around, pad)), + ("diamond", gradient(GradientKind::Diamond, &stops, around, pad)), + ("repeating linear", gradient(GradientKind::Linear, &stops, across, GradientSpread::Repeat)), + ("reflecting radial", gradient(GradientKind::Radial, &stops, around, GradientSpread::Reflect)), + // A hard edge: two stops at 0.5, the inked half first. + ("hard edge", gradient(GradientKind::Linear, &[(0.0, inked), (0.5, inked), (0.5, none), (1.0, none)], across, pad)), + // Starting and ending with no cyan, padding past both ends. + ("none at the ends", gradient(GradientKind::Linear, &[(0.2, none), (0.4, none), (0.5, inked), (0.8, none)], across, pad)), + ]; + // Many stretches with no cyan. + let many: Vec<(f32, Color)> = (0..16).map(|i| (i as f32 / 15.0, if i % 4 < 2 { inked } else { none })).collect(); + let fills = fills.into_iter().chain([("many stops", gradient(GradientKind::Linear, &many, across, pad))]); + let cyan = Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)); + let cases: Vec<_> = fills.map(|(name, fill)| (name, overprinting(fill, Paint::None), cyan.clone(), "Cyan")).collect(); + assert_keeps_the_ink_below(&cases); +} + +#[test] +fn an_overprinting_gradient_with_a_hard_stop_at_an_end_keeps_the_ink_below_on_a_postscript_plate() { + // Two stops at an end, one with cyan and one without: Level 2's bands pad with the end stop, + // Level 3's shading with the stretch next to it, so each level is checked against its own + // plate of the gradient alone. + let (inked, none) = (Color::cmyk(0.6, 0.3, 0.0, 0.0), Color::cmyk(0.0, 0.3, 0.0, 0.0)); + // Each with where it puts cyan at Level 3 and at Level 2: halfway along its vector, before its + // start and past its end. + let ends = [ + ("none then cyan at 0", [(0.0, none), (0.0, inked), (1.0, inked)], [[true, true, true], [true, false, true]]), + ("cyan then none at 1", [(0.0, inked), (1.0, inked), (1.0, none)], [[true, true, true], [true, true, false]]), + ("cyan then none at 0", [(0.0, inked), (0.0, none), (1.0, none)], [[false, false, false], [false, true, false]]), + ("none then cyan at 1", [(0.0, none), (1.0, none), (1.0, inked)], [[false, false, false], [false, false, true]]), + ]; + let c = Point::new(100.0, 50.0); + let around = GradientGeom { start: c, end: c + Vec2::new(50.0, -10.0), aspect: 0.7, focal: None }; + let across = GradientGeom { start: Point::new(40.0, 40.0), end: Point::new(160.0, 60.0), aspect: 1.0, focal: None }; + let pad = GradientSpread::Pad; + let cyan = Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)); + // The points probed: halfway along the vector, before its start (a linear gradient only) and + // past its end, all inside the art. + let at = |g: GradientGeom, t: f64| g.start + (g.end - g.start) * t; + let shapes = [ + (GradientKind::Linear, across, "linear", [Some(at(across, 0.5)), Some(at(across, -0.125)), Some(at(across, 1.125))]), + (GradientKind::Radial, around, "radial", [Some(at(around, 0.5)), None, Some(at(around, 1.2))]), + (GradientKind::Diamond, around, "diamond", [Some(at(around, 0.5)), None, Some(at(around, 1.2))]), + ]; + let mut cases = vec![]; + let mut wrong = vec![]; + for (name, stops, inks) in &ends { + for (kind, geom, shape, probes) in shapes { + let fill = gradient(kind, stops, geom, pad); + let art = overprinting(fill, Paint::None); + // The gradient's own cyan prints at the probes where it puts some down, alone and over + // the cyan below; elsewhere the plate is paper alone and the cyan below prints. + for (level, inks) in [Level::Three, Level::Two].into_iter().zip(inks) { + let (_, alone) = plate_of(&over(None, std::slice::from_ref(&art)), "Cyan", level); + let (_, printed) = plate_of(&over(Some(cyan.clone()), std::slice::from_ref(&art)), "Cyan", level); + for (p, ink) in probes.iter().zip(inks).filter_map(|(p, ink)| p.map(|p| (p, *ink))) { + let (a, b) = (alone.over_white(p.x as u32, p.y as u32)[0], printed.over_white(p.x as u32, p.y as u32)[0]); + let ok = if ink { (60..=150).contains(&a) && (60..=150).contains(&b) } else { a >= 250 && b <= 10 }; + if !ok { + wrong.push(format!("{shape}, {name} at level {level:?} at {p:?}: {a} alone, {b} over the cyan, cyan expected: {ink}")); + } + } + } + cases.push((format!("{shape}, {name}"), art, cyan.clone(), "Cyan")); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); + let cases: Vec<_> = cases.iter().map(|(name, art, under, ink)| (name.as_str(), art.clone(), under.clone(), *ink)).collect(); + assert_keeps_the_ink_below_of(&cases, true); +} + +#[test] +fn an_overprinting_diamond_gradient_without_a_frame_keeps_the_ink_below_on_a_postscript_plate() { + // A vector of no length: the diamond is its color at 1 everywhere. With two stops at 1, that is + // the first of them, which ends the stretch before it, not the last stop. + let (inked, none) = (Color::cmyk(0.6, 0.3, 0.0, 0.0), Color::cmyk(0.0, 0.3, 0.0, 0.0)); + let c = Point::new(100.0, 50.0); + let flat = GradientGeom { start: c, end: c, aspect: 0.7, focal: None }; + let cyan = Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)); + let cases = [ + ("none last", [(0.0, inked), (1.0, inked), (1.0, none)]), + ("cyan last", [(0.0, none), (1.0, none), (1.0, inked)]), + ("none throughout", [(0.0, none), (0.5, none), (1.0, none)]), + ("cyan throughout", [(0.0, inked), (0.5, inked), (1.0, inked)]), + ]; + let cases: Vec<_> = cases + .iter() + .map(|(name, stops)| { + (*name, overprinting(gradient(GradientKind::Diamond, stops, flat, GradientSpread::Pad), Paint::None), cyan.clone(), "Cyan") + }) + .collect(); + assert_keeps_the_ink_below(&cases); +} + +/// [`keeps_the_ink_below`] for each of `cases` (a name, the art, the paint under it and the ink +/// of the plate) at Level 3 and Level 2, with every case that fails named. +fn assert_keeps_the_ink_below(cases: &[(&str, Node, Paint, &str)]) { + assert_keeps_the_ink_below_of(cases, false); +} + +/// [`assert_keeps_the_ink_below`], checked against the PostScript plate of each case's art alone +/// with `postscript`. +fn assert_keeps_the_ink_below_of(cases: &[(&str, Node, Paint, &str)], postscript: bool) { + let mut failed = vec![]; + for (name, art, under, ink) in cases { + for level in [Level::Three, Level::Two] { + let (paper, knocked_out, wrong) = keeps_the_ink_below(std::slice::from_ref(art), under, ink, level, postscript); + if knocked_out + wrong >= 100 { + failed.push(format!("{name} at level {level:?}: {knocked_out} of {paper} knocked out, {wrong} of the others differ")); + } + } + } + assert!(failed.is_empty(), "{failed:#?}"); +} + +#[test] +fn overprinting_gradient_strokes_type_freeforms_and_spot_inks_keep_the_ink_below_on_postscript_plates() { + let (inked, none) = (Color::cmyk(0.6, 0.3, 0.0, 0.0), Color::cmyk(0.0, 0.3, 0.0, 0.0)); + let stops = [(0.0, inked), (0.3, none), (0.6, none), (1.0, inked)]; + let across = GradientGeom { start: Point::new(30.0, 40.0), end: Point::new(170.0, 60.0), aspect: 1.0, focal: None }; + let linear = gradient(GradientKind::Linear, &stops, across, GradientSpread::Pad); + let stroked = |mode: StrokeGradientMode| { + let mut n = overprinting(Paint::None, linear.clone()); + if let Some(st) = n.appearance.stroke_mut() { + st.gradient_mode = mode; + } + n + }; + // Type: a gradient placed on the characters' bounds. + let on_type = GradientPaint::new(Gradient::new(GradientKind::Linear, stops.iter().map(|(o, c)| GradientStop::new(*o, *c)).collect())); + let style = CharStyle { fill: Paint::Gradient(Box::new(on_type)), overprint_fill: true, size: 80.0, ..Default::default() }; + let text = Node::new(NodeId(0), NodeKind::Text(Box::new(TextObject::point(Point::new(20.0, 85.0), "HIM", style)))); + // A freeform gradient with wide spreads of pure color around its points: none of the cyan + // around the left one. + let mut freeform = GradientPaint::new(Gradient::new(GradientKind::Freeform, vec![GradientStop::new(0.0, none), GradientStop::new(1.0, inked)])); + let pure = |at: Point, c: Color| FreeformPoint { spread: 0.9, ..FreeformPoint::new(at, c) }; + let points = vec![pure(Point::new(50.0, 50.0), none), pure(Point::new(150.0, 50.0), inked)]; + freeform.freeform = Some(Freeform { points, ..Default::default() }); + // A spot ink's own plate: its tints in the outer stops, none of it from 0.3 to 0.6. + let tint = |t: f32| GradientStop { swatch: Some("Ink".into()), tint: t, ..GradientStop::new(0.0, Color::cmyk(0.0, 0.0, 0.0, t)) }; + let spot = [ + GradientStop { offset: 0.0, ..tint(0.8) }, + GradientStop::new(0.3, none), + GradientStop::new(0.6, none), + GradientStop { offset: 1.0, ..tint(0.5) }, + ]; + let mut on_spot = GradientPaint::new(Gradient::new(GradientKind::Linear, spot.to_vec())); + on_spot.geom = Some(across); + let cyan = Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)); + let full = Paint::Solid { color: Color::cmyk(0.0, 0.0, 0.0, 1.0), swatch: Some("Ink".into()), tint: 1.0 }; + let cases = [ + ("stroke within", stroked(StrokeGradientMode::Within), cyan.clone(), "Cyan"), + ("stroke along", stroked(StrokeGradientMode::Along), cyan.clone(), "Cyan"), + ("stroke across", stroked(StrokeGradientMode::Across), cyan.clone(), "Cyan"), + ("type", text, cyan.clone(), "Cyan"), + ("freeform", overprinting(Paint::Gradient(Box::new(freeform)), Paint::None), cyan, "Cyan"), + ("spot", overprinting(Paint::Gradient(Box::new(on_spot)), Paint::None), full, "Ink"), + ]; + assert_keeps_the_ink_below(&cases); +} diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index 5bbb1c9fed..c715d817ec 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -8,6 +8,7 @@ use std::sync::Arc; use kurbo::Shape; use vectorcraft_color::{BlendMode, Color, GradientKind, GradientPaint, Paint}; +use vectorcraft_doc::overprint::is_white; use vectorcraft_doc::{ AppearanceItem, ColorMode, Document, Effect, ImageBlob, LineCap, LineJoin, Node, NodeKind, StrokeAlign, StrokeLayer, SymbolBoxes, TextObject, }; @@ -213,6 +214,14 @@ impl GradientSpace { GradientSpace::Inks(_, n) => *n, } } + + /// Whether components `c` in this space are paper white: no ink, or full light. + fn paper(&self, c: &[f32]) -> bool { + match self { + GradientSpace::Process(Space::Gray | Space::Rgb) => c.iter().all(|v| *v >= 1.0), + GradientSpace::Process(Space::Cmyk) | GradientSpace::Inks(..) => c.iter().all(|v| *v <= 0.0), + } + } } /// A gradient's stops as written: offsets from 0 to 1 and the components in its space. @@ -232,6 +241,13 @@ fn unit(v: f32) -> f32 { if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 } } +/// The color of `stops` (offsets in order, from 0 to 1) at 1, which a diamond gradient without a +/// frame is everywhere, as [`vectorcraft_color::Gradient::sample`] gives it: the first stop at +/// 1, the end of the stretch before it when several stops share that offset. +fn frameless_color(stops: &[(f64, Vec)]) -> Option<&[f32]> { + stops.iter().find(|(o, _)| *o >= 1.0).or(stops.last()).map(|(_, c)| c.as_slice()) +} + /// Can `a` be drawn through (a finite, non-flat map)? fn invertible(a: Affine) -> bool { let det = a.determinant(); @@ -287,6 +303,12 @@ pub(crate) struct Scene<'a> { max_body: usize, /// Symbols and brush art being written inside one another. nest: u32, + /// The document is a separation's plate: every color is the gray of one ink's coverage + /// ([`Self::on_plate`]). + plate: bool, + /// The gradient being painted overprints on a plate: where it is paper white it puts none of + /// the plate's ink down, and the plate below it is left as it is ([`Self::inked_spans`]). + keep_below: bool, } impl<'a> Scene<'a> { @@ -315,9 +337,19 @@ impl<'a> Scene<'a> { pending: 0, max_body: MAX_BODY, nest: 0, + plate: false, + keep_below: false, } } + /// This scene drawing a separation's plate when `plate` is true: an overprinting gradient + /// paints only where it puts the plate's ink down, as an overprinting solid color that puts + /// none down is drawn as nothing on it. + pub fn on_plate(mut self, plate: bool) -> Self { + self.plate = plate; + self + } + /// This scene with a page body of at most `max` bytes. #[cfg(test)] pub fn with_max_body(mut self, max: usize) -> Self { @@ -689,13 +721,20 @@ impl<'a> Scene<'a> { self.line("q"); push_path(&mut self.body, bp); self.body.push_str(clip_op(rule)); - self.paint_area(p, bounds, bp.bounding_box()); + self.paint_overprinting(overprint, p, bounds, bp.bounding_box()); self.line("Q"); } } self.overprint_off(on); } + /// [`Self::paint_area`] for a fill or stroke that overprints when `overprint` is true. + fn paint_overprinting(&mut self, overprint: bool, p: &Paint, bounds: Rect, area: Rect) { + let keep = std::mem::replace(&mut self.keep_below, self.plate && overprint); + self.paint_area(p, bounds, area); + self.keep_below = keep; + } + /// Paint all of `area` (inside the current clip) with gradient or pattern `p`, placed on /// `bounds`. fn paint_area(&mut self, p: &Paint, bounds: Rect, area: Rect) { @@ -786,7 +825,7 @@ impl<'a> Scene<'a> { self.line("q"); push_path(&mut self.body, bp); self.line("strokepath W"); - self.paint_area(p, paint_bounds, w.reach(st, bounds)); + self.paint_overprinting(st.overprint, p, paint_bounds, w.reach(st, bounds)); self.line("Q"); } } @@ -1152,7 +1191,8 @@ impl<'a> Scene<'a> { /// Paint all of `area` (inside the current clip) with linear, radial, conic or diamond gradient /// `g`, placed on `bounds`: a smooth shading at Level 3, else stepped fills (a conic: wedges at - /// both levels; a diamond: four linear gradients, [`Self::diamond_quadrants`]). + /// both levels; a diamond: four linear gradients, [`Self::diamond_quadrants`]). Overprinting + /// on a plate, it is clipped to the levels where it puts ink down ([`Self::inked_spans`]). fn gradient(&mut self, g: &GradientPaint, bounds: Rect, area: Rect) { let geom = g.resolve(bounds); // One mixed around the hue wheel that reflects is repeated from its curve's stops, which @@ -1185,7 +1225,7 @@ impl<'a> Scene<'a> { } let (space, stops) = self.gradient_stops(&g.gradient); if !stops.windows(2).any(|w| w[1].0 > w[0].0) { - if let Some((_, c)) = stops.first() { + if let Some((_, c)) = stops.first().filter(|(_, c)| !(self.keep_below && space.paper(c))) { self.set_comps(&space, c); self.rect_fill(area); } @@ -1193,20 +1233,47 @@ impl<'a> Scene<'a> { } let space = &space; let smooth = self.o.level == Level::Three && !self.o.compatible_gradients; + let spans = if g.gradient.kind == GradientKind::Conic { None } else { self.inked_spans(space, &stops, smooth) }; match g.gradient.kind { GradientKind::Conic => self.conic_steps(&geom, area, space, &stops, &g.gradient), - GradientKind::Diamond => self.diamond_quadrants(&geom, area, space, &stops, smooth), + GradientKind::Diamond => { + // Its levels are diamonds about the center, the square's edge at 1. + let Some(frame) = geom.diamond_frame() else { + // Without a frame it is its color at 1 everywhere; overprinting on a plate, + // paper white there leaves the ink below. + if !(self.keep_below && frameless_color(&stops).is_some_and(|c| space.paper(c))) { + self.diamond_quadrants(&geom, area, space, &stops, smooth); + } + return; + }; + if let Some(spans) = &spans { + let level = |t: f64| (t > 0.0).then(|| frame * BezPath::from_vec(diamond(t))); + self.line("q"); + let clipped = self.clip_rings(spans, area.inflate(1.0, 1.0), level); + if clipped { + self.diamond_quadrants(&geom, area, space, &stops, smooth); + } + self.line("Q"); + return; + } + self.diamond_quadrants(&geom, area, space, &stops, smooth); + } GradientKind::Radial => { let r = geom.length().max(1e-6); let squash = geom.radial_squash(); let inv = squash.inverse(); let (f, c) = (inv * geom.focal_point(), geom.start); + let local = inv.transform_rect_bbox(area); self.line("q"); let _ = writeln!(self.body, "{} cm", ps::matrix(squash)); - if smooth { - self.shading(3, space, &[f.x, f.y, 0.0, c.x, c.y, r], &stops); - } else { - self.radial_steps(f, c, r, inv.transform_rect_bbox(area), space, &stops); + // Its levels are circles from the focal point, at 1 the circle of radius `r`. + let level = |t: f64| (t > 0.0).then(|| kurbo::Circle::new(f + (c - f) * t, r * t).to_path(0.01)); + if spans.as_ref().is_none_or(|spans| self.clip_rings(spans, local.inflate(1.0, 1.0), level)) { + if smooth { + self.shading(3, space, &[f.x, f.y, 0.0, c.x, c.y, r], &stops); + } else { + self.radial_steps(f, c, r, local, space, &stops); + } } self.line("Q"); } @@ -1215,15 +1282,122 @@ impl<'a> Scene<'a> { if s.distance(e) < 1e-9 { e = s + Vec2::new(1.0, 0.0); } - if smooth { - self.shading(2, space, &[s.x, s.y, e.x, e.y], &stops); + if let Some(spans) = &spans { + self.line("q"); + if self.clip_strips(spans, s, e, area) { + self.linear(s, e, area, space, &stops, smooth); + } + self.line("Q"); } else { - self.linear_steps(s, e, area, space, &stops); + self.linear(s, e, area, space, &stops, smooth); } } } } + /// A linear gradient from `s` to `e` over `area`: a smooth shading, else stepped fills. + fn linear(&mut self, s: Point, e: Point, area: Rect, space: &GradientSpace, stops: &[(f64, Vec)], smooth: bool) { + if smooth { + self.shading(2, space, &[s.x, s.y, e.x, e.y], stops); + } else { + self.linear_steps(s, e, area, space, stops); + } + } + + /// Where an overprinting gradient with `stops` in `space` puts ink on a plate + /// ([`Self::keep_below`]): the spans of its levels outside every stretch between two stops of + /// paper white and outside the padding past an end painted paper white, in order, an end + /// padding with ink unbounded. The padding takes the end stop's color when stepped and the + /// end stretch's color when `smooth` ([`Self::shading`]); the two differ when two stops share + /// the end's offset. `None` when the gradient puts ink everywhere or does not overprint on a + /// plate; empty when it puts none down. + fn inked_spans(&self, space: &GradientSpace, stops: &[(f64, Vec)], smooth: bool) -> Option> { + if !self.keep_below { + return None; + } + let stretches: Vec<_> = stops.windows(2).filter(|w| w[1].0 > w[0].0).collect(); + let (first, last) = (stretches.first()?, stretches.last()?); + let (start, end) = if smooth { (&first[0].1, &last[1].1) } else { (&stops.first()?.1, &stops.last()?.1) }; + let (before, after) = (space.paper(start), space.paper(end)); + let mut blank: Vec<(f64, f64)> = vec![]; + let mut add = |a: f64, b: f64| match blank.last_mut() { + Some(l) if l.1 >= a => l.1 = l.1.max(b), + _ => blank.push((a, b)), + }; + if before { + add(f64::NEG_INFINITY, first[0].0); + } + for w in &stretches { + if space.paper(&w[0].1) && space.paper(&w[1].1) { + add(w[0].0, w[1].0); + } + } + if after { + add(last[1].0, f64::INFINITY); + } + if blank.is_empty() { + return None; + } + let mut inked = vec![]; + let mut from = f64::NEG_INFINITY; + for (a, b) in blank { + if a > from { + inked.push((from, a)); + } + from = b; + } + if from < f64::INFINITY { + inked.push((from, f64::INFINITY)); + } + Some(inked) + } + + /// Clip to the parts of `area` where a linear gradient from `s` to `e` has a level in `spans`: + /// a strip across the gradient for each. False, with nothing written, when no span reaches + /// into `area`. + fn clip_strips(&mut self, spans: &[(f64, f64)], s: Point, e: Point, area: Rect) -> bool { + let d = e - s; + let len = d.hypot(); + // Gradient space: x along the gradient (0 to 1), y across it in points. + let frame = Affine::new([d.x, d.y, -d.y / len, d.x / len, s.x, s.y]); + let local = frame.inverse().transform_rect_bbox(area.inflate(1.0, 1.0)); + let mut bp = BezPath::new(); + for &(a, b) in spans { + let (a, b) = (a.max(local.x0), b.min(local.x1)); + if a < b { + bp.extend((frame * Rect::new(a, local.y0, b, local.y1).to_path(0.1)).iter()); + } + } + self.clip_path(&bp, FillRule::NonZero) + } + + /// Clip to the levels in `spans` of a gradient whose level `t` is bounded by `level(t)` (a + /// closed path holding every lower level; `None` for a level without area): for each span + /// the ring between its levels, an unbounded end at `outer`, even-odd. False, with nothing + /// written, when no span has area. + fn clip_rings(&mut self, spans: &[(f64, f64)], outer: Rect, level: impl Fn(f64) -> Option) -> bool { + let mut bp = BezPath::new(); + for &(a, b) in spans { + let edge = if b.is_finite() { level(b) } else { Some(outer.to_path(0.1)) }; + let Some(edge) = edge else { continue }; + bp.extend(edge.iter()); + if let Some(inner) = level(a).filter(|_| a.is_finite()) { + bp.extend(inner.iter()); + } + } + self.clip_path(&bp, FillRule::EvenOdd) + } + + /// Clip to `bp` by `rule`. False, with nothing written, when `bp` is empty. + fn clip_path(&mut self, bp: &BezPath, rule: FillRule) -> bool { + if bp.elements().is_empty() { + return false; + } + push_path(&mut self.body, bp); + self.body.push_str(clip_op(rule)); + true + } + /// A conic gradient as [`CONIC_WEDGE_COUNT`] solid wedges about its center covering `area` /// (PostScript has no conic shading), each running on to the seam under the next, so no /// hairline shows between neighbors ([`vectorcraft_color::GradientGeom::conic_wedges`]). @@ -1243,7 +1417,24 @@ impl<'a> Scene<'a> { Some(w) => w[1].1.clone(), None => stops.last().map_or_else(Vec::new, |s| s.1.clone()), }; - for (pts, t) in geom.conic_wedges(area, g.conic_wedge_count(CONIC_WEDGE_COUNT), true) { + let count = g.conic_wedge_count(CONIC_WEDGE_COUNT); + // Overprinting on a plate: clipped to the wedges that put ink down, each up to the next. + let clipped = self.keep_below && { + let wedges = geom.conic_wedges(area, count, false); + let inked: Vec<_> = wedges.iter().filter(|(_, t)| !space.paper(&at(spread(*t)))).collect(); + if inked.is_empty() { + return; + } + inked.len() < wedges.len() && { + let mut bp = BezPath::new(); + for (pts, _) in inked { + bp.extend(BezPath::from_vec(polygon(pts)).iter()); + } + self.line("q"); + self.clip_path(&bp, FillRule::NonZero) + } + }; + for (pts, t) in geom.conic_wedges(area, count, true) { self.set_comps(space, &at(spread(t))); for (i, p) in pts.iter().enumerate() { push_nums(&mut self.body, &[p.x, p.y]); @@ -1251,13 +1442,17 @@ impl<'a> Scene<'a> { } self.line("closepath fill"); } + if clipped { + self.line("Q"); + } } /// A diamond gradient over `area` as four linear gradients, each clipped to a quadrant of its /// frame and equal to the diamond there (PostScript has no diamond shading; /// [`vectorcraft_color::GradientGeom::diamond_quadrants`]): smooth axial shadings, else /// stepped fills. Each quadrant but the last runs on under the next (stops are opaque here), - /// so no hairline shows between them. A diamond without an extent is its last stop. + /// so no hairline shows between them. A diamond without an extent is its color at 1 + /// ([`frameless_color`]). fn diamond_quadrants( &mut self, geom: &vectorcraft_color::GradientGeom, @@ -1267,7 +1462,7 @@ impl<'a> Scene<'a> { smooth: bool, ) { let Some(quadrants) = geom.diamond_quadrants(area) else { - if let Some((_, c)) = stops.last() { + if let Some(c) = frameless_color(stops) { self.set_comps(space, c); self.rect_fill(area); } @@ -1442,20 +1637,68 @@ impl<'a> Scene<'a> { let field = g.freeform_on(b).model_field(spread_scale(b)); let q = |v: f32| (unit(v) * 255.0).round() as u8; let (w, h) = (u32::from(cols), u32::from(rows)); + // Overprinting on a plate: the cells of paper white put none of the ink down, so they are + // left out, as clear pixels at Level 3 and outside a clip of the other cells at Level 2. + let blank: Option> = self.keep_below.then(|| field.grid(area, cols, rows).map(|(c, _)| is_white(&Paint::solid(c))).collect()); + let blank = blank.filter(|b| b.contains(&true)); + if blank.as_ref().is_some_and(|b| !b.contains(&false)) { + return; + } + let keyed = self.o.level == Level::Three; + let clear = |i: usize, a: u8| if keyed && blank.as_ref().is_some_and(|b| b[i]) { 0 } else { a }; let image = if field.model() == Some(Model::Cmyk) || (self.cmyk && field.model() == Some(Model::Gray)) { let inks: Vec = field .grid(area, cols, rows) - .flat_map(|(color, a)| { + .enumerate() + .flat_map(|(i, (color, a))| { let [c, m, y, k] = color.to_cmyk(); - [q(c), q(m), q(y), q(k), q(a)] + [q(c), q(m), q(y), q(k), clear(i, q(a))] }) .collect(); self.encode_inks(&inks, w, h) } else { - let rgba: Vec = field.display_grid(area, cols, rows).flat_map(|(c, a)| [q(c[0]), q(c[1]), q(c[2]), q(a)]).collect(); + let rgba: Vec = + field.display_grid(area, cols, rows).enumerate().flat_map(|(i, (c, a))| [q(c[0]), q(c[1]), q(c[2]), clear(i, q(a))]).collect(); self.encode_image(&rgba, w, h) }; let Some(image) = image else { return }; + let cells = blank.filter(|_| !keyed).map(|b| { + let (cw, ch) = (area.width() / f64::from(cols), area.height() / f64::from(rows)); + let mut bp = BezPath::new(); + for (row, line) in b.chunks(usize::from(cols)).enumerate() { + let mut col = 0; + while col < line.len() { + let start = col; + while col < line.len() && !line[col] { + col += 1; + } + if col > start { + let (y0, y1) = (area.y0 + row as f64 * ch, area.y0 + (row + 1) as f64 * ch); + bp.extend(Rect::new(area.x0 + start as f64 * cw, y0, area.x0 + col as f64 * cw, y1).to_path(0.1).iter()); + } + col += 1; + } + } + bp + }); + if let Some(bp) = &cells { + // Each row's run of cells is a rectangle of five path elements, about 60 bytes. + if self.size().saturating_add(bp.elements().len().saturating_mul(12)).saturating_add(image.inline_len) > self.max_body { + self.warn(TOO_LARGE); + return; + } + self.line("q"); + self.clip_path(bp, FillRule::NonZero); + } + self.place_field(image, place); + if cells.is_some() { + self.line("Q"); + } + } + + /// Place freeform gradient image `image` on the unit square mapped by `place`, drawn from an + /// image already kept when one is encoded the same. + fn place_field(&mut self, image: ImageCode, place: Affine) { let key = image.content_key(); let found = self.fields.get(&key).and_then(|bucket| bucket.iter().copied().find(|&i| self.codes.get(i).is_some_and(|c| c.same_image(&image)))); @@ -1849,6 +2092,19 @@ fn image_code(prelude: String, dict: String, filter: &'static str, op: &'static code } +/// The closed polygon through `pts`. +fn polygon(pts: &[Point]) -> Vec { + let mut els: Vec = + pts.iter().enumerate().map(|(i, p)| if i == 0 { kurbo::PathEl::MoveTo(*p) } else { kurbo::PathEl::LineTo(*p) }).collect(); + els.push(kurbo::PathEl::ClosePath); + els +} + +/// The square with corners (±`t`, 0) and (0, ±`t`). +fn diamond(t: f64) -> Vec { + polygon(&[Point::new(t, 0.0), Point::new(0.0, t), Point::new(-t, 0.0), Point::new(0.0, -t)]) +} + /// `a` to `b` at `t`. fn mix(a: &[f32], b: &[f32], t: f32) -> Vec { a.iter().zip(b).map(|(x, y)| x + (y - x) * t).collect() diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index 8e7149cad2..e8f3c42b8e 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -9,6 +9,10 @@ //! are on disk, and the error names them. Where that copy of the old file can't be made, the file //! is left as it was and the save fails. //! +//! Work canceled ([`vectorcraft_doc::cancel`]) by the time the temporary file is written and flushed +//! puts nothing in place: the temporary file is removed, the file stays as it was (or absent), and +//! the error wraps [`vectorcraft_doc::cancel::Cancelled`]. +//! //! On macOS `File::sync_all` is a full flush (`F_FULLFSYNC`), which SMB shares refuse with //! `ENOTSUP` and virtiofs shares (folders shared into a macOS VM) with `ENOTTY`, while a plain //! `fsync` works: [`sync_file`] falls back to the plain one there (#1620). @@ -43,7 +47,8 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { } /// Write `path` atomically with `fill`, which writes the content into the temporary file. When -/// `fill` or flushing fails the temporary file is removed and `path` is left untouched. When the +/// `fill` or flushing fails, or the work was canceled meanwhile ([`vectorcraft_doc::cancel`]), the +/// temporary file is removed and `path` is left untouched. When the /// folder refuses the temporary file or the rename, the content is copied into `path` instead (see /// the module docs). pub fn write_atomic_with(path: &Path, fill: impl FnOnce(&mut File) -> io::Result<()>) -> io::Result<()> { @@ -79,7 +84,7 @@ fn write_atomic_stepping( (tmp, f, Some(e)) } }; - let filled = fill(&mut f).and_then(|()| sync_file(&f)); + let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled()); drop(f); if let Err(e) = filled { // Best effort: the temporary file is all there is to clean up. @@ -176,7 +181,7 @@ fn write_new_linking( ) -> io::Result<()> { let tmp = temp_path(path)?; let mut f = OpenOptions::new().write(true).create_new(true).open(&tmp)?; - let filled = fill(&mut f).and_then(|()| sync_file(&f)); + let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled()); drop(f); let placed = filled.and_then(|()| match link(&tmp, path) { Err(e) if e.kind() != io::ErrorKind::AlreadyExists => copy_new(&tmp, path), @@ -187,6 +192,12 @@ fn write_new_linking( placed } +/// `Err` wrapping [`vectorcraft_doc::cancel::Cancelled`] when the work running on this thread has +/// been canceled: the last check before a written temporary file is put in place. +fn not_cancelled() -> io::Result<()> { + vectorcraft_doc::cancel::check().map_err(io::Error::other) +} + /// Create `path` (never replacing anything) with the content of the file `from`; a failed copy /// removes it again. fn copy_new(from: &Path, path: &Path) -> io::Result<()> { @@ -408,6 +419,39 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// Work canceled by the time the temporary file is written and flushed puts nothing in place: + /// the old file stays as it was, also where the folder refuses the rename (no copy over it), a + /// new file is not created, and no temporary file is left. + #[test] + fn canceled_work_puts_nothing_in_place() { + use vectorcraft_doc::cancel::{CancelToken, Cancelled, scope}; + fn cancelled(e: &io::Error) -> bool { + e.get_ref().is_some_and(|e| e.is::()) + } + let d = dir("cancel"); + let path = d.join("doc.vectorcraft"); + std::fs::write(&path, b"original").unwrap(); + let token = CancelToken::new(); + let r = scope(&token, None, || { + write_atomic_with(&path, |f| { + f.write_all(b"new")?; + token.cancel(); + Ok(()) + }) + }); + assert!(r.as_ref().is_err_and(cancelled), "{r:?}"); + let refused = |_: &Path, _: &Path| -> io::Result<()> { Err(io::Error::from(io::ErrorKind::PermissionDenied)) }; + let r = scope(&token, None, || write_atomic_stepping(&path, |f| f.write_all(b"new"), create_new, refused)); + assert!(r.as_ref().is_err_and(cancelled), "{r:?}"); + assert_eq!(std::fs::read(&path).unwrap(), b"original"); + let new = d.join("new.vectorcraft"); + let r = scope(&token, None, || write_new_with(&new, |f| f.write_all(b"new"))); + assert!(r.as_ref().is_err_and(cancelled), "{r:?}"); + assert!(!new.exists()); + assert!(leftovers(&d, "doc.vectorcraft").is_empty(), "{:?}", leftovers(&d, "doc.vectorcraft")); + let _ = std::fs::remove_dir_all(&d); + } + #[test] fn the_original_file_survives_a_failed_write() { let d = dir("fail"); diff --git a/crates/geom/src/curvature.rs b/crates/geom/src/curvature.rs new file mode 100644 index 0000000000..304f20557e --- /dev/null +++ b/crates/geom/src/curvature.rs @@ -0,0 +1,424 @@ +//! The circle that touches a curve at one of its points with the curve's curvature there (its +//! osculating circle): the circle the curve bends along at that point. + +use kurbo::{CubicBez, ParamCurve, ParamCurveDeriv, Point, Vec2}; + +use crate::{AnchorKind, SubPath}; + +/// Why no circle matches a curve at a point. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NoCircle { + /// The curve is straight there (a straight segment, or the turn of an S curve): the circle + /// would have no end. + Straight, + /// The curve has no single direction there: a cusp, a handle drawn back onto its anchor, or a + /// segment with no length. + Cusp, + /// Two segments meet at an anchor at an angle: the path has no single direction there. + Corner, +} + +/// The circle that touches a curve at one point and bends as the curve does there. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CurvatureCircle { + /// The point where the circle touches the curve. + pub at: Point, + pub center: Point, + pub radius: f64, + /// The segment is the usual cubic of a circular arc of 90° or less ([`circular_arc`]), and the + /// circle has that arc's own radius rather than the cubic's curvature at the point. + pub nominal: bool, +} + +/// Largest turn (radians) of an arc that [`circular_arc`] takes: a quarter turn. +const MAX_ARC: f64 = std::f64::consts::FRAC_PI_2 * (1.0 + 1e-9); +/// How far apart (as a share of the radius) the arc's two ends may lie from its center. +const RADIUS_TOL: f64 = 1e-4; +/// How far each handle's length may differ from the circular arc's (as a share of it). +const HANDLE_TOL: f64 = 1e-3; +/// Below this sine of the angle between the curve's first two derivatives, the curve is straight. +const STRAIGHT_SIN: f64 = 1e-10; +/// Below this share of the control polygon's length, the curve's direction is not defined. +const CUSP_SHARE: f64 = 1e-9; +/// The largest turn (radians) at an anchor not marked smooth that still counts as smooth: half a +/// degree, which takes in handles rounded to a few decimals in imported files. +const SMOOTH_TURN: f64 = 0.5 * std::f64::consts::PI / 180.0; + +/// The circle that touches segment `c` at `t` (0 to 1) with its curvature there, on the side the +/// segment bends toward, or on the other side with `convex`. A segment that is the usual cubic of +/// a circular arc of 90° or less gives a circle of that arc's radius: on the concave side it is the +/// arc's own circle, and it touches the arc's circle at the point nearest `c` at `t`; on the convex +/// side it touches `c` at `t`, its center one radius out from there. A `t` outside 0 to +/// 1 and a segment whose points are not finite give [`NoCircle::Cusp`]. +pub fn curvature_circle(c: CubicBez, t: f64, convex: bool) -> Result { + let finite = [c.p0, c.p1, c.p2, c.p3].iter().all(|p| p.is_finite()); + if !finite || !(0.0..=1.0).contains(&t) { + return Err(NoCircle::Cusp); + } + let at = c.eval(t); + let (center, radius, nominal) = match circular_arc(c) { + Some((center, radius)) => { + let out = at - center; + let len = out.hypot(); + if len == 0.0 || !len.is_finite() { + return Err(NoCircle::Cusp); + } + if convex { + // One radius out from `at`, so the circle touches the segment at `at` even where + // the cubic strays a little from the arc's circle. + return Ok(CurvatureCircle { at, center: at + out * (radius / len), radius, nominal: true }); + } + // The point of the arc's circle nearest `at`: the circle touches the segment there. + let on = center + out * (radius / len); + return Ok(CurvatureCircle { at: on, center, radius, nominal: true }); + } + None => { + let (center, radius) = osculating(c, t)?; + (center, radius, false) + } + }; + let center = if convex { at + (at - center) } else { center }; + Ok(CurvatureCircle { at, center, radius, nominal }) +} + +/// [`curvature_circle`] at `t` on segment `seg` of `sp`. At an end of the segment where it meets +/// the next or previous segment at a corner, the path has no single direction: that is a +/// [`NoCircle::Corner`]. A segment `sp` lacks is a [`NoCircle::Cusp`]. Segments with no length +/// between the two are passed over, and a closed subpath with one segment of length meets itself. +/// The anchor is smooth when it is marked smooth, with both handles pulled out and no segment of no +/// length passed over to reach it, and the path turns there by less than 90°, or when +/// the two segments leave it within [`SMOOTH_TURN`] of one direction. +pub fn curvature_circle_on(sp: &SubPath, seg: usize, t: f64, convex: bool) -> Result { + let n = sp.segment_count(); + if seg >= n { + return Err(NoCircle::Cusp); + } + let c = sp.segment(seg); + let corner = if start_direction(c) == Vec2::ZERO { + false + } else if t == 0.0 { + neighbor(sp, seg, false).is_some_and(|(prev, skipped)| !smooth(sp, seg, skipped, end_direction(prev), start_direction(c))) + } else if t == 1.0 { + neighbor(sp, seg, true).is_some_and(|(next, skipped)| !smooth(sp, (seg + 1) % n, skipped, end_direction(c), start_direction(next))) + } else { + false + }; + if corner { + return Err(NoCircle::Corner); + } + curvature_circle(c, t, convex) +} + +/// The nearest segment with length before (or with `forward`, after) segment `seg`, and whether +/// segments with no length lay between; `None` at an open end of the subpath. In a closed subpath +/// whose only segment with length is `seg`, that is `seg` itself. +fn neighbor(sp: &SubPath, seg: usize, forward: bool) -> Option<(CubicBez, bool)> { + let n = sp.segment_count(); + for k in 1..=n { + let i = if forward { (seg + k < n || sp.closed).then(|| (seg + k) % n)? } else { (seg >= k || sp.closed).then(|| (seg + n - k) % n)? }; + let s = sp.segment(i); + if start_direction(s) != Vec2::ZERO { + return Some((s, k > 1)); + } + } + None +} + +/// Is the join at anchor `anchor` smooth: marked smooth (with no segment of no length passed +/// over) with the directions `a` into it and `b` out of it less than 90° apart, or `a` and `b` the +/// same within [`SMOOTH_TURN`]? +fn smooth(sp: &SubPath, anchor: usize, skipped: bool, a: Vec2, b: Vec2) -> bool { + let marked = !skipped && sp.anchors.get(anchor).is_some_and(|an| an.kind == AnchorKind::Smooth && an.has_in() && an.has_out()); + let (la, lb) = (a.hypot(), b.hypot()); + let ahead = la > 0.0 && lb > 0.0 && a.dot(b) > 0.0; + ahead && (marked || a.cross(b).abs() <= SMOOTH_TURN.sin() * la * lb) +} + +/// The direction a segment leaves its first anchor in: toward its first control point that is +/// not on that anchor; zero for a segment with no length. +fn start_direction(c: CubicBez) -> Vec2 { + [c.p1 - c.p0, c.p2 - c.p0, c.p3 - c.p0].into_iter().find(|v| v.hypot() > 0.0).unwrap_or_default() +} + +/// The direction a segment reaches its last anchor in, as [`start_direction`] finds it. +fn end_direction(c: CubicBez) -> Vec2 { + [c.p3 - c.p2, c.p3 - c.p1, c.p3 - c.p0].into_iter().find(|v| v.hypot() > 0.0).unwrap_or_default() +} + +/// The center and radius of the circle of curvature of `c` at `t`. +fn osculating(c: CubicBez, t: f64) -> Result<(Point, f64), NoCircle> { + let polygon = c.p0.distance(c.p1) + c.p1.distance(c.p2) + c.p2.distance(c.p3); + let d = c.deriv().eval(t).to_vec2(); + let dd = c.deriv().deriv().eval(t).to_vec2(); + let speed = d.hypot(); + if polygon <= 0.0 || !polygon.is_finite() { + return Err(NoCircle::Cusp); + } + // All four control points on one line: a straight segment, whatever its handles. + let (v1, v2, v3) = (c.p1 - c.p0, c.p2 - c.p0, c.p3 - c.p0); + if [v1.cross(v2), v1.cross(v3), v2.cross(v3)].iter().all(|a| a.abs() <= 1e-12 * polygon * polygon) { + return Err(NoCircle::Straight); + } + if speed <= CUSP_SHARE * polygon { + return Err(NoCircle::Cusp); + } + let cross = d.cross(dd); + if cross.abs() <= STRAIGHT_SIN * speed * dd.hypot().max(polygon) { + return Err(NoCircle::Straight); + } + // The center lies along the normal toward the side the curve turns to, `|d|² / cross` of the + // normal `(-d.y, d.x)` away: its length is the radius, `|d|³ / |cross|`. + let center = c.eval(t) + Vec2::new(-d.y, d.x) * (d.hypot2() / cross); + let radius = speed.powi(3) / cross.abs(); + if !center.is_finite() || !radius.is_finite() { + return Err(NoCircle::Straight); + } + Ok((center, radius)) +} + +/// The center and radius of the circular arc `c` draws, when it is the usual cubic of an arc of +/// 90° or less: its two ends are the same distance from the point where the lines square to its +/// handles meet, and each handle is `4/3 · tan(θ/4)` of the radius long for an arc of θ, pointing +/// along the arc. +pub fn circular_arc(c: CubicBez) -> Option<(Point, f64)> { + let (d0, d3, chord) = (c.p1 - c.p0, c.p3 - c.p2, c.p3 - c.p0); + let (l0, l3) = (d0.hypot(), d3.hypot()); + let usable = |v: f64| v.is_finite() && v != 0.0; + if !usable(l0) || !usable(l3) || !usable(chord.hypot()) || d0.dot(chord) <= 0.0 || d3.dot(chord) <= 0.0 { + return None; + } + // The ends' normals: p0 + s·n0 = p3 + u·n3. + let (n0, n3) = (Vec2::new(-d0.y, d0.x), Vec2::new(-d3.y, d3.x)); + let den = n0.cross(n3); + if den.abs() <= 1e-12 * l0 * l3 { + return None; + } + let center = c.p0 + n0 * (chord.cross(n3) / den); + let (r0, r3) = (c.p0.distance(center), c.p3.distance(center)); + let radius = (r0 + r3) / 2.0; + if !center.is_finite() || !usable(radius) || (r0 - r3).abs() > RADIUS_TOL * radius { + return None; + } + let (a, b) = (c.p0 - center, c.p3 - center); + let turn = a.cross(b).abs().atan2(a.dot(b)); + if turn.is_nan() || turn <= 0.0 || turn > MAX_ARC { + return None; + } + let handle = 4.0 / 3.0 * (turn / 4.0).tan() * radius; + ((l0 - handle).abs() <= HANDLE_TOL * handle && (l3 - handle).abs() <= HANDLE_TOL * handle).then_some((center, radius)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Anchor, shapes}; + use kurbo::Rect; + + /// Every segment of a circle drawn by [`shapes::ellipse`] is the usual cubic of a quarter + /// turn, and the circle at any point of it is the circle itself: radius 100, center (150, 150). + #[test] + fn the_curvature_circle_of_a_circle_is_the_circle() { + let pd = shapes::ellipse(Rect::new(50.0, 50.0, 250.0, 250.0)); + let sp = &pd.subpaths[0]; + for seg in 0..sp.segment_count() { + for t in [0.0, 0.3, 0.5, 1.0] { + let got = curvature_circle(sp.segment(seg), t, false).unwrap(); + assert!(got.nominal, "{seg} {t}"); + assert!((got.radius - 100.0).abs() < 1e-9 && got.center.distance(Point::new(150.0, 150.0)) < 1e-9, "{seg} {t}: {got:?}"); + assert!((got.at.distance(got.center) - 100.0).abs() < 1e-9, "the circle touches on its own edge"); + } + } + } + + /// A quarter circle of radius 10,000 whose handles are 0.09% longer than the usual cubic's still + /// counts as the arc, and its middle lies a few points off the arc's circle: on the convex side + /// the circle still touches the segment at that point, one radius from its center. + #[test] + fn the_convex_circle_of_a_near_arc_touches_the_segment() { + let r = 10_000.0; + let k = 4.0 / 3.0 * (std::f64::consts::FRAC_PI_8).tan() * r * 1.0009; + let c = CubicBez::new(Point::new(r, 0.0), Point::new(r, k), Point::new(k, r), Point::new(0.0, r)); + assert!(circular_arc(c).is_some()); + let at = c.eval(0.5); + assert!((at.distance(Point::ORIGIN) - r).abs() > 1.0, "the middle lies off the arc's circle"); + let got = curvature_circle(c, 0.5, true).unwrap(); + assert!(got.nominal); + assert_eq!(got.at, at); + assert!((got.center.distance(at) - got.radius).abs() < 1e-6, "{got:?}"); + assert!(got.center.distance(Point::ORIGIN) > got.radius, "the center is on the side away from the arc's"); + } + + /// The cubic's own radius of curvature on a quarter circle's segment is about 2.2% larger than + /// the circle's at its ends and 0.6% larger at its middle: the nominal radius is the circle's. + #[test] + fn a_circle_segment_bends_near_its_radius() { + let pd = shapes::ellipse(Rect::new(-100.0, -100.0, 100.0, 100.0)); + let seg = pd.subpaths[0].segment(0); + for t in [0.0, 0.5, 1.0] { + let (center, r) = osculating(seg, t).unwrap(); + assert!((r - 100.0).abs() < 2.5 && center.distance(Point::ORIGIN) < 2.5, "{t}: {center:?} {r}"); + } + } + + /// On the parabola y = x² / 200, the curvature at its vertex is 1/100: drawn as a cubic from + /// (-100, 50) to (100, 50), the circle at the middle has radius 100 and center (0, 100), above + /// the curve on the side it bends toward; Shift's other side puts the center at (0, -100). + #[test] + fn the_curvature_circle_at_a_parabola_vertex() { + // The quadratic (-100, 50), (0, -50), (100, 50) raised to a cubic. + let (p0, q, p3) = (Point::new(-100.0, 50.0), Point::new(0.0, -50.0), Point::new(100.0, 50.0)); + let c = CubicBez::new(p0, p0 + (q - p0) * (2.0 / 3.0), p3 + (q - p3) * (2.0 / 3.0), p3); + assert_eq!(circular_arc(c), None); + let got = curvature_circle(c, 0.5, false).unwrap(); + assert!(!got.nominal && got.at.distance(Point::ORIGIN) < 1e-9, "{got:?}"); + assert!((got.radius - 100.0).abs() < 1e-9 && got.center.distance(Point::new(0.0, 100.0)) < 1e-9, "{got:?}"); + let other = curvature_circle(c, 0.5, true).unwrap(); + assert!((other.radius - 100.0).abs() < 1e-9 && other.center.distance(Point::new(0.0, -100.0)) < 1e-9, "{other:?}"); + } + + /// A straight segment, with its handles on its line or on its anchors, and the + /// turning point of an S curve have no curvature circle. + #[test] + fn a_straight_segment_has_no_circle() { + let (a, b) = (Point::new(10.0, 20.0), Point::new(130.0, 70.0)); + let on_line = CubicBez::new(a, a.lerp(b, 0.3), a.lerp(b, 0.7), b); + assert_eq!(curvature_circle(on_line, 0.4, false), Err(NoCircle::Straight)); + // A line's handles sit on its anchors: straight at its ends too. + for t in [0.0, 0.5, 1.0] { + assert_eq!(curvature_circle(CubicBez::new(a, a, b, b), t, false), Err(NoCircle::Straight), "{t}"); + } + let s = CubicBez::new(Point::new(0.0, 0.0), Point::new(50.0, 50.0), Point::new(50.0, -50.0), Point::new(100.0, 0.0)); + assert_eq!(curvature_circle(s, 0.5, false), Err(NoCircle::Straight)); + assert!(curvature_circle(s, 0.25, false).is_ok()); + } + + /// A cusp, a handle drawn back onto its anchor at that end, a segment with no length, points + /// that are not finite and a `t` outside 0 to 1 have no curvature circle. + #[test] + fn a_cusp_has_no_circle() { + let cusp = CubicBez::new(Point::new(0.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0), Point::new(100.0, 0.0)); + assert_eq!(curvature_circle(cusp, 0.5, false), Err(NoCircle::Cusp)); + let p = Point::new(5.0, 5.0); + let retracted = CubicBez::new(Point::new(0.0, 0.0), Point::new(0.0, 0.0), Point::new(60.0, 40.0), Point::new(100.0, 0.0)); + assert_eq!(curvature_circle(retracted, 0.0, false), Err(NoCircle::Cusp)); + assert_eq!(curvature_circle(CubicBez::new(p, p, p, p), 0.5, false), Err(NoCircle::Cusp)); + let far = CubicBez::new(Point::new(f64::NAN, 0.0), p, p, Point::new(9.0, 0.0)); + assert_eq!(curvature_circle(far, 0.5, false), Err(NoCircle::Cusp)); + for t in [-0.1, 1.5, f64::NAN] { + assert_eq!(curvature_circle(cusp, t, false), Err(NoCircle::Cusp), "{t}"); + } + } + + /// At an anchor where a curve meets a line at a corner, the path has no single direction, from + /// either segment; at a smooth anchor of a circle, and at the open ends of a path, the circle is + /// drawn. A segment the subpath lacks has none. + #[test] + fn a_corner_anchor_has_no_circle() { + let bp = kurbo::BezPath::from_svg("M0 0 C50 -50 100 -50 150 0 L300 0").unwrap(); + let sp = &crate::PathData::from_bezpath(&bp).subpaths[0]; + assert_eq!(curvature_circle_on(sp, 0, 1.0, false), Err(NoCircle::Corner)); + assert_eq!(curvature_circle_on(sp, 1, 0.0, false), Err(NoCircle::Corner)); + assert_eq!(curvature_circle_on(sp, 1, 0.5, false), Err(NoCircle::Straight)); + assert!(curvature_circle_on(sp, 0, 0.0, false).is_ok() && curvature_circle_on(sp, 0, 0.5, false).is_ok()); + assert_eq!(curvature_circle_on(sp, 2, 0.5, false), Err(NoCircle::Cusp)); + let circle = &shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)).subpaths[0]; + for seg in 0..4 { + for t in [0.0, 1.0] { + assert!(curvature_circle_on(circle, seg, t, false).is_ok_and(|c| c.nominal), "{seg} {t}"); + } + } + // A closed triangle of curves: the anchor where the last segment meets the first is a corner. + let bp = kurbo::BezPath::from_svg("M0 0 C10 -10 90 -10 100 0 C110 10 60 90 50 100 C40 90 -10 30 0 0 Z").unwrap(); + let tri = &crate::PathData::from_bezpath(&bp).subpaths[0]; + assert!(tri.closed); + assert_eq!(curvature_circle_on(tri, 0, 0.0, false), Err(NoCircle::Corner)); + } + + /// A closed subpath whose only segment with length loops back to its start meets itself at its + /// point: a teardrop's tip is a corner, from both ends of the loop. + #[test] + fn a_loop_that_meets_itself_at_an_angle_has_no_circle_there() { + let a = Point::new(0.0, 0.0); + let tip = |out: Point, back: Point| SubPath::new(vec![Anchor::with_handles(a, a, out), Anchor::with_handles(a, back, a)], true); + let drop = tip(Point::new(100.0, -100.0), Point::new(100.0, 100.0)); + assert_eq!(drop.segment_count(), 2); + assert_eq!(curvature_circle_on(&drop, 0, 0.0, false), Err(NoCircle::Corner)); + assert_eq!(curvature_circle_on(&drop, 0, 1.0, false), Err(NoCircle::Corner)); + assert!(curvature_circle_on(&drop, 0, 0.5, false).is_ok()); + } + + /// A segment with no length between a curve and a line, or a closed subpath whose last anchor + /// repeats its first, still leaves a corner there: the segments with no length are passed over. + #[test] + fn a_corner_behind_a_segment_with_no_length_has_no_circle() { + let (a, b, c) = (Point::new(0.0, 0.0), Point::new(150.0, 0.0), Point::new(300.0, 0.0)); + let curve_in = Anchor::with_handles(b, Point::new(100.0, -50.0), b); + let open = SubPath::new(vec![Anchor::with_handles(a, a, Point::new(50.0, -50.0)), curve_in, Anchor::corner(b), Anchor::corner(c)], false); + assert_eq!(curvature_circle_on(&open, 0, 1.0, false), Err(NoCircle::Corner)); + assert_eq!(curvature_circle_on(&open, 2, 0.0, false), Err(NoCircle::Corner), "from the line's side too"); + assert_eq!(curvature_circle_on(&open, 2, 0.5, false), Err(NoCircle::Straight)); + // A closed triangle of curves drawn back to its first anchor before it closes. + let tri = SubPath::new( + vec![ + Anchor::with_handles(a, a, Point::new(10.0, -10.0)), + Anchor::with_handles(Point::new(100.0, 0.0), Point::new(90.0, -10.0), Point::new(110.0, 10.0)), + Anchor::with_handles(Point::new(50.0, 100.0), Point::new(60.0, 90.0), Point::new(40.0, 90.0)), + Anchor::with_handles(a, Point::new(-10.0, 30.0), a), + ], + true, + ); + assert_eq!(tri.segment_count(), 4); + assert_eq!(curvature_circle_on(&tri, 0, 0.0, false), Err(NoCircle::Corner)); + assert_eq!(curvature_circle_on(&tri, 2, 1.0, false), Err(NoCircle::Corner)); + } + + /// An anchor whose handles turn by a thousandth of a radian, as rounded coordinates leave them, + /// is smooth; one marked smooth is smooth unless its handles turn by 90° or more; a turn of 2° + /// is a corner. + #[test] + fn a_nearly_smooth_or_marked_smooth_anchor_has_a_circle() { + let mid = |out_x: f64, kind: AnchorKind| { + let p = Point::new(100.0, 0.0); + let mut an = Anchor::with_handles(p, Point::new(100.0, -50.0), Point::new(out_x, 50.0)); + an.kind = kind; + let ends = |q: Point, h: Point| Anchor::with_handles(q, h, h); + SubPath::new(vec![ends(Point::new(0.0, 0.0), Point::new(0.0, -50.0)), an, ends(Point::new(0.0, 100.0), Point::new(0.0, 150.0))], false) + }; + let rounded = mid(100.05, AnchorKind::Corner); + assert!(curvature_circle_on(&rounded, 0, 1.0, false).is_ok() && curvature_circle_on(&rounded, 1, 0.0, false).is_ok()); + let turned = 50.0 * 2f64.to_radians().tan(); + assert_eq!(curvature_circle_on(&mid(100.0 - turned, AnchorKind::Corner), 0, 1.0, false), Err(NoCircle::Corner)); + assert!(curvature_circle_on(&mid(100.0 - turned, AnchorKind::Smooth), 0, 1.0, false).is_ok()); + // Marked smooth, with the out handle pointing back along the in handle. + let mut back = mid(100.0, AnchorKind::Smooth); + back.anchors.get_mut(1).unwrap().h_out = Point::new(100.0, -40.0); + assert_eq!(curvature_circle_on(&back, 0, 1.0, false), Err(NoCircle::Corner)); + assert_eq!(curvature_circle_on(&back, 1, 0.0, false), Err(NoCircle::Corner)); + // Marked smooth, with the out handle square to the in handle: a turn of 90°. + let mut square = mid(100.0, AnchorKind::Smooth); + square.anchors.get_mut(1).unwrap().h_out = Point::new(150.0, 0.0); + assert_eq!(curvature_circle_on(&square, 0, 1.0, false), Err(NoCircle::Corner)); + } + + /// An arc's cubic is taken only up to a quarter turn, with both ends on one circle and handles + /// of the arc's length: a third of a circle, a circle squashed into an ellipse and handles 1% + /// too long give the cubic's own curvature. + #[test] + fn only_a_true_arc_of_a_quarter_turn_or_less_is_nominal() { + let arc = |deg: f64, r: f64, stretch: f64, handle: f64| { + let th = deg.to_radians(); + let k = 4.0 / 3.0 * (th / 4.0).tan() * r * handle; + let (p0, p3) = (Point::new(r, 0.0), Point::new(r * th.cos() * stretch, r * th.sin())); + CubicBez::new(p0, p0 + Vec2::new(0.0, k), p3 + Vec2::new(th.sin(), -th.cos()) * k, p3) + }; + let (center, r) = circular_arc(arc(60.0, 50.0, 1.0, 1.0)).unwrap(); + assert!(center.distance(Point::ORIGIN) < 1e-9 && (r - 50.0).abs() < 1e-9); + assert!(circular_arc(arc(90.0, 50.0, 1.0, 1.0)).is_some()); + assert_eq!(circular_arc(arc(120.0, 50.0, 1.0, 1.0)), None); + assert_eq!(circular_arc(arc(60.0, 50.0, 1.1, 1.0)), None); + assert_eq!(circular_arc(arc(60.0, 50.0, 1.0, 1.01)), None); + // On the convex side, the circle touches the arc's circle from outside. + let c = curvature_circle(arc(60.0, 50.0, 1.0, 1.0), 0.0, true).unwrap(); + assert!(c.nominal && c.center.distance(Point::new(100.0, 0.0)) < 1e-9 && (c.radius - 50.0).abs() < 1e-9, "{c:?}"); + } +} diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index 7d3e3f0f4b..3f11c71062 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -11,6 +11,7 @@ pub mod anchors; pub mod arc; pub mod bez; pub mod corners; +pub mod curvature; pub mod hit; pub mod path; pub mod projective; diff --git a/crates/geom/src/path.rs b/crates/geom/src/path.rs index c5343171ef..abd72b255e 100644 --- a/crates/geom/src/path.rs +++ b/crates/geom/src/path.rs @@ -158,10 +158,56 @@ impl Anchor { let dir = p - pos; let l = dir.hypot(); if l > 1e-9 { - *other = p + dir * (len / l); + let turned = p + dir * (len / l); + if turned.is_finite() { + *other = turned; + } else { + // Long handles overflow the squares above: measure with `f64::hypot` and scale + // the unit direction, leaving the handle where it is if that is not finite. + let (v, l) = (*other - p, dir.x.hypot(dir.y)); + let turned = p + (dir / l) * v.x.hypot(v.y); + if turned.is_finite() { + *other = turned; + } + } } } } + /// Place the end of the outgoing (`out`) or incoming handle at `pos` and make the anchor smooth: + /// the other handle turns to lie in line with it on the far side of the anchor, at its own + /// length. A retracted other handle is pulled out to the moved handle's length when `pull_out` + /// and stays retracted otherwise. A handle placed on the anchor, or where the turned handle's + /// end would not be a finite point, gives no direction: it is placed, and the other handle and + /// the anchor's kind stay as they are. + pub fn link_handle(&mut self, out: bool, pos: Point, pull_out: bool) { + let p = self.p; + let (moved, other) = if out { (&mut self.h_out, &mut self.h_in) } else { (&mut self.h_in, &mut self.h_out) }; + *moved = pos; + // `f64::hypot` keeps long handles from overflowing the square of their length. + let dir = p - pos; + let l = dir.x.hypot(dir.y); + if !(l > EPS && l.is_finite()) { + return; + } + let v = *other - p; + let len = v.x.hypot(v.y); + let len = if len > EPS { + len + } else if pull_out { + l + } else { + 0.0 + }; + if len > 0.0 { + // The unit direction first, so a short handle does not overflow the scale factor. + let turned = p + (dir / l) * len; + if !turned.is_finite() { + return; + } + *other = turned; + } + self.kind = AnchorKind::Smooth; + } /// Swap handles (used when reversing path direction). pub fn reversed(&self) -> Self { Self { p: self.p, h_in: self.h_out, h_out: self.h_in, kind: self.kind } @@ -280,6 +326,11 @@ impl SubPath { pub fn polyline(points: &[Point], closed: bool) -> Self { Self { anchors: points.iter().map(|&p| Anchor::corner(p)).collect(), closed } } + /// Whether anchor `ai` has a segment on its outgoing (`out`) or incoming side. + pub fn has_segment(&self, ai: usize, out: bool) -> bool { + let n = self.anchors.len(); + ai < n && n > 1 && (self.closed || if out { ai + 1 < n } else { ai > 0 }) + } /// Number of segments (a closed path has one more, back to the start). pub fn segment_count(&self) -> usize { let n = self.anchors.len(); @@ -1103,4 +1154,73 @@ mod tests { let back: PathData = serde_json::from_str(&s).unwrap(); assert_eq!(p, back); } + + /// `link_handle` makes a corner smooth: the other handle turns onto the far side of the anchor + /// at its own length; a retracted one is pulled out to the moved handle's length only when + /// asked, and a handle placed on the anchor changes nothing else. + #[test] + fn link_handle_makes_a_corner_smooth_keeping_the_other_length() { + let p = Point::new(10.0, 10.0); + let mut a = Anchor { p, h_in: Point::new(10.0, 0.0), h_out: Point::new(13.0, 10.0), kind: AnchorKind::Corner }; + a.link_handle(true, Point::new(14.0, 13.0), false); + assert_eq!(a.kind, AnchorKind::Smooth); + assert_eq!(a.h_out, Point::new(14.0, 13.0)); + // The in handle keeps its length of 10, opposite the out handle's direction (4, 3) / 5. + assert!(a.h_in.distance(Point::new(2.0, 4.0)) < 1e-9, "{:?}", a.h_in); + + let retracted = Anchor { p, h_in: p, h_out: Point::new(13.0, 10.0), kind: AnchorKind::Corner }; + let mut pulled = retracted; + pulled.link_handle(true, Point::new(13.0, 14.0), true); + assert_eq!((pulled.kind, pulled.h_in), (AnchorKind::Smooth, Point::new(7.0, 6.0))); + let mut kept = retracted; + kept.link_handle(true, Point::new(13.0, 14.0), false); + assert_eq!((kept.kind, kept.h_in), (AnchorKind::Smooth, p)); + + let mut on_anchor = Anchor { p, h_in: Point::new(10.0, 0.0), h_out: Point::new(13.0, 10.0), kind: AnchorKind::Corner }; + on_anchor.link_handle(false, p, true); + assert_eq!(on_anchor, Anchor { p, h_in: p, h_out: Point::new(13.0, 10.0), kind: AnchorKind::Corner }); + + // A handle so far away that its distance overflows leaves the other handle finite. + let far = Point::new(1.7e308, 1.7e308); + let mut overflow = retracted; + overflow.link_handle(true, far, true); + assert_eq!(overflow, Anchor { p, h_in: p, h_out: far, kind: AnchorKind::Corner }); + // A very long other handle turned by a very short one stays finite, at its own length. + let mut long = Anchor { p: Point::ZERO, h_in: Point::new(1e308, 0.0), h_out: Point::ZERO, kind: AnchorKind::Corner }; + long.link_handle(true, Point::new(0.0, 1e-8), false); + assert_eq!((long.kind, long.h_in), (AnchorKind::Smooth, Point::new(0.0, -1e308))); + // One whose turned end would leave the finite range is left where it is. + let edge = Point::new(-1.5e308, 0.0); + let mut beyond = Anchor { p: edge, h_in: Point::new(1.5e308, 0.0), h_out: edge, kind: AnchorKind::Corner }; + beyond.link_handle(true, Point::new(-1.5e308 + 1e300, 0.0), false); + assert_eq!((beyond.kind, beyond.h_in), (AnchorKind::Corner, Point::new(1.5e308, 0.0))); + } + + /// `set_handle` on a smooth anchor turns a very long other handle without overflowing, and + /// leaves it where it is when its turned end would not be a finite point. + #[test] + fn set_handle_on_a_smooth_anchor_keeps_long_handles_finite() { + let mut long = Anchor { p: Point::ZERO, h_in: Point::new(-1e308, 0.0), h_out: Point::new(1.0, 0.0), kind: AnchorKind::Smooth }; + long.set_handle(true, Point::new(0.0, 1e-8), false); + assert_eq!(long.h_in, Point::new(0.0, -1e308)); + let edge = Point::new(-1.5e308, 0.0); + let mut beyond = Anchor { p: edge, h_in: Point::new(-1.6e308, 0.0), h_out: Point::new(1.5e308, 0.0), kind: AnchorKind::Smooth }; + beyond.set_handle(false, Point::new(-1.5e308 + 1e300, 0.0), false); + assert_eq!(beyond.h_out, Point::new(1.5e308, 0.0)); + } + + /// `has_segment` sees a segment on each side of an inner anchor, none past an open path's ends, + /// and both sides on a closed path of two anchors or more. + #[test] + fn has_segment_follows_the_open_ends() { + let pts = [Point::ZERO, Point::new(10.0, 0.0), Point::new(10.0, 10.0)]; + let open = SubPath::polyline(&pts, false); + assert!(!open.has_segment(0, false) && open.has_segment(0, true)); + assert!(open.has_segment(1, false) && open.has_segment(1, true)); + assert!(open.has_segment(2, false) && !open.has_segment(2, true)); + assert!(!open.has_segment(3, false)); + let closed = SubPath::polyline(&pts, true); + assert!(closed.has_segment(0, false) && closed.has_segment(2, true)); + assert!(!SubPath::polyline(&pts[..1], true).has_segment(0, true)); + } } diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 838015115b..5641900186 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -441,6 +441,96 @@ pub fn straight_star_inner_radius(r1: f64, points: u32) -> f64 { r1 * (PI / n * 2.0).cos() / (PI / n).cos() } +/// The smallest circle that holds every one of `points`: its center and radius. Points that are +/// not finite are skipped; `None` when no finite point is left. One point gives a circle of +/// radius 0 around it. +pub fn enclosing_circle(points: &[Point]) -> Option<(Point, f64)> { + let mut world = convex_hull(points.iter().copied().filter(|p| p.is_finite()).collect()); + // A fixed shuffle keeps the expected work linear for any order of the points, and the same + // points always give the same circle. + let mut seed: u64 = 0x9E37_79B9_7F4A_7C15; + for i in (1..world.len()).rev() { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + world.swap(i, (seed % (i as u64 + 1)) as usize); + } + // The work is done relative to one of the points, so the rounding allowance in `holds` scales + // with the size of the points' spread, not with their distance from the origin. + let origin = *world.first()?; + let rel = |p: &Point| (*p - origin).to_point(); + let first = Point::ORIGIN; + let holds = |(c, r): (Point, f64), p: Point| (p - c).hypot() <= r + 1e-12 * (r + c.to_vec2().hypot()); + let diameter = |a: Point, b: Point| (a.midpoint(b), (b - a).hypot() / 2.0); + let mut circle = (first, 0.0); + for (i, pi) in world.iter().map(rel).enumerate().skip(1) { + if holds(circle, pi) { + continue; + } + circle = (pi, 0.0); + for (j, pj) in world.iter().map(rel).enumerate().take(i) { + if holds(circle, pj) { + continue; + } + circle = diameter(pi, pj); + for pk in world[..j].iter().map(rel) { + if holds(circle, pk) { + continue; + } + circle = circle_through(pi, pj, pk).unwrap_or_else(|| { + // Three points on one line: the circle on the two farthest apart. + let pairs = [(pi, pj), (pj, pk), (pk, pi)]; + let far = pairs.into_iter().fold((pi, pj), |a, b| if (b.1 - b.0).hypot2() > (a.1 - a.0).hypot2() { b } else { a }); + diameter(far.0, far.1) + }); + } + } + } + // The radius reaches the farthest point from the center returned, whatever rounding the steps + // above and the move back from `origin` left. + let center = circle.0 + origin.to_vec2(); + let radius = world.iter().map(|p| (*p - center).hypot()).fold(0.0, f64::max); + (center.is_finite() && radius.is_finite()).then_some((center, radius)) +} + +/// The corners of the convex hull of `points`, counter-clockwise in a y-up frame, without points +/// on its edges. Fewer than three points, or points on one line, give their ends. Points that are +/// not finite are left out. +pub fn convex_hull(mut points: Vec) -> Vec { + points.retain(|p| p.is_finite()); + // -0.0 and 0.0 are one coordinate: adding 0.0 turns -0.0 into 0.0, so the sort below puts + // points with the same x in y order. + for p in &mut points { + *p = Point::new(p.x + 0.0, p.y + 0.0); + } + points.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y))); + points.dedup(); + if points.len() < 3 { + return points; + } + // Andrew's monotone chain: the lower chain left to right, then the upper chain right to left. + let mut hull: Vec = Vec::with_capacity(points.len() + 1); + chain(&mut hull, points.iter().copied()); + chain(&mut hull, points.iter().rev().copied()); + hull +} + +/// Adds to `hull` the chain of `points` that turns left at every corner, without its last point, +/// which starts the next chain. +fn chain(hull: &mut Vec, points: impl Iterator) { + let start = hull.len(); + for p in points { + while let [.., o, a] = hull[start..] { + if (a - o).cross(p - o) > 0.0 { + break; + } + hull.pop(); + } + hull.push(p); + } + hull.pop(); +} + /// Open straight line. pub fn line(a: Point, b: Point) -> PathData { PathData::single(SubPath::polyline(&[a, b], false)) @@ -795,6 +885,87 @@ mod tests { assert_eq!(circle_through(a, b, Point::new(0.0, 1e-12)), None); } + /// The smallest circle around a set of points: two points far apart are its diameter and the + /// points between them change nothing; an acute triangle's corners lie on it; a right triangle + /// is held by the circle on its hypotenuse; and points on one line give the circle on the two + /// ends. + #[test] + fn the_enclosing_circle_is_the_smallest_that_holds_every_point() { + let near = |(c, r): (Point, f64), want: Point, wr: f64| c.distance(want) < 1e-9 && (r - wr).abs() < 1e-9; + let pts = [Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(5.0, 1.0), Point::new(4.0, -2.0)]; + let got = enclosing_circle(&pts).unwrap(); + assert!(near(got, Point::new(5.0, 0.0), 5.0), "{got:?}"); + // An equilateral triangle of side 6: radius 6 / √3, center at its centroid. + let h = 27.0_f64.sqrt(); + let tri = [Point::new(0.0, 0.0), Point::new(6.0, 0.0), Point::new(3.0, h), Point::new(3.0, 1.0)]; + let got = enclosing_circle(&tri).unwrap(); + assert!(near(got, Point::new(3.0, h / 3.0), 6.0 / 3.0_f64.sqrt()), "{got:?}"); + let right = [Point::new(0.0, 0.0), Point::new(8.0, 0.0), Point::new(0.0, 6.0)]; + assert!(near(enclosing_circle(&right).unwrap(), Point::new(4.0, 3.0), 5.0)); + let line: Vec = (0..20).map(|i| Point::new(f64::from(i), 2.0 * f64::from(i))).collect(); + let got = enclosing_circle(&line).unwrap(); + assert!(near(got, Point::new(9.5, 19.0), Point::new(19.0, 38.0).distance(Point::ORIGIN) / 2.0), "{got:?}"); + } + + /// Many points on a circle, in any order and far from the origin, give that circle; every + /// point is held. One point gives a circle of radius 0, and no finite point gives none. + #[test] + fn the_enclosing_circle_holds_every_point_in_any_order() { + let c = Point::new(4.0e5, -3.0e5); + let mut pts: Vec = (0..997).map(|i| c + Vec2::from_angle(f64::from(i) * 0.37) * 120.0).collect(); + pts.extend((0..500).map(|i| c + Vec2::from_angle(f64::from(i)) * (f64::from(i % 97) + 1.0))); + for order in 0..3 { + if order == 1 { + pts.reverse(); + } else if order == 2 { + pts.sort_by(|a, b| a.x.total_cmp(&b.x)); + } + let (center, r) = enclosing_circle(&pts).unwrap(); + assert!(center.distance(c) < 1e-6 && (r - 120.0).abs() < 1e-6, "{center:?} {r}"); + assert!(pts.iter().all(|p| p.distance(center) <= r + 1e-9), "a point is outside"); + } + // Small art far from the origin keeps its smallest circle. + let far = [Point::new(1.0e12, 5.0), Point::new(1.0e12 + 1.0, 5.0)]; + assert_eq!(enclosing_circle(&far), Some((Point::new(1.0e12 + 0.5, 5.0), 0.5))); + // Where the center rounds on its way back from the first point, the radius still reaches + // every point from the center returned. + let wide = [Point::new(2f64.powi(53), 0.0), Point::new(2f64.powi(53) + 2.0, 0.0)]; + let (center, r) = enclosing_circle(&wide).unwrap(); + assert!(wide.iter().all(|p| p.distance(center) <= r), "{center:?} {r}"); + let one = Point::new(3.0, 4.0); + assert_eq!(enclosing_circle(&[one, one, Point::new(f64::NAN, 1.0)]), Some((one, 0.0))); + assert_eq!(enclosing_circle(&[]), None); + assert_eq!(enclosing_circle(&[Point::new(f64::INFINITY, 0.0)]), None); + } + + /// The hull keeps a square's corners counter-clockwise (y up) from the lowest-leftmost one, + /// without points inside, points on its edges, repeated corners or points that are not finite; + /// points on one line give their ends, and one or two points give themselves. + #[test] + fn the_convex_hull_keeps_only_the_corners() { + let p = Point::new; + let pts = vec![ + p(5.0, 5.0), + p(10.0, 10.0), + p(0.0, 10.0), + p(5.0, 0.0), + p(0.0, 0.0), + p(10.0, 0.0), + p(10.0, 10.0), + p(0.0, 5.0), + p(f64::NAN, 3.0), + p(2.0, 7.0), + ]; + assert_eq!(convex_hull(pts), vec![p(0.0, 0.0), p(10.0, 0.0), p(10.0, 10.0), p(0.0, 10.0)]); + let line: Vec = (0..9).rev().map(|i| p(f64::from(i), 2.0 * f64::from(i))).collect(); + assert_eq!(convex_hull(line), vec![p(0.0, 0.0), p(8.0, 16.0)]); + assert_eq!(convex_hull(vec![p(3.0, 1.0), p(1.0, 2.0)]), vec![p(1.0, 2.0), p(3.0, 1.0)]); + assert_eq!(convex_hull(vec![p(1.0, 1.0), p(1.0, 1.0)]), vec![p(1.0, 1.0)]); + assert_eq!(convex_hull(vec![p(f64::INFINITY, 1.0)]), vec![]); + // -0.0 is 0.0: the three points lie on one line, and the hull is its two ends. + assert_eq!(convex_hull(vec![p(-0.0, 10.0), p(0.0, 0.0), p(0.0, 5.0)]), vec![p(0.0, 0.0), p(0.0, 10.0)]); + } + #[test] fn rect_is_4_corners_clockwise() { let p = rectangle(Rect::new(0.0, 0.0, 100.0, 50.0)); diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 98327a2b61..380d161ecf 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -327,7 +327,7 @@ fn install_errors(interp: &mut Interp, object_proto: ObjId) -> JsResult<()> { for (i, (name, f)) in kinds.into_iter().enumerate() { // Error.prototype and each NativeError prototype are Error objects (sections 15.11.4 and // 15.11.7.7). - let proto = alloc(interp, Class::Error, Some(if i == 0 { object_proto } else { error_proto })); + let proto = alloc(interp, Class::Error(None), Some(if i == 0 { object_proto } else { error_proto })); if i == 0 { error_proto = proto; method(interp, proto, "toString", error_to_string, 0)?; diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 3b96953e8d..f612b00138 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -215,7 +215,9 @@ pub(crate) enum Class { length_writable: bool, }, Function(Func), - Error, + /// An error object. One the interpreter threw itself holds a hash of the description it had + /// then ([`crate::interp::Interp::describe`]); one a script made holds `None`. + Error(Option), Arguments(Box), /// A `Boolean` object made by ToObject, with its primitive value. Boolean(bool), @@ -313,7 +315,7 @@ impl Class { Class::Ordinary | Class::ForIn(_) => "Object", Class::Array { .. } => "Array", Class::Function(_) => "Function", - Class::Error => "Error", + Class::Error(_) => "Error", Class::Arguments(_) => "Arguments", Class::Boolean(_) => "Boolean", Class::Number(_) => "Number", diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index d81e12f3ac..24c33d2fc5 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -48,6 +48,14 @@ fn internal(message: &str) -> JsResult { Err(Abrupt::Internal(message.into())) } +/// The hash an error the interpreter throws keeps of its description ([`Interp::throw`]). +fn description_hash(text: &str) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::hash::DefaultHasher::new(); + text.hash(&mut h); + h.finish() +} + /// The kinds of error object the engine throws. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum ErrorType { @@ -60,6 +68,21 @@ pub(crate) enum ErrorType { Uri, } +impl ErrorType { + /// The `name` the prototype of this kind of error has before a script changes it. + pub(crate) fn name(self) -> &'static str { + match self { + ErrorType::Error => "Error", + ErrorType::Eval => "EvalError", + ErrorType::Range => "RangeError", + ErrorType::Reference => "ReferenceError", + ErrorType::Syntax => "SyntaxError", + ErrorType::Type => "TypeError", + ErrorType::Uri => "URIError", + } + } +} + /// The objects the interpreter itself refers to. #[derive(Clone, Copy, Debug)] pub(crate) struct Intrinsics { @@ -538,15 +561,34 @@ impl Interp { pub(crate) fn error_object(&mut self, t: ErrorType, message: &str) -> ObjId { let proto = self.intrinsics.error_proto(t); - let mut o = Object::new(Class::Error, Some(proto)); + let mut o = Object::new(Class::Error(None), Some(proto)); if !message.is_empty() { o.props.insert(key("message"), Prop::Data { value: Value::str(message), flags: HIDDEN }); } self.heap.alloc_object(o) } + /// An error of the interpreter's or a host function's own, marked as such with a hash of the + /// description it has with its kind's own name ([`Self::thrown_by_script`]), so a name a script + /// gave the kind's prototype before the error was made counts as the script's text. pub(crate) fn throw(&mut self, t: ErrorType, message: &str) -> Abrupt { - Abrupt::Throw(Value::Object(self.error_object(t, message))) + let o = self.error_object(t, message); + let own = if message.is_empty() { t.name().to_string() } else { format!("{}: {message}", t.name()) }; + if let Some(object) = self.heap.object_mut(o) { + object.class = Class::Error(Some(description_hash(&own))); + } + Abrupt::Throw(Value::Object(o)) + } + + /// Is the text [`Self::describe`] gives for the thrown value `v` the script's own? It is unless + /// `v` is an error the interpreter or a host function threw, with its name and message as they + /// were then: a value the script threw, an error it made, and an error whose name or message it + /// changed all hold its own text. + pub(crate) fn thrown_by_script(&mut self, v: &Value) -> bool { + let Value::Object(o) = v else { return true }; + let Some(Class::Error(Some(hash))) = self.heap.object(*o).map(|o| &o.class) else { return true }; + let hash = *hash; + description_hash(&self.describe(v)) != hash } pub(crate) fn type_error(&mut self, message: &str) -> Abrupt { @@ -819,7 +861,7 @@ impl Interp { let passed = matches!((&v, std::mem::replace(&mut self.passing, Value::Undefined)), (Value::Object(a), Value::Object(b)) if *a == b); if !passed && let Value::Object(o) = v - && self.heap.object(o).is_some_and(|o| matches!(o.class, Class::Error)) + && self.heap.object(o).is_some_and(|o| matches!(o.class, Class::Error(_))) { self.last_error = v.clone(); } diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index 9f9c59a96f..bfe358bc20 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -239,6 +239,44 @@ fn errors_carry_line_and_column() { assert_eq!(e.message, "42"); } +/// A run error says whether its message is the script's own text, whatever that text reads: an +/// error the interpreter or a host function threw is not, even when a script caught it and threw +/// it again, and a value or error the script made, or an error whose name or message it changed, +/// is. +#[test] +fn script_error_origin_distinguishes_native_and_authored_values() { + let native = "RangeError: invalid array length"; + for (src, message, authored) in [ + ("new Array(-1)", native, false), + ("try { new Array(-1); } catch (e) { throw e; }", native, false), + ("try { new Array(-1); } catch (e) { e.message = 'invalid array length'; throw e; }", native, false), + ("nope()", "ReferenceError: nope is not defined", false), + ("throw new RangeError('invalid array length')", native, true), + ("throw new Error('invalid array length')", "Error: invalid array length", true), + ("throw 'invalid array length'", "invalid array length", true), + ("throw 17", "17", true), + ("throw {}", "[object Object]", true), + ("throw new Error()", "Error", true), + ("try { new Array(-1); } catch (e) { throw e.message; }", "invalid array length", true), + ("try { new Array(-1); } catch (e) { throw new RangeError(e.message); }", native, true), + ("try { new Array(-1); } catch (e) { e.message = 'mine'; throw e; }", "RangeError: mine", true), + ("try { nope(); } catch (e) { e.name = 'TypeError'; throw e; }", "TypeError: nope is not defined", true), + ("try { new Array(-1); } catch (e) { RangeError.prototype.name = 'Mine'; throw e; }", "Mine: invalid array length", true), + ("RangeError.prototype.name = 'Mine'; new Array(-1)", "Mine: invalid array length", true), + ("RangeError.prototype.name = 'RangeError'; new Array(-1)", native, false), + ] { + let e = fail(src); + assert_eq!((e.kind, e.message.as_str(), e.authored), (RunErrorKind::Thrown, message, authored), "{src}"); + } + assert!(!fail("var x = ;").authored, "a syntax error"); + let mut realm = Realm::new(); + realm.define_function("add", |_| Err("add takes two numbers".into())); + let e = realm.run("add()").unwrap_err(); + assert_eq!((e.message.as_str(), e.authored), ("Error: add takes two numbers", false), "a host function's error"); + let e = realm.run("throw new Error('add takes two numbers')").unwrap_err(); + assert_eq!((e.message.as_str(), e.authored), ("Error: add takes two numbers", true)); +} + /// An error about a property of `null` or `undefined` names a computed property whose name is a /// primitive, and says whether the script read or set it, never naming an empty property; a /// member assignment, an object key and a long name leave the name out. diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 0a1006a23c..d675e82ec7 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -139,6 +139,10 @@ pub struct RunError { pub message: String, pub line: u32, pub column: u32, + /// `message` is text the script supplied: a value it threw, or an error object it made or whose + /// name or message it changed. False for the interpreter's and host functions' own errors, + /// syntax errors and limits, even when a script caught one and threw it again. + pub authored: bool, } impl std::fmt::Display for RunError { @@ -151,7 +155,7 @@ impl std::error::Error for RunError {} impl From for RunError { fn from(e: SyntaxError) -> Self { - RunError { kind: RunErrorKind::Syntax, message: e.to_string(), line: e.line, column: e.column } + RunError { kind: RunErrorKind::Syntax, message: e.to_string(), line: e.line, column: e.column, authored: false } } } @@ -241,7 +245,7 @@ impl Realm { self.script_tag = UNKNOWN_SOURCE; let interp = &mut self.interp; if let Some(message) = &interp.install_error { - return Err(RunError { kind: RunErrorKind::Internal, message: message.clone(), line: 0, column: 0 }); + return Err(RunError { kind: RunErrorKind::Internal, message: message.clone(), line: 0, column: 0, authored: false }); } interp.fuel = interp.limits.fuel; interp.flattened_fuel.set(0); @@ -269,7 +273,7 @@ impl Realm { interp.error_tag = self.script_tag; Err(e.into()) } - Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0 }), + Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0, authored: false }), } } @@ -293,15 +297,18 @@ impl Realm { Ok(v) => Ok(interp.to_js_value(&v)), Err(Abrupt::Throw(v)) => { let message = interp.describe(&v); + let authored = interp.thrown_by_script(&v); interp.last_thrown = v; - Err(RunError { kind: RunErrorKind::Thrown, message, line, column }) + Err(RunError { kind: RunErrorKind::Thrown, message, line, column, authored }) } Err(Abrupt::Limit(LimitKind::Host)) => { let message = interp.host_abort.take().unwrap_or_else(|| format!("limit reached: {:?}", LimitKind::Host)); - Err(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line, column }) + Err(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line, column, authored: false }) } - Err(Abrupt::Limit(kind)) => Err(RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line, column }), - Err(Abrupt::Internal(message)) => Err(RunError { kind: RunErrorKind::Internal, message, line, column }), + Err(Abrupt::Limit(kind)) => { + Err(RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line, column, authored: false }) + } + Err(Abrupt::Internal(message)) => Err(RunError { kind: RunErrorKind::Internal, message, line, column, authored: false }), } } @@ -323,10 +330,16 @@ impl Realm { pub fn advance(&mut self, slice: u64) -> Result { let interp = &mut self.interp; if interp.frames.is_empty() { - return Err(RunError { kind: RunErrorKind::Internal, message: "no run to advance".into(), line: 0, column: 0 }); + return Err(RunError { kind: RunErrorKind::Internal, message: "no run to advance".into(), line: 0, column: 0, authored: false }); } if interp.waiting { - return Err(RunError { kind: RunErrorKind::Internal, message: "the run waits for a host function's result".into(), line: 0, column: 0 }); + return Err(RunError { + kind: RunErrorKind::Internal, + message: "the run waits for a host function's result".into(), + line: 0, + column: 0, + authored: false, + }); } let total = interp.fuel; let cap = slice.saturating_add(self.unbroken_fuel).min(total); @@ -384,7 +397,13 @@ impl Realm { pub fn answer(&mut self, d: crate::Data) -> Result<(), RunError> { let interp = &mut self.interp; if !interp.waiting { - return Err(RunError { kind: RunErrorKind::Internal, message: "no host function waits for a result".into(), line: 0, column: 0 }); + return Err(RunError { + kind: RunErrorKind::Internal, + message: "no host function waits for a result".into(), + line: 0, + column: 0, + authored: false, + }); } interp.waiting = false; // The value on top of the stack stood in for the result. diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index a8d6cc86e6..870f4a23a3 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -323,6 +323,7 @@ fn headless_command_list_includes_ui_commands() { "app.quit", "window.arrange.tile", "align.horizontalLeft", + "align.toKeyObject", "ui.action.play", ]; for (n, id) in want.iter().enumerate() { @@ -1663,6 +1664,45 @@ fn transform_refused_by_a_later_operation_changes_nothing() { 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(); diff --git a/crates/mcp/src/tests/shapewidgets.rs b/crates/mcp/src/tests/shapewidgets.rs index 3ef209efab..bce666d484 100644 --- a/crates/mcp/src/tests/shapewidgets.rs +++ b/crates/mcp/src/tests/shapewidgets.rs @@ -1,5 +1,6 @@ -//! A shape tool's double-click on a selected live shape's corner widget through MCP: the -//! gesture's `requests` carry the Transform panel. +//! Live shape widgets through MCP: a shape tool's double-click on a selected live shape's corner +//! widget, whose gesture's `requests` carry the Transform panel, and a drag on a live polygon's +//! side widget. use serde_json::{Value, json}; use vectorcraft_tools::corners::CornerWidgets; @@ -28,3 +29,74 @@ fn a_corner_widget_double_click_with_a_shape_tool_requests_the_transform_panel() let off = ok(&mut h, "pointer_gesture", json!({"events": [{"kind": "doubleclick", "x": 280, "y": 280}]})); assert_eq!(off["requests"], json!([]), "{off}"); } + +/// The selected live polygon's sides, radius and transform. +fn polygon(h: &mut Headless) -> (u32, f64, vectorcraft_geom::Affine) { + let st = h.session.doc().unwrap(); + let id = st.selection.objects[0]; + let vectorcraft_doc::NodeKind::Path { live, .. } = &st.doc.node(id).unwrap().kind else { panic!("not a path") }; + let Some(vectorcraft_doc::LiveShape::Polygon { sides, radius, xf, .. }) = live.as_deref() else { panic!("not a live polygon: {live:?}") }; + (*sides, *radius, *xf) +} + +/// A drag down on a live polygon's side widget with the Selection tool gives it more sides in one +/// undo step, keeping its radius and transform; undo puts the count back. +#[test] +fn a_side_widget_drag_changes_a_polygons_sides_in_one_undo_step() { + let mut h = Headless::new(); + h.call("engine.execute", json!({"command": "file.new", "params": {"width": 300, "height": 300}})).unwrap(); + h.call("engine.execute", json!({"command": "shape.polygon", "params": {"cx": 150, "cy": 150, "radius": 60, "sides": 5}})).unwrap(); + let st = h.session.doc().unwrap(); + let id = st.selection.objects[0]; + let b = st.doc.node(id).unwrap().geometric_bounds_with(&st.doc.symbol_boxes()).expect("bounds"); + let bx = vectorcraft_doc::OrientedBox::aligned(b); + let w = vectorcraft_tools::sidewidget::SideWidget::of(&st.doc, &st.selection, &bx, h.view.zoom).expect("a side widget"); + let steps = st.history.undo.len(); + let before = polygon(&mut h); + assert_eq!(before.0, 5); + let zoom = h.view.zoom; + let ev = |kind: &str, dy: f64| json!({"kind": kind, "x": w.at.x, "y": w.at.y + dy / zoom}); + ok(&mut h, "pointer_gesture", json!({"tool": "selection", "events": [ev("down", 0.0), ev("drag", 13.0), ev("drag", 25.0), ev("up", 25.0)]})); + let after = polygon(&mut h); + assert_eq!((after.0, after.1, after.2), (7, before.1, before.2)); + assert_eq!(h.session.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + h.call("engine.execute", json!({"command": "edit.undo", "params": {}})).unwrap(); + assert_eq!(polygon(&mut h), before); + // A drag that comes back to the start leaves no undo step. + ok(&mut h, "pointer_gesture", json!({"tool": "selection", "events": [ev("down", 0.0), ev("drag", 25.0), ev("drag", 0.0), ev("up", 0.0)]})); + assert_eq!(polygon(&mut h), before); + assert_eq!(h.session.doc().unwrap().history.undo.len(), steps); +} + +/// A batch run during a side widget drag settles the drag first. A batch step that switches +/// documents then ends the drag without undoing the batch's own steps in the document it leaves. +#[test] +fn a_batch_that_switches_documents_during_a_side_widget_drag_keeps_its_steps() { + let mut h = Headless::new(); + for _ in 0..2 { + h.call("engine.execute", json!({"command": "file.new", "params": {"width": 300, "height": 300}})).unwrap(); + } + h.call("engine.execute", json!({"command": "shape.polygon", "params": {"cx": 150, "cy": 150, "radius": 60, "sides": 5}})).unwrap(); + let st = h.session.doc().unwrap(); + let (uid, id) = (st.uid, st.selection.objects[0]); + let b = st.doc.node(id).unwrap().geometric_bounds_with(&st.doc.symbol_boxes()).expect("bounds"); + let bx = vectorcraft_doc::OrientedBox::aligned(b); + let w = vectorcraft_tools::sidewidget::SideWidget::of(&st.doc, &st.selection, &bx, h.view.zoom).expect("a side widget"); + let steps = st.history.undo.len(); + let zoom = h.view.zoom; + let ev = |kind: &str, dy: f64| json!({"kind": kind, "x": w.at.x, "y": w.at.y + dy / zoom}); + // The drag stays held: no `up`. + ok(&mut h, "pointer_gesture", json!({"tool": "selection", "events": [ev("down", 0.0), ev("drag", 13.0), ev("drag", 25.0)]})); + let batch = json!({"commands": [ + {"command": "shape.rectangle", "params": {"x": 10, "y": 10, "width": 20, "height": 20}}, + {"command": "document.activate", "params": {"index": 0}} + ]}); + h.call("engine.execute", json!({"command": "command.batch", "params": batch})).unwrap(); + let st = h.session.documents().iter().find(|d| d.uid == uid).expect("the polygon's document"); + let vectorcraft_doc::NodeKind::Path { live, .. } = &st.doc.node(id).unwrap().kind else { panic!("not a path") }; + assert!(matches!(live.as_deref(), Some(vectorcraft_doc::LiveShape::Polygon { sides: 7, .. })), "the settled drag: {live:?}"); + assert_eq!(st.history.undo.len(), steps + 2, "the drag and the batch, each one undo step"); + let rect = st.selection.objects[0]; + assert_ne!(rect, id, "the batch's rectangle is selected"); + assert!(st.doc.node(rect).is_some(), "the batch's rectangle stays"); +} diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index d730f8deaf..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. A scale, reflect or shear its command refuses returns that error before any step runs, and nothing changes.", + "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 95c8e8671d..12c3b24f37 100644 --- a/crates/mcp/src/tools/dispatch.rs +++ b/crates/mcp/src/tools/dispatch.rs @@ -187,7 +187,7 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result 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. + // 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}") } @@ -312,7 +313,12 @@ pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result 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"))?; } - let reflect = a.get("reflect").and_then(Value::as_str); + // 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"))?; } @@ -320,9 +326,18 @@ pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result 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(); diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 4ff7aacecd..d9415a9549 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -143,6 +143,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} opens SVG Options; with params = document.export {path?, svg?: {…SVG options}, range?…} (a .svgz path writes it gzipped)", ), + ( + "file.export.svg.browser", + "Show in Browser", + "", + "{svg?: {…SVG options}, exportSelection?} SVG Options' Show in Browser: write the SVG of one page (with exportSelection the selection's crop, else the first artboard the options choose) and its linked images to a new temporary folder and open it in the default browser (desktop; refused for control and MCP requests) → {path, warnings}", + ), ( "file.export.png", "Export As PNG…", @@ -184,8 +190,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "Cmd+I", "{} open the Check Spelling dialog to walk through unrecognized words with suggestions, ignore, change and dictionary options", ), - ("shortcuts.set", "Set Keyboard Shortcut", "", "{id: command id or tool:, shortcut: \"Cmd+Shift+K\" | \"\" (none) | null (default), force?}"), - ("shortcuts.list", "List Keyboard Shortcuts", "", "{query?} → [{id, label, group, shortcut, default, overridden}]"), + ( + "shortcuts.set", + "Set Keyboard Shortcut", + "", + "{id: command id or tool:, shortcut?: \"Cmd+Shift+K\" | \"\" (none) | null (default), hold?: a character key alone or with Shift (\"X\", \"Shift+X\", \".\") | \"\" | null (none), force?} → {id, shortcut, hold, removedFrom}; `hold` alone leaves the shortcut as it is; a command listed only with a shortcut takes a hold only with one and loses it with the shortcut; a hold shortcut acts while the holdShortcuts preference is on", + ), + ("shortcuts.list", "List Keyboard Shortcuts", "", "{query?} → [{id, label, group, shortcut, hold, default, overridden}]"), ("shortcuts.conflicts", "Keyboard Shortcut Conflicts", "", "{} → [{shortcut, ids}]"), ("shortcuts.reset", "Reset Keyboard Shortcuts", "", "{}"), ( @@ -199,7 +210,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "shortcuts.exportText", "Export Keyboard Shortcuts as Text…", "", - "{path?, format?: \"text\"|\"sheet\"|\"csv\" (default text), pageSize?: \"letter\"|\"a4\" (sheet only; default A4 when the current document prints on A4, else letter)} save the current set's tools and menu commands with their shortcuts (Keyboard Shortcuts › Export Text…). text: a UTF-8 text file: the set's name, then a Tools and a Menu Commands section in the dialog's order, one `nameshortcut` line per row, empty after the tab when it has none. sheet: a printable PDF on landscape pages that lists the rows with a shortcut, Tools and then a group per top-level menu, under a colored band per group, shortcut then name, in four columns. csv: a UTF-8 CSV file (RFC 4180 quoting, CRLF) with a `Group,Command,Shortcut` header and one record per row in the sheet's groups, in the UI language; a field that starts with = + - @ and has more after it starts with '. A `path` is written as given. Without it, pick a file: the desktop save dialog offers the three formats (text first) unless `format` names one, and the file type picked decides and gives the name its extension; with no dialog, writer or download, returns {text} (text, csv) or {pdf: base64} (sheet); a bad `format` or `pageSize` is an error", + "{path?, format?: \"text\"|\"sheet\"|\"csv\" (default text), pageSize?: \"letter\"|\"a4\" (sheet only; default A4 when the current document prints on A4, else letter)} save the current set's tools and menu commands with their shortcuts (Keyboard Shortcuts › Export Text…). text: a UTF-8 text file: the set's name, then a Tools and a Menu Commands section in the dialog's order, one `nameshortcut` line per row, empty after the tab when it has none, and while the holdShortcuts preference is on a third `Hold ` column on a row with a hold shortcut. sheet: a printable PDF on landscape pages that lists the rows with a shortcut, Tools and then a group per top-level menu, under a colored band per group, shortcut then name, in four columns. csv: a UTF-8 CSV file (RFC 4180 quoting, CRLF) with a `Group,Command,Shortcut` header and one record per row in the sheet's groups, in the UI language; a field that starts with = + - @ and has more after it starts with '. A `path` is written as given. Without it, pick a file: the desktop save dialog offers the three formats (text first) unless `format` names one, and the file type picked decides and gives the name its extension; with no dialog, writer or download, returns {text} (text, csv) or {pdf: base64} (sheet); a bad `format` or `pageSize` is an error", ), ("shortcuts.import", "Import Keyboard Shortcuts…", "", "{path? | data?}"), ( @@ -212,6 +223,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ("view.pixelPreview", "Pixel Preview", "Cmd+Alt+Y", "{}"), ("view.trimView", "Trim View", "", "{} toggle: hide everything outside the artboards"), ("view.cornerWidget", "Hide Corner Widget", "", "{} toggle the live corner widgets"), + ( + "view.shapeWidgets", + "Hide Shape Widgets", + "", + "{on?: bool} hide or show selected live shapes' corner, pie and side widgets for the Selection tool and the shape tools (the shape tools' Control bar button); without `on` it toggles; returns the new state. Direct Selection's corner widgets follow view.cornerWidget alone", + ), ( "view.snapToPixel", "Snap to Pixel", @@ -374,6 +391,24 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} the Align panel's Horizontal Distribute Space button: object.distributeSpacing {axis: \"horizontal\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), + ( + "align.toSelection", + "Align to Selection", + "", + "{} the Align panel's Align to Selection button: Align To becomes Selection (saved with the preferences, ui.inspect › ui.align_to) and the key object, key guide or key anchor is let go → {alignTo: the choice the Align panel then shows: \"selection\", or \"artboard\" while one object is selected, since one object aligns to the artboard}; with the Artboard tool chosen the selected objects keep their key", + ), + ( + "align.toKeyObject", + "Align to Key Object", + "", + "{} the Align panel's Align to Key Object button: with no key, the topmost of two or more selected objects becomes the key object, or a ruler guide selected with one object the key guide; the stored Selection or Artboard choice stays → {alignTo: \"key\"}; an error (\"no key object\") when there is no key and nothing to make one of, which includes a topmost selected object inside another selected object; an error (\"Align to Key Object isn't available with the Artboard tool\") with the Artboard tool chosen", + ), + ( + "align.toArtboard", + "Align to Artboard", + "", + "{} the Align panel's Align to Artboard button: Align To becomes Artboard (saved with the preferences, ui.inspect › ui.align_to) and the key object, key guide or key anchor is let go → {alignTo: \"artboard\"}; with the Artboard tool chosen the selected objects keep their key", + ), ( "type.bold", "Bold", @@ -416,6 +451,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", @@ -524,6 +571,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "{double?: bool, toolbar?: name} show the toolbar's tools (with `toolbar`, that toolbar made with New Toolbar's) in two columns (true), one (false) or toggle (omitted), as the double arrow at the top of the toolbar does; returns the new state", ), ("window.toolbarAdvanced", "Toolbar: Advanced / Basic", "", "{}"), + ( + "window.toolbarCompact", + "Compact Tools", + "", + "{on?: bool} use smaller tool cells and a narrower main Tools panel (true), restore its regular spacing (false), or toggle (omitted or null); the choice starts off and is kept with the workspace, independently of one/two columns and Basic/Advanced or edited tools. Tool icons and footer controls keep their size; tool flyouts, torn-off groups and named custom toolbars keep their spacing. A value other than true, false or null is an error and changes nothing; returns the new state", + ), ( "window.toolsBesideCanvas", "Keep Tools Beside the Canvas", @@ -688,7 +741,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", @@ -780,6 +833,30 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} clear the Learn panel's progress, every tutorial finished and every step marked done, as Reset progress under the list of skills does; open documents, opened practice samples and the Learn view stay as they are; returns what learn.list returns", ), + ( + "retype.find", + "Find Matching Fonts", + "", + "{more?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first): ten, as Find Matching Fonts does, or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more that is not true or false, is an error and leaves the list as it was; returns what retype.list returns", + ), + ( + "retype.list", + "List Matching Fonts", + "", + "{} what the Retype panel shows: {searched (a search ran since the last reset), fonts: [{family, style, matched (shapes it matches)}], shapes (shapes the last search compared), more (more fonts match than the list holds), truncated (the last search left out shapes past type.retype's limits), size: small|medium|large, text (the samples' text; empty for a generic sample)}", + ), + ( + "retype.preview", + "Retype Preview", + "", + "{size?: small|medium|large, text?: string} the size of the Retype panel's samples, as its panel menu sets it, and the text they show, as its sample field sets it (at most 100 characters; empty for a generic sample); any other value is an error and changes nothing; returns what retype.list returns", + ), + ( + "retype.reset", + "Reset Retype Panel", + "", + "{} clear the Retype panel's list of matching fonts, as Reset Retype Panel in its panel menu does; the samples' size and text stay; returns what retype.list returns", + ), ("window.brightness", "UI Brightness", "", "{brightness: dark|mediumDark|mediumLight|light}"), ( "window.workspace", @@ -853,6 +930,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "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.switchSelectionTools", + "Switch Selection Tools", + "", + "{} choose Direct Selection while Selection is active, otherwise choose Selection; this is a persistent explicit tool choice, as selecting the tool from the toolbar, and can be assigned a key in Keyboard Shortcuts with no default key. Normal tool deactivation finishes pending work; returns the actual active {tool}", + ), ( "tool.setOption", "Tool Option", @@ -871,13 +954,30 @@ 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…", "", "{colors?: n (an n-colour job: n rows, Scale Tints) | [colour] (new colours to assign, in order; with no art selected and no group they are the rows, and OK saves them as a new colour group, field `groupName`: the Color Guide's Edit or Apply Colors), library?: id or name; or \"document\" (Limit to Library; \"\" the first library), group?: colour group (Edit or Apply Color Group: OK rewrites the group with the new colours and recolours the selected art, if any)} open Recolor Artwork (dialog `recolor`; engine: recolor.reduce / recolor.apply)", ), + ( + "ui.recolorUndo", + "Undo Changes", + "", + "{} the open Recolor Artwork dialog goes back one of its own color edits (rows, Colors, Method, the Preserve options, Limit to Library, the harmony rule, Global Adjust, the Color Theme Picker's picks, the Prominent Colors weights): its fields and the preview return to their values before that edit; the document's undo history is unchanged, and OK still records one undo step → {changed, canUndo, canRedo}; an error when the dialog isn't open. Each opening starts with nothing to undo, and selecting another color group or Save Changes leaves nothing to undo or redo", + ), + ( + "ui.recolorRedo", + "Redo Changes", + "", + "{} the open Recolor Artwork dialog restores the color edit ui.recolorUndo went back from last; a new edit after ui.recolorUndo leaves nothing to redo → {changed, canUndo, canRedo}; an error when the dialog isn't open", + ), ( "ui.cropImage", "Crop Image", @@ -950,6 +1050,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{swatches?: [names]} open New Color Group, from those swatches or the selected artwork (dialog `newColorGroup`, engine: swatch.newGroup)", ), + ( + "ui.colorGroupOptions", + "Color Group Options…", + "", + "{group?} open Color Group Options for that color group, or without group for the color group selected alone in the Swatches panel (dialog `colorGroupOptions`, field `name`): OK renames the group (engine: swatch.renameGroup); a name that is empty or that another color group or a swatch has keeps the dialog open; when another document is active, or the color group at the group's place in the list no longer has the name and swatches it opened with, OK closes the dialog and renames nothing", + ), ( "ui.colorPicker", "Color Picker…", @@ -1032,7 +1138,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), 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", @@ -1114,19 +1220,19 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.layerDelete", "Delete Selection", "", - "{ids?|id?, doc?, confirmed?: bool} Delete Selection as the Layers panel runs it (its trash button, rows dropped on the trash, its menu, Delete and Backspace), on the rows layer.delete takes (default: the highlighted rows, else the current layer). When a layer or sublayer among them holds art (an object other than a guide; hidden, locked and nested objects count) it asks first: dialog `confirm` with `message`; OK deletes those rows by id with layer.delete (one undo step), Cancel keeps them. OK runs ui.layerDelete again with the rows, `doc` (the document's uid) and `confirmed: true`: with another document active then, nothing is deleted. Other rows (an empty layer, groups and objects alone) and rows layer.delete refuses go to layer.delete at once → layer.delete's {deleted}, or null while the question is open", + "{ids?|id?, doc?, confirmed?: bool} Delete Selection as the Layers panel runs it (its trash button, rows dropped on the trash, its menu, Delete and Backspace), on the rows layer.delete takes (default: the highlighted rows, else the current layer; in isolation mode, with no row highlighted, a current layer outside the isolated art is an error and nothing is deleted). When a layer or sublayer among them holds art (an object other than a guide; hidden, locked and nested objects count) it asks first: dialog `confirm` with `message`; OK deletes those rows by id with layer.delete (one undo step), Cancel keeps them. OK runs ui.layerDelete again with the rows, `doc` (the document's uid) and `confirmed: true`: with another document active then, nothing is deleted. In isolation mode a row outside the isolated art is an error and nothing is deleted. Other rows (an empty layer, groups and objects alone) and rows layer.delete refuses go to layer.delete at once → layer.delete's {deleted}, or null while the question is open", ), ( "ui.rename", "Rename", "", - "{id?} open the Layers panel's name field on the row of layer, group or object id, as double-clicking the row's name does (the panel is shown and the layers around the row open): Enter renames it with layer.setProps (one undo step), Escape keeps the name. Without id: the highlighted row when a Layers panel row was clicked last, else the one selected object or group, else the one highlighted row, else the current layer. Several rows or objects, or a row the panel's search, filter or Show Layers Only hides, is an error and nothing opens → {id, name}", + "{id?} open the Layers panel's name field on the row of layer, group or object id, as double-clicking the row's name does (the panel is shown and the layers around the row open): Enter renames it with layer.setProps (one undo step), Escape keeps the name. Without id: the highlighted row when a Layers panel row was clicked last, else the one selected object or group, else the one highlighted row, else the current layer. Several rows or objects, a row the panel's search, filter or Show Layers Only hides, or in isolation mode an object outside the isolated art, is an error and nothing opens → {id, name}", ), ( "ui.newLayer", "New Layer Options…", "Cmd+Alt+L", - "{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields", + "{sublayer?: bool} open Layer Options for a new layer (or a sublayer of the current layer), named and coloured as it would be: dialog `layerOptions` with mode new|newSublayer; OK runs layer.new or layer.newSublayer with the fields. In isolation mode, a layer that would be outside the isolated art is an error and nothing opens; OK checks again, and with isolation mode started since, it returns the same error and makes no layer", ), ( "ui.newArtboard", @@ -1152,6 +1258,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", ), + ( + "ui.attributesPanelOptions", + "Panel Options…", + "", + "{count?: 1–30 (10 by default)} set how many of the recent URLs (attributes.info › recentUrls, which keeps 30) the Attributes panel's URL menu lists, newest first (kept with the UI state) → {count}; without count, open its Panel Options (dialog `attributesPanelOptions`, field count; OK sets it); an error for a count that is not a whole number from 1 to 30, which changes nothing", + ), ( "ui.layersExpand", "Expand Layers Panel Rows", @@ -1365,7 +1477,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.widthPointEdit", "Width Point Edit…", "", - "{id, index?: existing width point, t?: 0..1 for a new point, adjustAdjoining?: bool (false)} open Width Point Edit on path `id` (dialog `widthPoint`: side1, side2 (pt), linked, adjustAdjoining; double-clicking the stroke opens it too, Shift on a width point enabling adjoining adjustment): OK runs stroke.widthPoint.set; discard: true (Delete) removes an existing point or discards a prospective point", + "{id, index?: existing width point, indices?: [i…] several existing width points, t?: 0..1 for a new point (give only one of index, indices and t), adjustAdjoining?: bool (false)} open Width Point Edit on path `id` (dialog `widthPoint`: side1, side2 (pt), linked, adjustAdjoining; for several points also totalWidth, and side1, side2 and totalWidth are null where the points differ; double-clicking the stroke opens it too, on one of several Shift-selected width points for all of them, Shift on a width point enabling adjoining adjustment): OK runs stroke.widthPoint.set, for several points one stroke.widthProfile.set (none when nothing changed); discard: true (Delete) removes the existing points or discards a prospective point", ), ( "ui.corners", @@ -1443,13 +1555,19 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, both are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, 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); harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; 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, harmony, harmonyRule, vision}", ), ( "ui.savePdfDialog", "Save PDF Dialog", "", - "{path?, preset?, range?, useArtboards?, …document.exportPdf options} open the Save PDF dialog with these options (fields = the options, sections are objects; OK writes path, else asks); useArtboards: false: one page of the visible art's bounds, with no Artboards section", + "{path?, preset?, range?, useArtboards?, …document.exportPdf options} open the Save PDF dialog with these options (fields = the options, sections are objects; Custom… sets `flattener`, which setting flattenerPreset drops; OK writes path, else asks); useArtboards: false: one page of the visible art's bounds, with no Artboards section", + ), + ( + "ui.pdfSummary.save", + "Save Summary…", + "", + "{path} write the Summary of the open Save PDF dialog (or PDF preset editor) to path as UTF-8 text without a byte order mark, with LF line endings, line for line as the Summary section shows it: Options and each option that differs from the preset (or the line saying none does), a blank line, then Warnings and each warning (or None.). The Summary the section last drew for the same fields, document, saved PDF and flattener presets, loaded color profiles and available fonts is used without computing the settings again. The web downloads the file under path's file name. The Summary section's Save Summary… button writes the same text to a file picked in a save panel that suggests ` PDF Summary.txt` in the document's folder. The dialog stays open and the document does not change. No such dialog open, a path that is missing, empty or not a string, a path outside the automation write roots and a failed document.pdfSettings are errors that write nothing; a failed write is an error → {path, bytes}", ), ( "file.exportAs", @@ -1520,6 +1638,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", @@ -1532,6 +1662,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} close the progress window of the files being opened; they go on being read, shown in the status bar → {hidden: n}", ), + ( + "file.cancelPlace", + "Cancel Place", + "", + "{} stop placing every file being read in the background (its progress window's Cancel): the files aren't placed → {cancelled: n}", + ), ( "ui.dxfOptionsDialog", "DXF Options Dialog", @@ -1596,13 +1732,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.action.new", "New Action", "", - "{set: index, name, key?: 0-15, cmd?, shift?, color?: red|yellow|green|blue|violet} add an action named name (spaces trimmed from both ends) after the last action of the Actions panel's set at set (0 is the top set) and start recording into it; Stop Playing/Recording (ui.action.stop) ends the recording. key 1 to 15 is the function key F1 to F15 that plays the action (0 or null: none), with cmd (Ctrl, Command on macOS) and shift; color is its Button Mode color (null or \"\": none), the color of its button in Button Mode (ui.action.buttonMode). Action function keys take priority over command shortcuts and preserve the command's binding. On Windows F1, Ctrl+F4 and Ctrl+F6 cannot be used. The set becomes current and the new action is selected. The panel's Create New Action button and menu's New Action… (dialog `actionNew` with set, name, key, cmd, shift and color) run this on Record. While an action is recording, and for an index past the last set, an empty name, a key or color that is not one of these, or an action that would give the set more than 1,000 actions or an action set file larger than 8 MiB, it is an error, nothing is added and no recording starts → {set, action}", + "{set: index, name, key?: 0-15, cmd?, shift?, color?: red|yellow|green|blue|violet, automaticAlignTo?: bool} add an action named name (spaces trimmed from both ends) after the last action of the Actions panel's set at set (0 is the top set) and start recording into it; Stop Playing/Recording (ui.action.stop) ends the recording. key 1 to 15 is the function key F1 to F15 that plays the action (0 or null: none), with cmd (Ctrl, Command on macOS) and shift; color is its Button Mode color (null or \"\": none), the color of its button in Button Mode (ui.action.buttonMode). Action function keys take priority over command shortcuts and preserve the command's binding. On Windows F1, Ctrl+F4 and Ctrl+F6 cannot be used. automaticAlignTo (false when omitted or null) makes each object.align choose its reference at playback: an active key object, key anchor or key guide, else the artboard for one whole selected object, else the selection; false uses the recorded target, and stored steps stay unchanged. The set becomes current and the new action is selected. The panel's Create New Action button and menu's New Action… (dialog `actionNew` with set, name, key, cmd, shift, color and automaticAlignTo) run this on Record. While an action is recording, and for an index past the last set, an empty name, a key or color that is not one of these, or an action that would give the set more than 1,000 actions or an action set file larger than 8 MiB, it is an error, nothing is added and no recording starts → {set, action}", ), ( "ui.action.options", "Action Options", "", - "{set: index, action: index, name?, key?: 0-15, cmd?, shift?, color?: red|yellow|green|blue|violet} change the Actions panel's action at action in set (0 is the top set); its steps stay. name renames it (spaces trimmed from both ends), key 1 to 15 with cmd (Ctrl, Command on macOS) and shift sets the function key F1 to F15 that plays it (0 or null: none), and color sets its Button Mode color (null or \"\": none); a param left out keeps what the action has, and cmd or shift alone changes that modifier of its key. Action function keys take priority over command shortcuts and preserve the command's binding. The panel menu's Action Options… (dialog `actionSetOptions` with set, action, name, key, cmd, shift and color) runs this for the selected action. An index past the last set or action, an empty name, a key or color that is not one of these, or a change that would give the set's action set file more than 8 MiB (counting the steps the recording in progress adds to it; a change that leaves the file as large or makes it smaller is never refused) is an error and changes nothing → {name, key, color}", + "{set: index, action: index, name?, key?: 0-15, cmd?, shift?, color?: red|yellow|green|blue|violet, automaticAlignTo?: bool} change the Actions panel's action at action in set (0 is the top set); its steps stay. name renames it (spaces trimmed from both ends), key 1 to 15 with cmd (Ctrl, Command on macOS) and shift sets the function key F1 to F15 that plays it (0 or null: none), and color sets its Button Mode color (null or \"\": none); a param left out keeps what the action has, and cmd or shift alone changes that modifier of its key. automaticAlignTo overrides each object.align reference at playback with the current key object, key anchor or key guide, else the artboard for one whole selected object, else the selection; false uses the unchanged recorded targets, and omission or null keeps the option. Action function keys take priority over command shortcuts and preserve the command's binding. The panel menu's Action Options… (dialog `actionSetOptions` with set, action, name, key, cmd, shift, color and automaticAlignTo) runs this for the selected action. An index past the last set or action, an empty name, a key or color that is not one of these, or a change that would give the set's action set file more than 8 MiB (counting the steps the recording in progress adds to it; a change that leaves the file as large or makes it smaller is never refused) is an error and changes nothing → {name, key, color, automaticAlignTo}", ), ( "ui.action.play", @@ -1724,6 +1860,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", @@ -1737,6 +1879,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{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", "Save for Web (Legacy)…", diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 8e5f53ce41..3f6dd8d5dd 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -85,14 +85,23 @@ pub fn export(doc: &Document, region: Rect, kind: Kind) -> Result Result<(), String> { + let empty = |r: Rect| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0; + if regions.iter().any(|r| empty(r.abs())) { + return Err("the export region is empty".into()); + } + Ok(()) +} + /// Write the visible art of `doc` over each of `regions` as `kind`, one metafile per region in the /// same order, each as [`export`] writes it over that region. The live effects are applied once /// for all of them. When any region is empty, nothing is written and the result is an error. pub fn export_regions(doc: &Document, regions: &[Rect], kind: Kind) -> Result, String> { + check_regions(regions)?; let regions: Vec = regions.iter().map(|r| r.abs()).collect(); - if regions.iter().any(|r| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0) { - return Err("the export region is empty".into()); - } if regions.is_empty() { return Ok(Vec::new()); } diff --git a/crates/pathops/src/addons/pathtools.rs b/crates/pathops/src/addons/pathtools.rs index d8ad6ae8e4..d5fe994bed 100644 --- a/crates/pathops/src/addons/pathtools.rs +++ b/crates/pathops/src/addons/pathtools.rs @@ -4,10 +4,10 @@ //! tool shows over a path, open paths lengthened or shortened at an end ([`extend`]), the places //! where paths cross ([`crossings`]), the stretches between them ([`spans`]), anchors slid along //! their path ([`slide`]), touching edges merged ([`shared_edge`]), paths divided into dashes -//! ([`divide_dashes`]), two circles joined by a smooth bridge ([`smooth_bridge`]), the common -//! tangents of two convex outlines ([`common_tangents`]), the -//! Parametric Shape Tool's shapes ([`shapes`]) and the circles that touch two or three shapes -//! ([`tangent_circles`]). +//! ([`divide_dashes`]), two circles joined by a smooth bridge ([`smooth_bridge`]) or many circles +//! joined to their neighbors ([`bridge_many`]), the common tangents of two convex outlines +//! ([`common_tangents`]), the Parametric Shape Tool's shapes ([`shapes`]) and the circles that touch +//! two or three shapes ([`tangent_circles`]). mod bridge; mod crossings; @@ -27,7 +27,9 @@ use std::collections::BTreeSet; use kurbo::{CubicBez, ParamCurve, ParamCurveArclen, ParamCurveNearest, Point, Vec2}; use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath}; -pub use bridge::{BridgeError, circle_of, smooth_bridge}; +pub use bridge::{ + ArcRadius, BridgeError, Bridged, Joined, MAX_BRIDGED_CIRCLES, MAX_BRIDGES, ManyError, bridge_many, bridges_any, circle_of, smooth_bridge, +}; pub use crossings::{MAX_CROSSED_BY_SEGMENTS, MAX_CROSSING_SEGMENTS, Place, Work, crossings, crossings_on, crossings_on_within, insert_at}; pub use dashes::{DashSpec, Piece, divide_dashes}; pub use extend::{ExtendMode, extend_length_to, extend_open}; @@ -39,6 +41,8 @@ pub use tangent_circle::{Circle, MAX_TANGENT_CIRCLE_SEGMENTS, MAX_TANGENT_CIRCLE pub use tangents::{Coincide, MAX_TANGENT_SEGMENTS, Outline, OutlineError, Tangent, TangentKind, common_tangents}; pub use trim::{Span, slice, span_at, spans, without_spans}; +pub use tangent_circle::{SegmentCircle, circles_of_radius, circles_through}; + use crate::fit::{end_tangent, start_tangent}; /// The auto-smooth rule's handle length as a share of the nearer neighbour's distance: the share diff --git a/crates/pathops/src/addons/pathtools/bridge.rs b/crates/pathops/src/addons/pathtools/bridge.rs index 43ee629a91..2b2fd9512e 100644 --- a/crates/pathops/src/addons/pathtools/bridge.rs +++ b/crates/pathops/src/addons/pathtools/bridge.rs @@ -1,10 +1,14 @@ //! Smooth Bridge: two circles joined into one outline by two concave arcs, each touching both -//! circles from outside, so the outline runs on smoothly from each circle into the bridge. +//! circles from outside, so the outline runs on smoothly from each circle into the bridge; and +//! many circles joined at once, each to the others within reach ([`bridge_many`]). +use std::collections::{BTreeMap, HashMap, HashSet}; use std::f64::consts::{FRAC_PI_2, PI, SQRT_2, TAU}; use kurbo::{CubicBez, ParamCurve, Point, Shape, Vec2}; -use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath}; +use vectorcraft_geom::{Anchor, AnchorKind, FillRule, PathData, SubPath, shapes}; + +use crate::boolean::{DEFAULT_PRECISION, try_unite_all_with}; use super::Circle; @@ -58,6 +62,64 @@ pub fn circle_of(path: &PathData) -> Option { /// a tangent there. Overlapping and touching circles are joined too. A larger radius makes a wider, /// gentler bridge; farther apart circles make a narrower one, until the arcs would cross. pub fn smooth_bridge(a: Circle, b: Circle, radius: f64) -> Result { + let t = touches(a, b, radius)?; + let mut segs = vec![]; + arc(&mut segs, a.center, a.radius, t.a1, t.a2, Some(-t.u)); + arc(&mut segs, t.p2, radius, t.a2, t.b2, None); + arc(&mut segs, b.center, b.radius, t.b2, t.b1, Some(t.u)); + arc(&mut segs, t.p1, radius, t.b1, t.a1, None); + closed(&segs, AnchorKind::Smooth) +} + +/// The part of [`smooth_bridge`]'s outline between the circles: the two arcs, joined across each +/// circle by a straight line between the arc ends on it. Each line lies inside its circle, so the +/// two circles and this shape unite into the outline, with each circle drawn once however many +/// bridges it has. +fn neck(a: Circle, b: Circle, radius: f64) -> Result { + let t = touches(a, b, radius)?; + let line = |p: Point, q: Point| CubicBez::new(p, p, q, q); + let mut segs = vec![]; + arc(&mut segs, t.p2, radius, t.a2, t.b2, None); + segs.push(line(t.b2, t.b1)); + arc(&mut segs, t.p1, radius, t.b1, t.a1, None); + segs.push(line(t.a1, t.a2)); + closed(&segs, AnchorKind::Corner) +} + +/// A closed subpath through the cubics `segs`, each starting where the one before it ends, with +/// anchors of `kind`; [`BridgeError::Bad`] when a point does not fit in `f64`. +fn closed(segs: &[CubicBez], kind: AnchorKind) -> Result { + let count = segs.len(); + let anchors: Vec = (0..count) + .filter_map(|i| { + let (prev, seg) = (segs.get((i + count - 1) % count)?, segs.get(i)?); + Some(Anchor { p: seg.p0, h_in: prev.p2, h_out: seg.p1, kind }) + }) + .collect(); + let finite_point = |p: Point| p.x.is_finite() && p.y.is_finite(); + if !anchors.iter().all(|q| finite_point(q.p) && finite_point(q.h_in) && finite_point(q.h_out)) { + return Err(BridgeError::Bad); + } + Ok(SubPath::new(anchors, true)) +} + +/// Where the arcs of radius `radius` that bridge circles `a` and `b` lie: the unit vector from +/// `a`'s center to `b`'s, and on each side the arc's center (`p1`, `p2`) and where it touches `a` +/// and `b`; and the neck's width where the arcs come nearest each other between the circles +/// (infinite when that is at the circles). +struct Touches { + waist: f64, + u: Vec2, + p1: Point, + a1: Point, + b1: Point, + p2: Point, + a2: Point, + b2: Point, +} + +/// The arcs of [`smooth_bridge`], or why there are none. +fn touches(a: Circle, b: Circle, radius: f64) -> Result { let finite = |x: f64| x.is_finite() && x > 0.0; let points = [a.center, b.center].iter().all(|c| c.x.is_finite() && c.y.is_finite()); if !finite(radius) || !finite(a.radius) || !finite(b.radius) || !points { @@ -95,29 +157,241 @@ pub fn smooth_bridge(a: Circle, b: Circle, radius: f64) -> Result = (0..count) - .map(|i| { - let (prev, seg) = (segs[(i + count - 1) % count], segs[i]); - Anchor { p: seg.p0, h_in: prev.p2, h_out: seg.p1, kind: AnchorKind::Smooth } - }) - .collect(); - let finite_point = |p: Point| p.x.is_finite() && p.y.is_finite(); - if !anchors.iter().all(|q| finite_point(q.p) && finite_point(q.h_in) && finite_point(q.h_out)) { - return Err(BridgeError::Bad); + let waist = if along > 0.0 && along < d { 2.0 * (across - radius) } else { f64::INFINITY }; + Ok(Touches { waist, u, p1, a1, b1, p2, a2, b2 }) +} + +/// The most circles [`bridge_many`] takes. +pub const MAX_BRIDGED_CIRCLES: usize = 2000; +/// The most bridges [`bridge_many`] makes. +pub const MAX_BRIDGES: usize = 8000; +/// Holes [`bridge_many`] fills: those smaller than this share of the area of the smallest circle +/// they join. +const SPECK: f64 = 0.01; + +/// The radius of the arcs that bridge two circles. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum ArcRadius { + /// This share of the smaller circle's radius (1 is the same radius). + Share(f64), + /// The smaller circle's radius plus this gap (pt). Each arc is then this gap outside a circle + /// of the smaller circle's radius about the arc's center: for equal circles that gap apart, + /// the place of a third circle that gap from both, as in a triangular grid. + Gap(f64), +} + +impl ArcRadius { + /// The arcs' radius (pt) for circles `a` and `b`. + pub fn between(self, a: Circle, b: Circle) -> f64 { + let r = a.radius.min(b.radius); + match self { + ArcRadius::Share(share) => r * share, + ArcRadius::Gap(gap) => r + gap, + } } - Ok(SubPath::new(anchors, true)) +} + +/// Circles that bridges join into one shape: their indices, ascending, and the shape's outline. +#[derive(Clone, Debug, PartialEq)] +pub struct Joined { + pub members: Vec, + pub outline: PathData, +} + +/// What [`bridge_many`] makes: the joined shapes, in the order of their first member, and the +/// indices of the circles left alone, ascending. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Bridged { + pub joined: Vec, + pub alone: Vec, +} + +/// Why [`bridge_many`] makes nothing. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ManyError { + /// More than [`MAX_BRIDGED_CIRCLES`] circles. + TooManyCircles, + /// More than [`MAX_BRIDGES`] pairs of circles to bridge: within reach, near enough for the + /// arcs and with a neck wide enough for the shape's precision. Also more than nine times as many + /// pairs within reach to check. + 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)); + }; + if pairs.len() > MAX_BRIDGES { + return Err(ManyError::TooManyBridges); + } + 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)), + } + } + } + // A bound on the work before thin necks are dropped; [`bridgeable`] holds the pairs left + // to [`MAX_BRIDGES`]. + if pairs.len() > 9 * MAX_BRIDGES { + return Err(ManyError::TooManyBridges); + } + } + // Saturated cells can list a pair twice. + pairs.sort_unstable_by_key(|&(pair, _)| pair); + pairs.dedup_by_key(|&mut (pair, _)| pair); + Ok((pairs, too_far)) } /// Append to `out` the arc of the circle about `center` with radius `r` from `from` to `to` (both @@ -331,6 +605,212 @@ mod tests { assert_eq!(smooth_bridge(circle(f64::INFINITY, 0.0, 10.0), b, 10.0), Err(BridgeError::Bad)); } + /// A 3 × 3 grid of circles of radius 10, 4 apart (centers 24 apart), top-left at the origin. + fn grid() -> Vec { + (0..9).map(|k| circle(24.0 * (k % 3) as f64, 24.0 * (k / 3) as f64, 10.0)).collect() + } + + fn area(path: &PathData) -> f64 { + crate::area(path, FillRule::NonZero) + } + + fn inside(path: &PathData, x: f64, y: f64) -> bool { + path.to_bezpath().winding(Point::new(x, y)) != 0 + } + + #[test] + fn a_grid_joins_each_circle_to_its_neighbors_within_reach() { + // Reach 5: the side neighbors (4 apart) are joined, the diagonal ones (about 13.9 apart) not. + let b = bridge_many(&grid(), ArcRadius::Gap(4.0), 5.0).unwrap(); + assert_eq!(b.alone, Vec::::new()); + let [one] = b.joined.as_slice() else { panic!("{} shapes", b.joined.len()) }; + assert_eq!(one.members, (0..9).collect::>()); + for (x, y) in [(12.0, 0.0), (0.0, 12.0), (36.0, 48.0), (48.0, 36.0), (24.0, 24.0)] { + assert!(inside(&one.outline, x, y), "bridged at ({x}, {y})"); + } + // Between four circles the side bridges' arcs leave a hole: no diagonal bridge fills it. + for (x, y) in [(12.0, 12.0), (36.0, 36.0)] { + assert!(!inside(&one.outline, x, y), "a hole at ({x}, {y})"); + } + let hull = PathData::single(SubPath::polyline( + &[Point::new(-10.0, -10.0), Point::new(58.0, -10.0), Point::new(58.0, 58.0), Point::new(-10.0, 58.0)], + true, + )); + assert!(area(&one.outline) < area(&hull)); + assert_eq!(one.outline.subpaths.len(), 5, "the outline and a hole in each square"); + // Reach 15 takes in the diagonal neighbors too, and their bridges fill the middle of each + // square. The specks of holes (about 0.1 pt²) where side and diagonal arcs nearly meet are + // filled. + let b = bridge_many(&grid(), ArcRadius::Gap(4.0), 15.0).unwrap(); + let [one] = b.joined.as_slice() else { panic!("{} shapes", b.joined.len()) }; + assert!(inside(&one.outline, 12.0, 12.0) && inside(&one.outline, 36.0, 36.0)); + assert_eq!(one.outline.subpaths.len(), 1); + } + + #[test] + fn a_circle_with_no_neighbor_in_reach_is_left_alone() { + let mut circles = grid(); + circles.truncate(2); + circles.push(circle(200.0, 0.0, 10.0)); + circles.push(circle(224.0, 0.0, 10.0)); + circles.push(circle(100.0, 100.0, 10.0)); + let b = bridge_many(&circles, ArcRadius::Share(1.0), 5.0).unwrap(); + assert_eq!(b.joined.iter().map(|j| j.members.clone()).collect::>(), [vec![0, 1], vec![2, 3]]); + assert_eq!(b.alone, [4]); + // Each pair alone is the two-circle bridge. + let two = smooth_bridge(circles[0], circles[1], 10.0).unwrap(); + let (got, want) = (area(&b.joined[0].outline), area(&PathData::single(two))); + assert!((got - want).abs() < 1e-3 * want, "{got} {want}"); + } + + #[test] + fn a_ring_around_an_empty_place_leaves_a_round_hole_the_gap_wider_than_a_circle() { + // Six circles of radius 10 around an empty place at the origin, each 4 from its two + // neighbors and from where a seventh circle would be (centers 24 from the origin). + let ring: Vec = (0..6).map(|k| f64::from(k) * PI / 3.0).map(|t| circle(24.0 * t.cos(), 24.0 * t.sin(), 10.0)).collect(); + let b = bridge_many(&ring, ArcRadius::Gap(4.0), 5.0).unwrap(); + let [one] = b.joined.as_slice() else { panic!("{} shapes", b.joined.len()) }; + assert_eq!(one.members, (0..6).collect::>()); + assert_eq!(one.outline.subpaths.len(), 2, "the outline and the hole"); + // The hole's edge is 14 from the origin all the way round: a circle of radius 10 there + // would be 4 from the shape everywhere, the same as from each of the six. + let hole = one.outline.subpaths.iter().min_by(|p, q| { + let size = |sp: &SubPath| PathData::single(sp.clone()).to_bezpath().area().abs(); + size(p).total_cmp(&size(q)) + }); + let edge = outline(hole.unwrap()); + let (near, far) = edge.iter().map(|p| p.distance(Point::ZERO)).fold((f64::INFINITY, 0.0f64), |(n, f), d| (n.min(d), f.max(d))); + assert!((near - 14.0).abs() < 1e-2 && (far - 14.0).abs() < 1e-2, "{near} to {far}"); + } + + #[test] + fn many_circles_make_the_two_circle_outline_for_each_pair() { + // Overlapping, touching, unequal and unequal overlapping pairs, each with a far circle. + for (a, b, share) in [ + (circle(0.0, 0.0, 20.0), circle(30.0, 0.0, 20.0), 0.5), + (circle(0.0, 0.0, 20.0), circle(40.0, 0.0, 20.0), 0.5), + (circle(0.0, 0.0, 30.0), circle(70.0, 0.0, 10.0), 4.0), + (circle(0.0, 0.0, 10.0), circle(25.0, 0.0, 30.0), 10.0), + // Circles far smaller than the union's usual precision (0.01 pt). + (circle(0.0, 0.0, 0.004), circle(0.01, 0.0, 0.004), 1.0), + ] { + let made = bridge_many(&[a, b, circle(1000.0, 0.0, 5.0)], ArcRadius::Share(share), 40.0).unwrap(); + assert_eq!(made.alone, [2]); + let two = smooth_bridge(a, b, share * a.radius.min(b.radius)).unwrap(); + let (got, want) = (area(&made.joined[0].outline), area(&PathData::single(two))); + assert!((got - want).abs() < 1e-3 * want, "{a:?}: {got} {want}"); + } + } + + #[test] + fn a_pair_too_far_apart_for_the_arcs_gets_no_bridge() { + // b and c are within reach (6 apart) but arcs of radius 3 close before they reach both. + let (a, b, c) = (circle(0.0, 0.0, 3.0), circle(8.0, 0.0, 3.0), circle(20.0, 0.0, 3.0)); + assert_eq!(smooth_bridge(b, c, 3.0), Err(BridgeError::TooFar)); + let made = bridge_many(&[a, b, c], ArcRadius::Share(1.0), 10.0).unwrap(); + assert_eq!(made.joined.iter().map(|j| j.members.clone()).collect::>(), [vec![0, 1]]); + assert_eq!(made.alone, [2]); + // Arcs of radius 10 between circles of radius 10 just under 20√3 apart leave a neck about + // 0.00003 pt wide, too thin for the union: that pair is left unbridged too. + let (a, b, c) = (circle(0.0, 0.0, 10.0), circle(34.6409, 0.0, 10.0), circle(58.6409, 0.0, 10.0)); + assert!(smooth_bridge(a, b, 10.0).is_ok(), "two circles alone are bridged"); + let made = bridge_many(&[a, b, c], ArcRadius::Share(1.0), 20.0).unwrap(); + assert_eq!(made.joined.iter().map(|j| j.members.clone()).collect::>(), [vec![1, 2]]); + assert_eq!(made.alone, [0]); + // Two tiny circles far off are united at a finer precision, which does not change that. + let tiny = [circle(500.0, 0.0, 0.01), circle(500.025, 0.0, 0.01)]; + let made = bridge_many(&[a, b, c, tiny[0], tiny[1]], ArcRadius::Share(1.0), 20.0).unwrap(); + assert_eq!(made.joined.iter().map(|j| j.members.clone()).collect::>(), [vec![1, 2], vec![3, 4]]); + assert_eq!(made.alone, [0]); + // 260 touching circles in a row with a wide reach: 33,670 pairs within reach, far more than + // the bridge limit, but only the 259 touching pairs are near enough for the arcs. + let row: Vec = (0..260).map(|i| circle(f64::from(i) * 20.0, 0.0, 10.0)).collect(); + let made = bridge_many(&row, ArcRadius::Share(1.0), 6000.0).unwrap(); + let [one] = made.joined.as_slice() else { panic!("{} shapes", made.joined.len()) }; + assert_eq!(one.members.len(), 260); + assert!(made.alone.is_empty()); + } + + #[test] + fn the_gap_form_keeps_the_gap_from_a_circle_at_each_arcs_center() { + // Two circles 4 apart; with a gap of 4 each arc's center is 24 from both centers, where a + // third circle of the same size is 4 from both (as in a triangular grid). + let (a, b) = (circle(0.0, 0.0, 10.0), circle(24.0, 0.0, 10.0)); + let r = ArcRadius::Gap(4.0).between(a, b); + assert_eq!(r, 14.0); + let sp = smooth_bridge(a, b, r).unwrap(); + for third in [circle(12.0, 432f64.sqrt(), 10.0), circle(12.0, -(432f64.sqrt()), 10.0)] { + let gaps: Vec = outline(&sp).iter().map(|p| p.distance(third.center) - third.radius).collect(); + // No part of the bridge comes nearer than the gap, and a stretch of it is that gap away. + assert!(gaps.iter().all(|&g| g > 4.0 - 1e-2), "{:?}", gaps.iter().copied().fold(f64::INFINITY, f64::min)); + let along = gaps.iter().filter(|&&g| (g - 4.0).abs() < 1e-2).count(); + assert!(along >= 32, "{along}"); + } + // The same for unequal circles: the gap is kept from a circle of the smaller one's size. + let (a, b) = (circle(0.0, 0.0, 15.0), circle(30.0, 5.0, 8.0)); + let r = ArcRadius::Gap(3.0).between(a, b); + let sp = smooth_bridge(a, b, r).unwrap(); + let d = (b.center - a.center).hypot(); + let (ra, rb) = (15.0 + r, 8.0 + r); + let along = (d * d + ra * ra - rb * rb) / (2.0 * d); + let u = (b.center - a.center) / d; + let center = a.center + u * along + Vec2::new(-u.y, u.x) * (ra * ra - along * along).sqrt(); + let gaps: Vec = outline(&sp).iter().map(|p| p.distance(center) - 8.0).collect(); + assert!(gaps.iter().all(|&g| g > 3.0 - 1e-2) && gaps.iter().filter(|&&g| (g - 3.0).abs() < 1e-2).count() >= 16); + } + + #[test] + fn the_gap_form_is_the_percentage_form_of_the_radius_plus_the_gap() { + for (a, b, gap) in [(circle(0.0, 0.0, 10.0), circle(24.0, 0.0, 10.0), 4.0), (circle(0.0, 0.0, 20.0), circle(40.0, 30.0, 10.0), 7.5)] { + let small = a.radius.min(b.radius); + let share = ArcRadius::Share((small + gap) / small); + assert!((ArcRadius::Gap(gap).between(a, b) - share.between(a, b)).abs() < 1e-12); + let (g, s) = (smooth_bridge(a, b, ArcRadius::Gap(gap).between(a, b)).unwrap(), smooth_bridge(a, b, share.between(a, b)).unwrap()); + for (p, q) in g.anchors.iter().zip(&s.anchors) { + assert!(p.p.distance(q.p) < 1e-9 && p.h_in.distance(q.h_in) < 1e-9 && p.h_out.distance(q.h_out) < 1e-9); + } + assert_eq!(g.anchors.len(), s.anchors.len()); + } + // Over a grid the two forms make the same shape too. + let by_gap = bridge_many(&grid(), ArcRadius::Gap(4.0), 5.0).unwrap(); + let by_share = bridge_many(&grid(), ArcRadius::Share(1.4), 5.0).unwrap(); + let (g, s) = (area(&by_gap.joined[0].outline), area(&by_share.joined[0].outline)); + assert!((g - s).abs() < 1e-6 * g, "{g} {s}"); + } + + #[test] + fn too_many_circles_or_bridges_and_bad_pairs_are_refused() { + let many = vec![circle(0.0, 0.0, 1.0); MAX_BRIDGED_CIRCLES + 1]; + assert_eq!(bridge_many(&many, ArcRadius::Share(1.0), 1.0), Err(ManyError::TooManyCircles)); + // 200 circles in a tight row: 19,900 pairs within reach. + let row: Vec = (0..200).map(|i| circle(i as f64 * 0.1, 0.0, 10.0)).collect(); + assert_eq!(bridge_many(&row, ArcRadius::Share(1.0), 1.0), Err(ManyError::TooManyBridges)); + let spread: Vec = (0..3).map(|i| circle(i as f64 * 100.0, 0.0, 10.0)).collect(); + assert_eq!(bridge_many(&spread, ArcRadius::Share(1.0), 5.0), Err(ManyError::NoneInReach)); + let nested = [circle(0.0, 0.0, 30.0), circle(5.0, 0.0, 10.0), circle(200.0, 0.0, 10.0)]; + assert_eq!(bridge_many(&nested, ArcRadius::Share(1.0), 5.0), Err(ManyError::Pair(0, 1, BridgeError::Inside))); + // Within reach (40 apart) but too far for arcs of radius 1. + let far = [circle(0.0, 0.0, 10.0), circle(60.0, 0.0, 10.0), circle(300.0, 0.0, 10.0)]; + assert_eq!(bridge_many(&far, ArcRadius::Share(0.1), 50.0), Err(ManyError::Pair(0, 1, BridgeError::TooFar))); + assert_eq!(bridge_many(&far, ArcRadius::Share(1.0), f64::NAN), Err(ManyError::Bad)); + assert_eq!(bridge_many(&far, ArcRadius::Share(1.0), -1.0), Err(ManyError::Bad)); + assert_eq!(bridge_many(&[circle(f64::INFINITY, 0.0, 1.0), far[0]], ArcRadius::Share(1.0), 1.0), Err(ManyError::Bad)); + } + + #[test] + fn the_bridge_limit_counts_the_necks_left_after_thin_ones_are_dropped() { + // Two columns of 65 nearly coincident circles: 8,385 pairs within reach that the arcs can + // bridge, but the 4,225 between the columns are thinner than the precision allows. + let column = |x: f64| (0..65).map(move |k| circle(x, 0.001 * k as f64, 10.0)); + let circles: Vec = column(0.0).chain(column(34.6409)).collect(); + let (pairs, too_far) = pairs_within(&circles, 15.0, ArcRadius::Share(1.0)).unwrap(); + assert_eq!((pairs.len(), too_far), (8385, None)); + let (pairs, ..) = bridgeable(&circles, ArcRadius::Share(1.0), 15.0).unwrap(); + assert_eq!(pairs.len(), 4160); + assert!(pairs.iter().all(|&((i, j), _)| (i < 65) == (j < 65))); + assert!(bridges_any(&circles, ArcRadius::Share(1.0), 15.0)); + } + #[test] fn huge_circles_bridge_with_finite_anchors_or_are_refused() { // Squaring these lengths overflows f64. diff --git a/crates/pathops/src/addons/pathtools/tangent_circle.rs b/crates/pathops/src/addons/pathtools/tangent_circle.rs index b17a52cac6..2a7fed0045 100644 --- a/crates/pathops/src/addons/pathtools/tangent_circle.rs +++ b/crates/pathops/src/addons/pathtools/tangent_circle.rs @@ -10,13 +10,19 @@ //! from a point to an outline changes by at most the distance the point moves, so a cell whose //! center is too far from every condition holds no center and is dropped. The cells left are //! refined with Newton's method on the exact curves. +//! +//! The Tangent Circle tool's circles on two picked segments are [`circles_through`] and +//! [`circles_of_radius`]. use kurbo::{CubicBez, ParamCurve, Point, Vec2}; use vectorcraft_geom::PathData; +mod on_segments; #[cfg(test)] mod tests; +pub use on_segments::{SegmentCircle, circles_of_radius, circles_through}; + /// Most segments the shapes may hold together, counted by [`tangent_circle_segments`]. pub const MAX_TANGENT_CIRCLE_SEGMENTS: usize = 2_000; diff --git a/crates/pathops/src/addons/pathtools/tangent_circle/on_segments.rs b/crates/pathops/src/addons/pathtools/tangent_circle/on_segments.rs new file mode 100644 index 0000000000..615c7f1412 --- /dev/null +++ b/crates/pathops/src/addons/pathtools/tangent_circle/on_segments.rs @@ -0,0 +1,268 @@ +//! The circles the Tangent Circle tool draws on two picked segments: the circle tangent to the +//! first segment at a point that also touches the second ([`circles_through`]), or the circles of a +//! radius tangent to the first segment that also touch the second ([`circles_of_radius`]). "The +//! second" is a list of segments (the picked one and those next to it). A circle touches them when +//! the nearest of their points to its center is on the circle, so they lie outside it, and it never +//! crosses the first segment. +//! +//! The roots are found by sampling a distance function along one parameter: samples where it is 0, +//! bisection where it changes sign, and a golden-section search where it comes down to 0 between +//! samples without changing sign. + +use kurbo::{CubicBez, ParamCurve, ParamCurveDeriv, ParamCurveNearest, Point, Vec2}; + +use super::Circle; + +/// A circle on two picked segments: the circle, where it touches the first segment and where it +/// touches the second ones. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SegmentCircle { + pub circle: Circle, + pub first: Point, + pub second: Point, +} + +/// Samples along the parameter the roots are looked for on. +const SAMPLES: usize = 512; +/// Bisection steps per root. +const BISECTIONS: usize = 64; +/// The largest radius [`circles_through`] looks at, as a multiple of the diagonal of the box around +/// the segments' control points. +const MAX_RADIUS: f64 = 1e4; +/// Below this share of the radius two points of a circle are one. +const SAME: f64 = 1e-7; +/// Below this share of the radius (or, while the radius is looked for, of the gap from the point to +/// the second segments) a circle's distance from the second segments counts as touching. +const CONTACT: f64 = 1e-9; +/// Below this (in units of the first segment's size) a length is rounding. +const ROUNDING: f64 = 1e-12; + +/// The diagonal of the box around the control points of `first` and `second`; none when it is 0 or +/// not finite. +fn scale(first: &CubicBez, second: &[CubicBez]) -> Option { + let pts = std::iter::once(first).chain(second).flat_map(|c| [c.p0, c.p1, c.p2, c.p3]); + let (mut lo, mut hi) = (Point::new(f64::INFINITY, f64::INFINITY), Point::new(f64::NEG_INFINITY, f64::NEG_INFINITY)); + for p in pts { + if !(p.x.is_finite() && p.y.is_finite()) { + return None; + } + lo = Point::new(lo.x.min(p.x), lo.y.min(p.y)); + hi = Point::new(hi.x.max(p.x), hi.y.max(p.y)); + } + let d = (hi - lo).hypot(); + (d.is_finite() && d > 0.0).then_some(d) +} + +/// The nearest point to `q` on `segs` and its distance. +fn nearest(q: Point, segs: &[CubicBez]) -> Option<(f64, Point)> { + segs.iter() + .map(|c| { + let n = c.nearest(q, 1e-9); + (n.distance_sq.sqrt(), c.eval(n.t)) + }) + .min_by(|a, b| a.0.total_cmp(&b.0)) +} + +/// The unit normal of `c` at `t` (its tangent turned a quarter turn). Where the derivative is 0 (a +/// handle lying on its anchor), the direction the curve leaves in: toward the far handle, or the +/// other end. None where the segment does not move by more than rounding in units of `scale`, its +/// size. +fn normal(c: &CubicBez, t: f64, scale: f64) -> Option { + let tiny = ROUNDING * scale; + let d = c.deriv().eval(t).to_vec2(); + let d = if d.hypot() > tiny { + d + } else if t < 0.5 { + c.p2 - c.p0 + } else { + c.p3 - c.p1 + }; + let d = if d.hypot() > tiny { d } else { c.p3 - c.p0 }; + let len = d.hypot(); + (len.is_finite() && len > tiny).then(|| Vec2::new(-d.y / len, d.x / len)) +} + +/// The parameters where `f` is 0, within `zero`, in order: every sample where it is (a stretch where +/// it stays 0 gives each of its samples), each place between two samples where it changes sign +/// (found by bisection), and, where `f` comes toward 0 between samples and goes back without a +/// sample on the other side, the place it comes nearest (a golden-section search): a touch when it +/// reaches 0 there, and the two places on either side, by bisection, when it passes 0. +fn roots(samples: &[f64], f: impl Fn(f64) -> Option, zero: f64) -> Vec { + let mut out = vec![]; + let values: Vec> = samples.iter().map(|s| f(*s)).collect(); + let is_zero = |v: f64| v.abs() <= zero; + for (s, v) in samples.iter().zip(&values) { + if v.is_some_and(is_zero) { + out.push(*s); + } + } + for (k, w) in values.windows(3).enumerate() { + let (Some(a), Some(b), Some(c)) = (w[0], w[1], w[2]) else { continue }; + let (Some(&lo), Some(&hi)) = (samples.get(k), samples.get(k + 2)) else { continue }; + let same_side = (a > 0.0) == (b > 0.0) && (b > 0.0) == (c > 0.0); + // A low point, or one of two equal low samples about a touch half way between them. + let low = b.abs() <= a.abs() && b.abs() <= c.abs() && (b.abs() < a.abs() || b.abs() < c.abs()); + if !same_side || is_zero(a) || is_zero(b) || is_zero(c) || !low { + continue; + } + out.extend(near_zero(lo, hi, b > 0.0, &f, zero)); + } + // At either end the lowest sample has no sample beyond it: the stretch to the next one. + for (end, next) in [(0, 1), (values.len().saturating_sub(1), values.len().saturating_sub(2))] { + let (Some(Some(a)), Some(Some(b))) = (values.get(end), values.get(next)) else { continue }; + let (Some(&s), Some(&t)) = (samples.get(end), samples.get(next)) else { continue }; + if (a > &0.0) == (b > &0.0) && !is_zero(*a) && !is_zero(*b) && a.abs() < b.abs() { + out.extend(near_zero(s.min(t), s.max(t), *a > 0.0, &f, zero)); + } + } + for (k, w) in values.windows(2).enumerate() { + let (Some(a), Some(b)) = (w[0], w[1]) else { continue }; + let (Some(&lo), Some(&hi)) = (samples.get(k), samples.get(k + 1)) else { continue }; + if (a > 0.0) == (b > 0.0) || is_zero(a) || is_zero(b) { + continue; + } + out.extend(bisect(lo, hi, &f)); + } + out.sort_by(f64::total_cmp); + out +} + +/// Where `f`, above 0 (`positive`) or below at the samples `lo` and `hi`, comes nearest 0 between +/// them: that place when it reaches 0 there, the two places on either side where it passes 0, or +/// none. +fn near_zero(lo: f64, hi: f64, positive: bool, f: &impl Fn(f64) -> Option, zero: f64) -> Vec { + // Toward 0 is down for a positive `f`, up for a negative one. + let toward = if positive { 1.0 } else { -1.0 }; + let Some(m) = smallest(lo, hi, |s| f(s).map(|v| v * toward)) else { return vec![] }; + let Some(fm) = f(m) else { return vec![] }; + if fm.abs() <= zero { + vec![m] + } else if fm * toward < 0.0 { + bisect(lo, m, f).into_iter().chain(bisect(m, hi, f)).collect() + } else { + vec![] + } +} + +/// Where `f` changes sign between `lo` and `hi`, by bisection; none when it does not. +fn bisect(mut lo: f64, mut hi: f64, f: impl Fn(f64) -> Option) -> Option { + let (a, b) = (f(lo)?, f(hi)?); + if (a > 0.0) == (b > 0.0) { + return None; + } + let positive_low = a > 0.0; + for _ in 0..BISECTIONS { + let mid = 0.5 * (lo + hi); + match f(mid) { + Some(v) if (v > 0.0) == positive_low => lo = mid, + Some(_) => hi = mid, + None => break, + } + } + Some(0.5 * (lo + hi)) +} + +/// Where `g` is smallest between `lo` and `hi`, by a golden-section search; none where `g` has no +/// value. +fn smallest(mut lo: f64, mut hi: f64, g: impl Fn(f64) -> Option) -> Option { + const INV_PHI: f64 = 0.618_033_988_749_894_9; + let (mut a, mut b) = (hi - INV_PHI * (hi - lo), lo + INV_PHI * (hi - lo)); + let (mut ga, mut gb) = (g(a)?, g(b)?); + for _ in 0..BISECTIONS { + if ga < gb { + hi = b; + (b, gb) = (a, ga); + a = hi - INV_PHI * (hi - lo); + ga = g(a)?; + } else { + lo = a; + (a, ga) = (b, gb); + b = lo + INV_PHI * (hi - lo); + gb = g(b)?; + } + } + Some(0.5 * (lo + hi)) +} + +/// Where the circle about `center` of radius `r` touches `second`: the nearest of their points, when +/// it is on the circle (within a millionth of the radius, plus rounding in units of `scale`). None +/// for a root where the distance only jumps past the radius, as it does where the first segment +/// turns back on itself and its normal flips. +fn touching(center: Point, r: f64, second: &[CubicBez], scale: f64) -> Option { + nearest(center, second).filter(|(d, _)| (d - r).abs() <= 1e-6 * r + ROUNDING * scale).map(|(_, p)| p) +} + +/// `found` without circles that cross `first`, that touch the two at one point, or that repeat an +/// earlier one (the same center, touching `first` at the same point). +fn keep(found: Vec, first: &CubicBez) -> Vec { + let own = scale(first, &[]).unwrap_or(0.0); + let mut out: Vec = vec![]; + for c in found { + let r = c.circle.radius; + let crosses = nearest(c.circle.center, std::slice::from_ref(first)).is_none_or(|(d, _)| d < r * (1.0 - 1e-6)); + let one_point = (c.first - c.second).hypot() <= SAME * r; + // The roots come in order along their parameter, so a repeat follows its first. Circles of + // one large radius at places tried close together along `first` are not repeats. + let repeat = + out.last().is_some_and(|o| (o.circle.center - c.circle.center).hypot() <= SAME * r * 10.0 && (o.first - c.first).hypot() <= SAME * own); + if !(crosses || one_point || repeat) && r.is_finite() && r > 0.0 { + out.push(c); + } + } + out +} + +/// The circles tangent to `first` at parameter `t` (passing through that point, their centers on +/// its normal there) that touch `second`. An empty list when `first` has no direction at `t`, when +/// the point is on `second`, or when no circle touches it; at most two in practice, one on each side. +pub fn circles_through(first: CubicBez, t: f64, second: &[CubicBez]) -> Vec { + if second.is_empty() || !t.is_finite() { + return vec![]; + } + let t = t.clamp(0.0, 1.0); + let (Some(scale), Some(own)) = (scale(&first, second), scale(&first, &[])) else { return vec![] }; + let Some(n) = normal(&first, t, own) else { return vec![] }; + let p = first.eval(t); + // On the second segments (a corner the two share), up to rounding in units of the first + // segment's size: no circle. + let on = ROUNDING * own; + let Some((gap, _)) = nearest(p, second).filter(|(d, _)| *d > on) else { return vec![] }; + // Radii spaced evenly in their logarithm, from half the gap from the point to the second + // segments (no smaller circle through the point reaches them) to far past the segments. + let (lo, hi) = (0.5 * gap * (1.0 - 1e-9), MAX_RADIUS * scale.max(gap)); + let samples: Vec = (0..=SAMPLES).map(|k| lo * (hi / lo).powf(k as f64 / SAMPLES as f64)).collect(); + let mut found = vec![]; + for side in [1.0, -1.0] { + let center = |r: f64| p + n * (side * r); + for r in roots(&samples, |r| nearest(center(r), second).map(|(d, _)| d - r), CONTACT * gap) { + if let Some(touch) = touching(center(r), r, second, own) { + found.push(SegmentCircle { circle: Circle { center: center(r), radius: r }, first: p, second: touch }); + } + } + } + keep(found, &first) +} + +/// The circles of `radius` tangent to `first` (their centers `radius` from it along its normal) +/// that touch `second`. An empty list when the radius is not above 0 or none is found. Where the +/// segments run twice the radius apart along a stretch, every circle along it touches both, and one +/// is listed for each of the 513 places along `first` that are tried there. +pub fn circles_of_radius(first: CubicBez, second: &[CubicBez], radius: f64) -> Vec { + if second.is_empty() || !radius.is_finite() || radius <= 0.0 { + return vec![]; + } + let (Some(_), Some(own)) = (scale(&first, second), scale(&first, &[])) else { return vec![] }; + let samples: Vec = (0..=SAMPLES).map(|k| k as f64 / SAMPLES as f64).collect(); + let mut found = vec![]; + for side in [1.0, -1.0] { + let center = |t: f64| normal(&first, t, own).map(|n| first.eval(t) + n * (side * radius)); + for t in roots(&samples, |t| center(t).and_then(|c| nearest(c, second)).map(|(d, _)| d - radius), CONTACT * radius) { + if let Some(c) = center(t) + && let Some(touch) = touching(c, radius, second, own) + { + found.push(SegmentCircle { circle: Circle { center: c, radius }, first: first.eval(t), second: touch }); + } + } + } + keep(found, &first) +} diff --git a/crates/pathops/src/addons/pathtools/tangent_circle/tests.rs b/crates/pathops/src/addons/pathtools/tangent_circle/tests.rs index 8b63d29873..c130fb5be3 100644 --- a/crates/pathops/src/addons/pathtools/tangent_circle/tests.rs +++ b/crates/pathops/src/addons/pathtools/tangent_circle/tests.rs @@ -1,4 +1,4 @@ -use kurbo::{Affine, Point, Rect}; +use kurbo::{Affine, CubicBez, Point, Rect}; use vectorcraft_geom::{PathData, SubPath, shapes}; use super::*; @@ -485,3 +485,210 @@ fn answers_about_a_tiny_shape_far_away_stay_apart() { assert!(a.y < b.y - 1e-3 || ((a.y - b.y).abs() <= 1e-3 && a.x < b.x), "{found:?}"); } } + +/// A straight segment from `a` to `b`, its handles at its thirds so that `t` runs evenly along it. +fn line(a: (f64, f64), b: (f64, f64)) -> CubicBez { + let (a, b) = (Point::new(a.0, a.1), Point::new(b.0, b.1)); + CubicBez::new(a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b) +} + +#[test] +fn a_line_with_its_handles_on_its_anchors_has_a_direction_at_its_ends() { + let (a, b) = (Point::new(0.0, 0.0), Point::new(100.0, 0.0)); + for t in [0.0, 1.0] { + let p = CubicBez::new(a, a, b, b).eval(t); + let found = circles_through(CubicBez::new(a, a, b, b), t, &[line((-50.0, 40.0), (150.0, 40.0))]); + assert_eq!(found.len(), 1, "{t}: {found:?}"); + assert!(near(found[0].circle.center, p.x, 20.0, 1e-6), "{t}: {found:?}"); + } +} + +fn near(p: Point, x: f64, y: f64, tol: f64) -> bool { + (p - Point::new(x, y)).hypot() <= tol +} + +#[test] +fn a_circle_through_a_point_of_one_line_touches_a_parallel_line() { + let found = circles_through(line((0.0, 0.0), (100.0, 0.0)), 0.5, &[line((0.0, 40.0), (100.0, 40.0))]); + // Only toward the other line: away from it, no circle reaches it. + assert_eq!(found.len(), 1, "{found:?}"); + let c = found[0]; + assert!(near(c.circle.center, 50.0, 20.0, 1e-6) && (c.circle.radius - 20.0).abs() < 1e-6, "{c:?}"); + assert!(near(c.first, 50.0, 0.0, 1e-9) && near(c.second, 50.0, 40.0, 1e-6), "{c:?}"); +} + +#[test] +fn a_crossing_line_gives_a_circle_on_each_side() { + let found = circles_through(line((0.0, 0.0), (100.0, 0.0)), 0.3, &[line((80.0, -100.0), (80.0, 100.0))]); + assert_eq!(found.len(), 2, "{found:?}"); + for y in [50.0, -50.0] { + assert!(found.iter().any(|c| near(c.circle.center, 30.0, y, 1e-6) && (c.circle.radius - 50.0).abs() < 1e-6), "{y}: {found:?}"); + } +} + +#[test] +fn a_circle_that_crosses_the_first_segment_is_left_out() { + // Through (50, 75) on a flat first segment, the circle touching y = -200 has radius 137.5. + let below = [line((-500.0, -200.0), (500.0, -200.0))]; + let flat = circles_through(line((0.0, 75.0), (100.0, 75.0)), 0.5, &below); + assert_eq!(flat.len(), 1, "{flat:?}"); + assert!((flat[0].circle.radius - 137.5).abs() < 1e-6, "{flat:?}"); + // On a hump from (0, 0) up to (50, 75) and back down to (100, 0), the same circle crosses the + // hump's sides (its center (50, -62.5) is 80 from (0, 0)), and none on the other side reaches. + let hump = CubicBez::new(Point::new(0.0, 0.0), Point::new(0.0, 100.0), Point::new(100.0, 100.0), Point::new(100.0, 0.0)); + assert!(near(hump.eval(0.5), 50.0, 75.0, 1e-9)); + let found = circles_through(hump, 0.5, &below); + assert!(found.is_empty(), "{found:?}"); +} + +#[test] +fn where_the_first_segment_turns_back_only_circles_that_touch_are_kept() { + // Out to (75, 0) and back: the normal flips at the turn, and the distance to the line jumps there. + let first = CubicBez::new(Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 0.0), Point::new(0.0, 0.0)); + let second = [line((-100.0, 40.0), (200.0, 40.0))]; + let found = circles_of_radius(first, &second, 30.0); + for c in &found { + assert!((c.circle.center.y - 10.0).abs() < 1e-6 || (c.circle.center.y - 70.0).abs() < 1e-6, "{c:?}"); + } + assert!(!found.iter().any(|c| (c.circle.center.x - 75.0).abs() < 1.0), "{found:?}"); +} + +#[test] +fn a_circle_through_a_point_touches_a_curved_segment() { + // The second segments are a Bézier circle of radius 20 about (50, 100): touched from outside, + // |center − (50, 100)| = r + 20 with the center at (50, r), so r = 40. + let ring = circle(50.0, 100.0, 20.0); + let segs: Vec = (0..4).map(|i| ring.subpaths[0].segment(i)).collect(); + let found = circles_through(line((0.0, 0.0), (100.0, 0.0)), 0.5, &segs); + assert_eq!(found.len(), 1, "{found:?}"); + let c = found[0]; + // Within the Bézier circle's own error (0.0273% of 20). + assert!((c.circle.radius - 40.0).abs() < 0.01 && near(c.circle.center, 50.0, 40.0, 0.01), "{c:?}"); + assert!(near(c.second, 50.0, 80.0, 0.01), "{c:?}"); +} + +#[test] +fn on_a_curved_first_segment_the_center_is_on_the_normal() { + // A quarter of a ring of radius 50 about (0, 0); the second segment a line far off to the right. + let ring = circle(0.0, 0.0, 50.0); + let mut checked = 0; + for i in 0..4 { + let first = ring.subpaths[0].segment(i); + for t in [0.0, 0.3, 0.7, 1.0] { + let found = circles_through(first, t, &[line((300.0, -500.0), (300.0, 500.0))]); + let tangent = kurbo::ParamCurveDeriv::deriv(&first).eval(t).to_vec2(); + for c in &found { + let to_center = c.circle.center - c.first; + assert!(to_center.dot(tangent).abs() <= 1e-9 * to_center.hypot() * tangent.hypot(), "{i} {t}: {c:?}"); + checked += 1; + } + } + } + assert!(checked >= 8, "{checked}"); +} + +#[test] +fn a_radius_fills_the_corner_between_two_lines() { + let first = line((0.0, 0.0), (100.0, 0.0)); + let found = circles_of_radius(first, &[line((100.0, 0.0), (100.0, 100.0))], 10.0); + // Outside the corner a circle tangent to the first line reaches the second only at the shared + // corner, where it touches both at one point: left out. + assert_eq!(found.len(), 1, "{found:?}"); + let c = found[0]; + assert!(near(c.circle.center, 90.0, 10.0, 1e-6) && c.circle.radius == 10.0, "{c:?}"); + assert!(near(c.first, 90.0, 0.0, 1e-6) && near(c.second, 100.0, 10.0, 1e-6), "{c:?}"); +} + +#[test] +fn lines_twice_the_radius_apart_give_circles_all_along() { + let found = circles_of_radius(line((0.0, 0.0), (100.0, 0.0)), &[line((0.0, 40.0), (100.0, 40.0))], 20.0); + assert!(found.len() > 100, "{}", found.len()); + assert!(found.iter().all(|c| (c.circle.center.y - 20.0).abs() < 1e-9 && c.circle.radius == 20.0), "{found:?}"); + let xs: Vec = found.iter().map(|c| c.circle.center.x).collect(); + assert!(xs.iter().any(|x| *x < 1.0) && xs.iter().any(|x| *x > 99.0), "from end to end: {xs:?}"); + // At a radius of 1,000,000 pt the places tried along the line, 0.2 pt apart, stay apart. + let found = circles_of_radius(line((0.0, 0.0), (100.0, 0.0)), &[line((0.0, 2e6), (100.0, 2e6))], 1e6); + let xs: Vec = found.iter().map(|c| c.circle.center.x).collect(); + let widest = xs.windows(2).map(|w| w[1] - w[0]).fold(0.0, f64::max); + assert!(xs.iter().any(|x| *x < 1.0) && xs.iter().any(|x| *x > 99.0) && widest < 1.0, "from end to end, none merged: {xs:?}"); +} + +#[test] +fn a_circle_that_touches_a_curve_between_the_places_tried_is_found() { + // A ring of radius 20 about (50.3, 60): a circle of radius 20 on the line y = 0 reaches it only + // at x = 50.3, between the places tried along the line, without the distance changing sign. + let ring = circle(50.3, 60.0, 20.0); + let segs: Vec = (0..4).map(|i| ring.subpaths[0].segment(i)).collect(); + let found = circles_of_radius(line((0.0, 0.0), (100.0, 0.0)), &segs, 20.0); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(near(found[0].circle.center, 50.3, 20.0, 1e-3) && near(found[0].second, 50.3, 40.0, 1e-3), "{found:?}"); +} + +#[test] +fn a_touch_half_way_between_two_places_tried_is_found() { + // A point half way between the places tried at x = 50 and x = 50.1953125: the two samples + // either side are equally far from a touch. + let dot = line((50.097_656_25, 40.0), (50.097_656_25, 40.0)); + let found = circles_of_radius(line((0.0, 0.0), (100.0, 0.0)), &[dot], 20.0); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(near(found[0].circle.center, 50.097_656_25, 20.0, 1e-6), "{found:?}"); +} + +#[test] +fn a_touch_between_the_end_and_the_next_place_tried_is_found() { + for x in [0.05, 99.95] { + let found = circles_of_radius(line((0.0, 0.0), (100.0, 0.0)), &[line((x, 40.0), (x, 40.0))], 20.0); + assert_eq!(found.len(), 1, "{x}: {found:?}"); + assert!(near(found[0].circle.center, x, 20.0, 1e-6), "{x}: {found:?}"); + } +} + +#[test] +fn two_circles_between_the_same_two_places_tried_are_both_found() { + // A point a hair less than twice the radius from the line: two circles, about 0.02 pt either + // side of x = 50.05, both between the places tried at 50 and 50.1953125. + let (x, y) = (50.05, 39.99999); + let found = circles_of_radius(line((0.0, 0.0), (100.0, 0.0)), &[line((x, y), (x, y))], 20.0); + assert_eq!(found.len(), 2, "{found:?}"); + let dx = (400.0 - (y - 20.0) * (y - 20.0)).sqrt(); + assert!(near(found[0].circle.center, x - dx, 20.0, 1e-6) && near(found[1].circle.center, x + dx, 20.0, 1e-6), "{found:?}"); +} + +#[test] +fn a_tiny_circle_between_long_lines_close_together_is_found() { + let found = circles_through(line((0.0, 0.0), (100.0, 0.0)), 0.5, &[line((0.0, 1e-4), (100.0, 1e-4))]); + assert_eq!(found.len(), 1, "{found:?}"); + assert!((found[0].circle.radius - 5e-5).abs() < 1e-12 && near(found[0].circle.center, 50.0, 5e-5, 1e-12), "{found:?}"); + // A short line near a very long one: the long one's size does not hide the gap. + let found = circles_through(line((0.0, 0.0), (100.0, 0.0)), 0.5, &[line((-5e9, 1e-3), (5e9, 1e-3))]); + assert_eq!(found.len(), 1, "{found:?}"); + assert!((found[0].circle.radius - 5e-4).abs() < 1e-9, "{found:?}"); + // Lines 1e-5 pt apart moved 1e9 pt to the right. + let found = circles_through(line((1e9, 0.0), (1e9 + 100.0, 0.0)), 0.5, &[line((1e9, 1e-5), (1e9 + 100.0, 1e-5))]); + assert_eq!(found.len(), 1, "{found:?}"); + assert!((found[0].circle.radius - 5e-6).abs() < 1e-9, "{found:?}"); +} + +#[test] +fn long_segments_far_apart_give_no_circle_of_a_small_radius() { + // Lines 1e10 pt long and 1450 pt apart: a circle of radius 500 on one stays 950 pt from the other. + let found = circles_of_radius(line((0.0, 0.0), (1e10, 0.0)), &[line((0.0, 1450.0), (1e10, 1450.0))], 500.0); + assert!(found.is_empty(), "{:?}", found.first()); + // A radius of 1,000,000 pt and lines 0.05 pt more than twice that apart: no touch. + let found = circles_of_radius(line((0.0, 0.0), (100.0, 0.0)), &[line((0.0, 2_000_000.05), (100.0, 2_000_000.05))], 1e6); + assert!(found.is_empty(), "{:?}", found.first()); +} + +#[test] +fn no_circle_when_the_radius_is_too_small_or_the_point_is_on_the_second() { + let (first, other) = (line((0.0, 0.0), (100.0, 0.0)), line((0.0, 40.0), (100.0, 40.0))); + assert!(circles_of_radius(first, &[other], 5.0).is_empty()); + for r in [0.0, -1.0, f64::NAN, f64::INFINITY] { + assert!(circles_of_radius(first, &[other], r).is_empty(), "{r}"); + } + assert!(circles_through(first, 1.0, &[line((100.0, 0.0), (100.0, 100.0))]).is_empty(), "the point is on the second"); + assert!(circles_through(first, 0.5, &[]).is_empty()); + assert!(circles_through(first, f64::NAN, &[other]).is_empty()); + let dot = line((5.0, 5.0), (5.0, 5.0)); + assert!(circles_through(dot, 0.5, &[other]).is_empty(), "no direction"); +} 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/import/actual_text.rs b/crates/pdf/src/import/actual_text.rs index aec147f99e..aa7f9a5e76 100644 --- a/crates/pdf/src/import/actual_text.rs +++ b/crates/pdf/src/import/actual_text.rs @@ -1,6 +1,6 @@ //! Bounded ownership of authored replacement text (ISO 32000-1, 14.9.4). -use super::state::Builder; +use super::state::{Builder, HeldStroke}; use super::{Affine, Look, Placement, Shape, TextLine, Upright}; use crate::import_text::TextContent; @@ -21,13 +21,16 @@ impl ActualText { self.depth = self.depth.saturating_add(1); } - pub(super) fn end(&mut self) { - if self.owner == Some(self.depth) { + /// `true`: the owner's span ended. + pub(super) fn end(&mut self) -> bool { + let ended = self.owner == Some(self.depth); + if ended { self.owner = None; self.pending = None; self.empty = false; } self.depth = self.depth.saturating_sub(1); + ended } pub(super) fn active(&self) -> bool { @@ -62,13 +65,32 @@ impl Builder<'_> { /// against the glyph's original Unicode, not against this replacement's characters. pub(super) fn actual_glyph(&mut self, o: &craft_pdf::interpret::font::OutlineGlyph, m: Affine, at: Placement, look: Look, opacity: f32) -> bool { let key = o.font_cache_key(); - self.flush_glyphs(); - // A fill and stroke callback for the same glyph consumes its text only once. - if let (Some(stroke), Some(line)) = (&look.stroke, &mut self.text) - && look.fill.is_none() - && line.stroke_actual(key, at, stroke.clone(), look.overprint_stroke) + // A fill and stroke callback for the same glyph consumes its text only once: the stroke + // goes over the glyph of the span filled, matched as the stroke pass ends as any other + // (`Builder::hold_stroke`), on a line the operator's kerning finished too. + let stroking = look.fill.is_none() && look.stroke.is_some(); + if let Some(stroke) = &look.stroke + && stroking { - return true; + let h = HeldStroke { + font: key, + at, + opacity, + text: String::new(), + stroke: stroke.clone(), + overprint: look.overprint_stroke, + glyph: None, + actual: true, + first: (0, 0), + }; + if self.hold_stroke(h) { + return true; + } + } + self.flush_glyphs(); + // Stroked type of its own ends the stroke pass of the glyphs filled before it. + if stroking { + self.end_fills(); } let width = o.advance_width().filter(|w| w.is_finite()); let advance = width.map_or(at.size * 0.5, |w| w as f64 / 1000.0 * at.size * at.h_scale / 100.0); @@ -87,7 +109,7 @@ impl Builder<'_> { None => line.push_content(&look, at, opacity, advance, content), }; if !self.text.as_mut().is_some_and(place) { - self.flush_text(); + self.park_text(!stroking); let mut line = TextLine::new(at, opacity); if !place(&mut line) { self.actual.pending = pending; diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index eb8742f2db..a908cf6879 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -4,7 +4,9 @@ use super::entry::{ UNNAMED_CHARACTERS_NOTE, max_objects, }; use super::reshaped; -use super::state::{Builder, Frame, FrameKind, GlyphRun, Saved, bounds, grouped, mean_scale, paints, round3, same_stroke, stroke_layer, type_stroke}; +use super::state::{ + Builder, Frame, FrameKind, GlyphRun, HeldStroke, Saved, bounds, grouped, mean_scale, paints, round3, same_stroke, stroke_layer, type_stroke, +}; use super::{ Affine, Appearance, AppearanceItem, Arc, BezPath, BfString, BlendMode, CacheKey, Color, Colors, Families, FillLayer, FillRule, FunctionBudget, FunctionPaint, HashMap, HashSet, ImageBlob, ImageObject, Knockout, Look, MaskSpec, MaskType, Native, Node, NodeId, NodeKind, OpacityMask, Paint, @@ -12,6 +14,30 @@ use super::{ Upright, Walked, clipped, contains, fold_stop_opacity, function_paint, gradient_shape, is_rectangle, luminance, mask_spec, shading_gradient, }; +/// The most lines of type kept for a text-showing operator's stroke pass ([`Builder::park_text`]): +/// beyond them the oldest is finished, and strokes over its glyphs come in as type of their own. +/// They are the lines its fill pass finished, besides the open one: a `TJ` over up to 65 lines is +/// filled and stroked, one over more is a filled object and a stroked one for each part. The +/// pass's first stroke goes over a glyph finished so, which can match a glyph kept (a `TJ` that +/// draws it again where it began): a first stroke that may go over one of them is type of its own +/// too, and ends the pass ([`Builder::hold_stroke`]). +const MAX_PARKED: usize = 64; + +/// The most strokes of a stroke pass held to be matched to the glyphs they go over +/// ([`Builder::hold_stroke`]): beyond them, those held are matched to the last glyphs filled one +/// after another that they go over, with as many glyphs filled from there on as strokes held +/// ([`Builder::replayed`]), and the pass goes on from there. The reader tells no operator's +/// start, so the last such run is taken: the operator's fill pass is the one right before its +/// stroke pass. An operator that fills the same run of more than this many glyphs twice at the +/// same places may have its first strokes matched to its second copy; such a pass is matched as +/// well as it can be, not exactly. +const MAX_HELD: usize = 4096; + +/// The most glyphs [`Builder::replayed`] compares to the strokes held, for bounded work on +/// hostile input: beyond them, each stroke goes over the first glyph it may go over after the one +/// the stroke before it goes over. +const MAX_REPLAY_WORK: usize = 1 << 20; + fn is_colour_face(face: &vectorcraft_text::FontFace) -> bool { use skrifa::Tag; use skrifa::raw::TableProvider; @@ -37,6 +63,9 @@ impl<'p> Builder<'p> { type3_run: None, text: None, text_glyphs: vec![], + parked: vec![], + held: vec![], + lost: None, text_as, actual: Default::default(), images: HashMap::new(), @@ -119,6 +148,9 @@ impl<'p> Builder<'p> { self.type3_run = None; self.text = None; self.text_glyphs.clear(); + self.parked.clear(); + self.held.clear(); + self.lost = None; self.mask = None; self.masked.clear(); self.marked.clear(); @@ -420,7 +452,10 @@ impl<'p> Builder<'p> { } } + /// Finish the open run of glyphs kept as outlines, once the strokes held are matched + /// ([`Self::settle_strokes`]): whatever is drawn next ends their stroke pass. pub(super) fn flush_glyphs(&mut self) { + self.settle_strokes(); let Some(run) = self.glyphs.take() else { return }; if run.path.elements().is_empty() { return; @@ -444,17 +479,308 @@ impl<'p> Builder<'p> { self.push_node(n); } + /// Finish the open line of type ([`Self::finish_text`]) before something else is drawn: a + /// path, an image, a Type 3 glyph's art, or a change of blend mode or soft mask. Nothing is + /// drawn between a text-showing operator's fill pass and its stroke pass, so no stroke drawn + /// after this goes over a glyph finished before it either: the glyphs of lines finished + /// before their stroke pass could end are forgotten ([`Self::park_text`]). pub(super) fn flush_text(&mut self) { + self.finish_text(); + self.lost = None; + } + + /// Finish the open line of type ([`Self::end_text`]) and the outlines it was kept as. Unlike + /// [`Self::flush_text`] it keeps the glyphs of lines finished past the most kept: it also + /// runs as the next line starts ([`Self::park_text`]), which may be in the middle of a fill + /// pass, after one of its glyphs was kept as an outline. + fn finish_text(&mut self) { if self.end_text() { self.flush_glyphs(); } } - /// 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. It runs in the middle of a fill pass when + /// one of its glyphs is kept as an outline: the glyphs of lines finished past the most kept + /// before it are not forgotten there, as they are by [`Self::flush_text`]. 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`]). A line finished here keeps them too ([`Self::finish_text`]): the + /// next line starting draws nothing else, and after a glyph kept as an outline there is no + /// open line, so the operator's next glyph comes here in the middle of its fill pass. + 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.finish_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, each line + // looked at counted as work. + let left = |(slot, i): (usize, usize), work: &mut usize| { + let mut n = 0usize; + for s in slot..=self.parked.len() { + if n >= held.len() { + break; + } + *work = work.saturating_add(1); + if let Some(line) = self.line_at(s) { + n = n.saturating_add(line.filled_len().saturating_sub(if s == slot { i } else { 0 })); + } + } + n.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); + // Too few glyphs filled after it for the strokes held: not where the pass starts. + let short = left(first, &mut work) < held.len(); + if work > MAX_REPLAY_WORK { + return None; + } + if short { + continue; + } + let mut places = Vec::with_capacity(held.len()); + places.push(first); + let mut at = first; + for h in rest { + work = work.saturating_add(1); + if work > MAX_REPLAY_WORK { + return None; + } + at = self.after_fill(at); + if !self.line_at(at.0).is_some_and(|line| line.fills_at(at.1, h.font, h.at, h.opacity, &h.text, h.actual)) { + break; + } + places.push(at); + } + if places.len() == held.len() { + return Some(places); + } + } + None + } + + /// [`Self::settle_strokes`], each stroke matched to the last glyph it may go over (`last`), + /// or, when too many are held ([`Self::hold_stroke`]), as the start of a pass that goes on + /// ([`Self::replayed`]). + fn settle(&mut self, last: bool) { + if self.held.is_empty() { + return; + } + let held = std::mem::take(&mut self.held); + let mut places = vec![]; + if last { + let mut before = None; + for h in held.iter().rev() { + let Some(p) = self.last_fill(before, h) else { break }; + places.push(p); + before = Some(p); + } + places.reverse(); + } else if let Some(p) = self.replayed(&held) { + places = p; + } + // Each held stroke goes over the first glyph it may go over after the one before it + // does ([`Self::hold_stroke`]), so the last ones are found too: this is only a guard. + if places.len() != held.len() { + places = held.iter().map(|h| h.first).collect(); + } + // The slots of the parked lines finished so far, which the later places count in. + let mut finished = 0usize; + for (h, (slot, index)) in held.into_iter().zip(places) { + let slot = slot.saturating_sub(finished); + let parked = self.parked.len(); + // The lines before the one stroked are past the stroke pass: they are finished. + self.release_parked(slot); + finished = finished.saturating_add(slot.min(parked)); + let target = match self.parked.first_mut() { + Some((line, glyphs)) if slot < parked => Some((line, glyphs)), + _ => self.text.as_mut().map(|line| (line, &mut self.text_glyphs)), + }; + if let Some((line, glyphs)) = target + && line.stroke_filled_at(index, h.stroke, h.overprint) + { + // Upright glyphs aren't kept as outlines (nor are those filled only): a vertical + // line that came in as its outlines would lose the ones filled only. + glyphs.extend(h.glyph); + } + } + } + + /// Finish `line` of type, whose `glyphs` are its outlines ([`Self::keep_glyph`]). `true`: + /// it was kept as them ([`Self::end_text`]). + fn end_line(&mut self, mut line: TextLine, glyphs: Vec) -> bool { let held = std::mem::take(&mut line.held); // Type the file names itself (ActualText) is in reading order as it stands. let checked = !glyphs.is_empty() && line.mapped() && !line.has_type3; @@ -880,13 +1206,9 @@ impl<'p> Builder<'p> { scale: f64, overprint: bool, ) { - let Some((paint, stroke)) = drawn else { return }; - let mut path = o.outline(); - if path.elements().is_empty() { - return; + if let Some(g) = glyph_run(o, m, drawn, opacity, scale, overprint) { + self.text_glyphs.push(g); } - path.apply_affine(m); - self.text_glyphs.push(GlyphRun { path, paint, opacity, stroke, scale, overprint }); } fn type3_font_name(&mut self, key: u128) -> FontInfo { @@ -1150,10 +1472,22 @@ impl<'p> Builder<'p> { Some(top) => line.push_upright(&look, at, opacity, Upright { top }, &text), None => line.push(&look, at, opacity, advance, &text), }; + let stroking = look.fill.is_none() && look.stroke.is_some(); + // A stroke over a glyph filled before it, on the open line or one the same operator's + // kerning finished: matched once its stroke pass ends. + if let Some(s) = &look.stroke + && stroking + { + let glyph = if top.is_none() { glyph_run(o, m, drawn.clone(), opacity, scale, overprint) } else { None }; + let h = HeldStroke { font: key, at, opacity, text: text.clone(), stroke: s.clone(), overprint, glyph, actual: false, first: (0, 0) }; + if self.hold_stroke(h) { + return true; + } + } self.flush_glyphs(); // A stroke over the glyph just filled (fill and stroke rendering). if let (Some(s), Some(line)) = (&look.stroke, &mut self.text) - && look.fill.is_none() + && stroking && line.stroke_filled(key, at, opacity, &text, s.clone(), overprint) { // Upright glyphs aren't kept as outlines (nor, below, are those filled only): a @@ -1163,8 +1497,12 @@ impl<'p> Builder<'p> { } return true; } + // Stroked type of its own ends the stroke pass of the glyphs filled before it. + if stroking { + self.end_fills(); + } if !self.text.as_mut().is_some_and(place) { - self.flush_text(); + self.park_text(!stroking); let mut line = TextLine::new(at, opacity); place(&mut line); self.text = Some(line); @@ -1184,6 +1522,25 @@ impl<'p> Builder<'p> { } } +/// Glyph `o` placed by `m` and drawn with `drawn` as the outline it is kept as +/// ([`Builder::keep_glyph`]). Nothing for a glyph that shows nothing. +fn glyph_run( + o: &craft_pdf::interpret::font::OutlineGlyph, + m: Affine, + drawn: Option<(Paint, Option)>, + opacity: f32, + scale: f64, + overprint: bool, +) -> Option { + let (paint, stroke) = drawn?; + let mut path = o.outline(); + if path.elements().is_empty() { + return None; + } + path.apply_affine(m); + Some(GlyphRun { path, paint, opacity, stroke, scale, overprint }) +} + /// The characters of one glyph in the order they are drawn: a PDF names a ligature's characters /// in logical order (lam then alef for لا), while a horizontal line of type is gathered glyph by /// glyph in visual order and only then put back in logical order. Right-to-left characters are diff --git a/crates/pdf/src/import/device.rs b/crates/pdf/src/import/device.rs index 452090c6b6..47924a717d 100644 --- a/crates/pdf/src/import/device.rs +++ b/crates/pdf/src/import/device.rs @@ -453,12 +453,20 @@ impl<'a> Device<'a> for Builder<'_> { self.flush(); } self.marked.pop(); - self.actual.end(); + // A span's glyphs are stroked within it: a stroke after it goes over none of them. + if self.actual.end() { + self.end_fills(); + } } fn actual_text(&mut self, text: &[u8]) { + let active = self.actual.active(); if self.nested == 0 && self.text_as == crate::TextAs::Text && !self.actual.set(text) { self.warn("ActualText beyond the import size or nesting limit was left to glyph mappings"); } + // Nor does a stroke in a span go over a glyph filled before it. + if !active && self.actual.active() { + self.end_fills(); + } } } diff --git a/crates/pdf/src/import/state.rs b/crates/pdf/src/import/state.rs index d8068279cf..a76531348a 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,20 @@ 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`]), a boundary of stroke passes ([`Builder::end_fills`]) or + /// anything else drawn ([`Builder::flush_text`]). + pub(super) lost: Option, pub(super) text_as: TextAs, pub(super) actual: super::actual_text::ActualText, pub(super) images: HashMap, diff --git a/crates/pdf/src/import_text.rs b/crates/pdf/src/import_text.rs index a6b128e042..fcfd849d92 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,60 @@ 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. The +/// first [`MAX_LOST_FILLS`](Self::MAX_LOST_FILLS) are kept, those finished first: a stroke pass +/// starts over its operator's first glyph, which is among them unless more glyphs than that were +/// finished so before the operator, since the last stroke or anything else drawn (#8549). A +/// stroke over a glyph not kept matches none, so type filled and stroked after a page of type +/// filled only stays filled and stroked; an operator whose first glyph isn't kept and that draws +/// it again where it drew it may have its first stroke matched to the copy, as well as it can be, +/// not exactly. +#[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)>, +} + +impl LostFills { + /// The most glyphs kept, for bounded work and memory on hostile input: those after them + /// are not kept. + pub const MAX_LOST_FILLS: usize = 4096; + + /// Add the glyphs `line` filled that a stroke may still go over, while there is room. + 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 { + 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 kept ([`TextLine::fills_at`]). + pub fn may_stroke(&self, font: u128, at: Placement, opacity: f32, text: &str, actual: bool) -> bool { + 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 +389,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 +440,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 +478,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 +580,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 +596,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 +679,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 +729,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 +859,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 +871,14 @@ impl TextLine { /// ([`Look::takes`]): then the glyph's text becomes a run of its own with this stroke, and /// the glyphs before it stay unstroked (#7741). The line's text is the same either way, so /// the characters' slots, gaps and authored flags, kept along the whole line, still line up. + /// + /// Not a glyph drawn before a boundary of stroke passes ([`end_fills`](Self::end_fills)): + /// a stroke after the end of an ActualText span would otherwise stroke the span's replacement + /// text, and one after its start a glyph filled before the span (#8543). fn stroke_last(&mut self, font: u128, at: Placement, glyph: &str, stroke: TypeStroke, overprint: bool) -> bool { + if self.last_closed { + return false; + } self.flush_stroke(); let start = self.last_start; let last_at = self.last_at; diff --git a/crates/pdf/src/print/plates.rs b/crates/pdf/src/print/plates.rs index 5b33683dcf..dada741c9d 100644 --- a/crates/pdf/src/print/plates.rs +++ b/crates/pdf/src/print/plates.rs @@ -7,7 +7,7 @@ use std::sync::Arc; use vectorcraft_color::cms::{self, Cms, Model, ProfileKind}; use vectorcraft_color::swatch::REGISTRATION; -use vectorcraft_color::{BlendMode, Color, GradientKind, Paint}; +use vectorcraft_color::{BlendMode, Color, GradientKind, GradientStop, Paint}; use vectorcraft_doc::inks::{Link, StopPlates, inks, plates, spot_color, stop_inks, visit_node_colors}; use vectorcraft_doc::overprint::{darken_overprints, is_black_ink, is_white}; use vectorcraft_doc::{AppearanceItem, ColorMode, Document, ImageBlob, Node, NodeKind}; @@ -175,33 +175,74 @@ impl<'a> Separator<'a> { /// carry counts as none. A link to a swatch the document lacks separates as the color's own /// values, so such a black counts as unlinked. fn no_ink(&self, plate: &str, p: &Paint) -> bool { - let process = |swatch: Option<&str>| swatch.is_none_or(|n| n != REGISTRATION && self.doc.swatch(n).is_none_or(|w| !w.spot)); - let none = |c: &Color, process: bool, ink: f32| ink <= 0.0 || (self.postscript && process && ink <= 0.005 && is_black_ink(c, 1.0, false)); match p { Paint::Solid { color, swatch, tint } => { - none(color, process(swatch.as_deref()), self.ink(plate, color, swatch.as_deref().map(|s| (s, *tint)))) + self.none(color, self.process(swatch.as_deref()), self.ink(plate, color, swatch.as_deref().map(|s| (s, *tint)))) } Paint::Gradient(g) => match g.freeform.as_ref().filter(|f| g.gradient.kind == GradientKind::Freeform && !f.points.is_empty()) { - Some(f) => f.points.iter().all(|pt| none(&pt.color, true, self.ink(plate, &pt.color, None))), - None => { - !g.gradient.stops.is_empty() - && g.gradient.stops.iter().all(|s| { - let ink = self.stop_ink(plate, &s.color, s.swatch.as_deref().map(|n| (n, s.tint)), s.plates); - none(&s.color, s.plates.is_none() && process(s.swatch.as_deref()), ink) - }) - } + Some(f) => f.points.iter().all(|pt| self.point_none(plate, &pt.color)), + None => !g.gradient.stops.is_empty() && g.gradient.stops.iter().all(|s| self.stop_none(plate, s)), }, _ => false, } } + /// Whether a color linked to swatch `swatch` separates as process inks: no link, or a link + /// to a process swatch or to one the document lacks, other than Registration. + fn process(&self, swatch: Option<&str>) -> bool { + swatch.is_none_or(|n| n != REGISTRATION && self.doc.swatch(n).is_none_or(|w| !w.spot)) + } + + /// Whether `ink` of color `c` (separating as process inks when `process` is true) counts as + /// none, as [`Self::no_ink`] says. + fn none(&self, c: &Color, process: bool, ink: f32) -> bool { + ink <= 0.0 || (self.postscript && process && ink <= 0.005 && is_black_ink(c, 1.0, false)) + } + + /// Whether gradient stop `s` puts none of ink `plate` down, as [`Self::no_ink`] says. + fn stop_none(&self, plate: &str, s: &GradientStop) -> bool { + let ink = self.stop_ink(plate, &s.color, s.swatch.as_deref().map(|n| (n, s.tint)), s.plates); + self.none(&s.color, s.plates.is_none() && self.process(s.swatch.as_deref()), ink) + } + + /// Whether a freeform gradient's point of color `c` puts none of ink `plate` down, as + /// [`Self::no_ink`] says. + fn point_none(&self, plate: &str, c: &Color) -> bool { + self.none(c, true, self.ink(plate, c, None)) + } + + /// On a PostScript plate, make paper white the stops and points of overprinting gradient `p` + /// that put none of ink `plate` down while others do ([`Self::no_ink`]'s rule for each): the + /// writer leaves the plate below as it is where the gradient is paper white. + fn clear_inkless_stops(&self, plate: &str, p: &mut Paint) { + let Paint::Gradient(g) = p else { return }; + if !self.postscript { + return; + } + let paper = Color::Gray { k: 0.0 }; + match g.freeform.as_mut().filter(|f| g.gradient.kind == GradientKind::Freeform && !f.points.is_empty()) { + Some(f) => { + for pt in f.points.iter_mut().filter(|pt| self.point_none(plate, &pt.color)) { + pt.color = paper; + } + } + None => { + for s in g.gradient.stops.iter_mut().filter(|s| self.stop_none(plate, s)) { + *s = GradientStop { color: paper, swatch: None, tint: 1.0, plates: None, ..s.clone() }; + } + } + } + } + /// Overprinting fills and strokes of `a`'s subtree with a Normal blending mode, and /// overprinting character fills and strokes, that put none of ink `plate` down leave its plate /// as it is: they are drawn as nothing on it (white ones with `discard_white` aside, which /// knock out). A writer without blending modes (PostScript) then keeps the ink below them, /// where it would draw their Darken as a knockout. One that puts any ink down is drawn, and on /// a PostScript plate its ink replaces the ink below, as a nonzero component of an overprinting - /// color replaces the backdrop's with overprint mode 1 (ISO 32000-1, 11.7.4.2). + /// color replaces the backdrop's with overprint mode 1 (ISO 32000-1, 11.7.4.2). On a + /// PostScript plate, the stops and points of such a gradient that put none of the ink down + /// become paper white ([`Self::clear_inkless_stops`]), which the writer leaves out there. fn clear_inkless_overprints(&self, plate: &str, a: &mut Arc, discard_white: bool) { let inkless = |overprint: bool, p: &Paint| overprint && !p.is_none() && !(discard_white && is_white(p)) && self.no_ink(plate, p); let n = Arc::make_mut(a); @@ -212,15 +253,21 @@ impl<'a> Separator<'a> { }; if normal && inkless(it.overprint(), it.paint()) { *it.paint_mut() = Paint::None; + } else if normal && it.overprint() { + self.clear_inkless_stops(plate, it.paint_mut()); } } if let NodeKind::Text(t) = &mut n.kind { for r in &mut t.runs { if inkless(r.style.overprint_fill, &r.style.fill) { r.style.fill = Paint::None; + } else if r.style.overprint_fill { + self.clear_inkless_stops(plate, &mut r.style.fill); } if inkless(r.style.overprint_stroke, &r.style.stroke) { r.style.stroke = Paint::None; + } else if r.style.overprint_stroke { + self.clear_inkless_stops(plate, &mut r.style.stroke); } } } diff --git a/crates/pdf/src/tests/print.rs b/crates/pdf/src/tests/print.rs index 588273faf9..bee9e61bad 100644 --- a/crates/pdf/src/tests/print.rs +++ b/crates/pdf/src/tests/print.rs @@ -999,6 +999,42 @@ fn overprinting_paints_keep_their_faint_ink_on_postscript_plates() { } } +#[test] +fn a_near_black_stop_of_an_overprinting_gradient_puts_no_cyan_on_postscript_plates() { + // 0.4% cyan beside 100% K counts as black on a PostScript plate stop by stop, as a solid fill + // of it does: the cyan plate draws that stop of an overprinting gradient as paper white. A + // PDF plate and a gradient that does not overprint keep the 0.4%. + let stops = vec![GradientStop::new(0.0, Color::cmyk(0.004, 0.0, 0.0, 1.0)), GradientStop::new(1.0, Color::cmyk(0.5, 0.0, 0.0, 0.0))]; + let fade = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let square = |x: f64, overprint: bool| { + let r = shapes::rectangle(Rect::new(x, 15.0, x + 20.0, 35.0)); + let mut n = Node::path(vectorcraft_doc::NodeId(0), r, Appearance::basic(fade.clone(), Paint::None, 0.0)); + if let Some(f) = n.appearance.fill_mut() { + f.overprint = overprint; + } + n + }; + let d = over_cyan(vec![square(10.0, true), square(40.0, false)]); + // The cyan plate's stops of each gradient, in thousandths of the ink. + let stops = |postscript: bool| { + let opts = PrintOptions { settings: settings(json!({"output": {"mode": "separations"}})), postscript, ..Default::default() }; + let p = plan(&d, &opts).unwrap(); + let mut all = vec![]; + p.plates[0].walk(|n| { + if let Some(Paint::Gradient(g)) = n.appearance.fill().map(|f| &f.paint) { + let gray = |s: &GradientStop| match s.color { + Color::Gray { k } if s.swatch.is_none() => (k * 1000.0).round(), + c => panic!("{c:?}"), + }; + all.push(g.gradient.stops.iter().map(gray).collect::>()); + } + }); + all + }; + assert_eq!(stops(true), [[0.0, 500.0], [4.0, 500.0]], "PostScript: the overprinting gradient, the other"); + assert_eq!(stops(false), [[4.0, 500.0], [4.0, 500.0]], "PDF"); +} + #[test] fn overprinting_type_leaves_the_inks_below_on_separations() { let style = vectorcraft_doc::CharStyle { fill: Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)), ..Default::default() }; diff --git a/crates/pdf/src/tests/textstroke.rs b/crates/pdf/src/tests/textstroke.rs index 1cc1edf5ba..109685c9c7 100644 --- a/crates/pdf/src/tests/textstroke.rs +++ b/crates/pdf/src/tests/textstroke.rs @@ -346,3 +346,279 @@ 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::>()); +} + +/// A page drawing `first`, then `lines` lines of type filled only, each of `glyphs` `A`s, then +/// `Title` filled and stroked by one `Tj` (mode 2) at 40, 150 in 24-point type, after `between`. +fn dense_then_title(first: &str, lines: usize, glyphs: usize, between: &str) -> String { + let line = format!("({}) Tj 0 -1 Td", "A".repeat(glyphs)); + let dense = vec![line; lines].join(" "); + let title = "/F1 24 Tf 1 0 0 1 40 150 Tm (Title) Tj"; + format!("BT 0 Tr {first} /F1 1 Tf 1 0 0 1 10 190 Tm {dense} ET {between} BT 2 Tr {title} 0 Tr ET").replace("{title}", title) +} + +/// Type filled and stroked after a page of type filled only, more lines than a fill pass keeps +/// for its stroke pass, comes in as one type object filled and stroked, with or without a path +/// drawn between them: neither the lines finished past the 64 kept nor more than 4,096 glyphs' +/// worth of them make the title's first stroke the start of a stroke pass over them (#8549). +#[test] +fn type_filled_and_stroked_after_a_dense_page_of_filled_type_is_filled_and_stroked() { + let title = vec![("Title".to_string(), true, true)]; + for (lines, glyphs) in [(150, 50), (70, 1)] { + for between in ["", "0 0 m 10 10 l S"] { + let types = type_runs(&dense_then_title("", lines, glyphs, between)); + assert_eq!(types.len(), lines + 1, "{lines} lines of {glyphs}, {between:?}"); + assert_eq!(types.last(), Some(&title), "{lines} lines of {glyphs}, {between:?}"); + } + } +} + +/// Type filled and stroked where a glyph filled only stood, on a line finished past the 64 kept, +/// comes in as one type object filled and stroked when a path is drawn between them: nothing is +/// drawn between an operator's fill pass and its stroke pass, so the path ends the stroke pass +/// of every glyph filled before it (#8549). +#[test] +fn type_filled_and_stroked_over_a_finished_glyph_after_a_path_is_filled_and_stroked() { + let content = dense_then_title("{title}", 70, 1, "0 0 m 10 10 l S"); + let types = type_runs(&content); + assert_eq!(types.len(), 72, "{content}"); + assert_eq!(types.first(), Some(&vec![("Title".to_string(), true, false)]), "{content}"); + assert_eq!(types.last(), Some(&vec![("Title".to_string(), true, true)]), "{content}"); +} + +/// A `TJ` over more lines than are kept, with a glyph kept as an outline after the lines it +/// finished past the 64 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 glyph after +/// the outline starts a line in the middle of the fill pass, which keeps the glyphs of the lines +/// finished, so the stroke over the first glyph doesn't take the last part's fill (#8549). +#[test] +fn an_outline_glyph_in_a_tj_over_more_lines_than_are_kept_leaves_fill_and_stroke_apart() { + // Helvetica's A is 667 units wide and code 1 draws no character (kept as an outline) and + // advances none: 66 As and 65 kerns of 3,500 back to the first A's origin. + let parts = vec!["(A)"; 66].join(" -3500 "); + let content = format!("BT 2 Tr /F1 4 Tf 20 80 Td [{parts} (\\001) 271522 (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, 67).chain(std::iter::repeat_n(stroke, 67)).collect(); + assert_eq!(type_runs(&content), want); +} 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 dc459d4331..fff66aa142 100644 --- a/crates/render/src/encode/quantize.rs +++ b/crates/render/src/encode/quantize.rs @@ -203,6 +203,21 @@ pub fn quantize_to(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, pal 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_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..78a6ea236b 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -493,7 +493,27 @@ impl Renderer { { return self.draw_staged(ctx, f, stage, &bp, *rule); } - let art = self.fx_art(f.symbols, a, cache); + let separations = f.opts.proof.as_ref().filter(|proof| proof.separations.is_some()); + let key = Arc::as_ptr(a) as usize; + let previous = (cache && separations.is_some()).then(|| self.fx_arts.get(&key, self.stamp).map(|entry| entry.1.clone())).flatten(); + let mut art = self.fx_art(f.symbols, a, cache); + if let Some(proof) = separations + && previous.as_ref().is_none_or(|previous| !Arc::ptr_eq(previous, &art)) + { + let made = crate::proof::generated_black(f.doc, proof, &art); + if !Arc::ptr_eq(&made, &art) { + if let Some((_, bounds)) = self.three_d_bounds.remove(&(Arc::as_ptr(&art) as usize)) { + self.three_d_bounds.insert(Arc::as_ptr(&made) as usize, (Arc::downgrade(&made), bounds)); + } + if cache + && let Some((node, _, found)) = + self.fx_arts.get(&key, self.stamp).filter(|entry| Arc::ptr_eq(&entry.0, a) && Arc::ptr_eq(&entry.1, &art)).cloned() + { + self.fx_arts.insert(key, (node, made.clone(), found), crate::lru::node_bytes(&made), self.stamp); + } + art = made; + } + } // Art the cache did not keep is made again in the next frame. let kept = cache && self.fx_arts.get(&(Arc::as_ptr(a) as usize), self.stamp).is_some_and(|e| Arc::ptr_eq(&e.1, &art)); let outer = self.made_again; @@ -1029,7 +1049,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/fx/tests.rs b/crates/render/src/fx/tests.rs index 3c2e9ff65a..1832f18580 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -1010,7 +1010,7 @@ fn an_edit_out_of_sight_builds_nothing() { let drawn_hidden = extruded(&mut d, 70.0); let ids = [d.insert(Some(l), 0, hidden).unwrap(), group.children().unwrap()[0].id, d.insert(Some(l), 0, drawn_hidden).unwrap()]; d.insert(Some(l), 0, group).unwrap(); - let opts = RenderOptions { hidden: vec![ids[2]], ..Default::default() }; + let opts = RenderOptions { hidden: [ids[2]].into(), ..Default::default() }; let mut r = Renderer::new(); r.render(&d, 100, 100, Affine::IDENTITY, &opts); let mut e = d.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/render/src/options.rs b/crates/render/src/options.rs index 671c9b6b97..6f0f7cde99 100644 --- a/crates/render/src/options.rs +++ b/crates/render/src/options.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use super::geometry::region_pixels; use super::{Arc, NodeId, Rect, encode, proof}; @@ -39,8 +41,8 @@ pub struct RenderOptions { pub background: Option<[u8; 4]>, /// Draw artboards as white rectangles (screen view). Export sets this to false. pub artboards: bool, - /// Objects not to draw (e.g. the object being edited by a live drag preview). - pub hidden: Vec, + /// Objects not to draw (e.g. the layers and fold lines the Fold Preview's print leaves out). + pub hidden: HashSet, /// Draw the layers as their Layer Options show them on screen: Preview off in outline, Dim /// Images fading their images (a template layer's too), a template in Preview in Outline view. pub dim_templates: bool, @@ -194,7 +196,7 @@ impl Default for RenderOptions { outline: false, background: None, artboards: false, - hidden: vec![], + hidden: HashSet::new(), dim_templates: true, proof: None, overprint_preview: false, diff --git a/crates/render/src/proof.rs b/crates/render/src/proof.rs index 284ad8ce5d..e809afb4ee 100644 --- a/crates/render/src/proof.rs +++ b/crates/render/src/proof.rs @@ -28,11 +28,11 @@ use std::sync::{Arc, Mutex, OnceLock, RwLock, Weak}; use vectorcraft_color::cms::{self, Cms, CmykLut, PROCESS_PLATES, ProofLut, lab}; pub use vectorcraft_color::cms::{Intent, ProofSetup, ProofTarget}; -use vectorcraft_color::{Color, Swatch, SwatchGroup}; +use vectorcraft_color::{Color, Paint, Swatch, SwatchGroup}; pub use vectorcraft_doc::inks::{Inks, Link, Plate, inks, map_document_colors, map_node_colors, plates, spot_color}; use vectorcraft_doc::inks::{StopPlates, map_node_inks, stop_inks}; use vectorcraft_doc::overprint::darken_overprints; -use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, Shared}; +use vectorcraft_doc::{AppearanceItem, Document, ImageBlob, Node, NodeId, Shared}; use vello_cpu::Pixmap; use vello_cpu::color::PremulRgba8; @@ -80,6 +80,46 @@ fn plate_color(doc: &Document, c: &Cms, proof: &ProofSetup, visible: &[String], Color::Rgb { r, g, b } } +/// Map grayscale inks created after document preparation to the visible plates. +pub(crate) fn generated_black(doc: &Document, proof: &ProofSetup, art: &Arc) -> Arc { + let Some(visible) = proof.separations.as_deref() else { return art.clone() }; + let c = cms::active(); + let mut made = Node::clone(art); + if !visible.iter().any(|plate| plate == "Black") { + hide_generated_black(&mut made); + } + let mut changed = false; + map_node_inks(&mut made, &mut |color, link, plates| { + // Document colors are already display RGB; newly generated black retains its Gray ink. + if matches!(color, Color::Gray { .. }) { + changed = true; + plate_color(doc, &c, proof, visible, color, link, plates) + } else { + *color + } + }); + if changed { Arc::new(made) } else { art.clone() } +} + +fn hide_generated_black(node: &mut Node) { + for item in &mut node.appearance.items { + match item { + AppearanceItem::Fill(layer) if layer.overprint && matches!(layer.paint, Paint::Solid { color: Color::Gray { .. }, swatch: None, .. }) => { + layer.visible = false; + } + AppearanceItem::Stroke(layer) + if layer.overprint && matches!(layer.paint, Paint::Solid { color: Color::Gray { .. }, swatch: None, .. }) => + { + layer.visible = false; + } + _ => {} + } + } + for child in node.children_mut().into_iter().flatten() { + hide_generated_black(Arc::make_mut(child)); + } +} + /// Separations Preview's tables for placed images: what the visible plates show of display pixels /// and of a CMYK image's own inks ([`plate_rgb`]), for one proof setup, color settings and set of /// profiles. Each table is made when an image first needs it. diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index bd26c851cd..3e79641a51 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -499,7 +499,7 @@ impl Renderer { fn draw_content(&mut self, ctx: &mut RenderContext, f: &Frame, n: &Node, knockout: bool) { match &n.kind { NodeKind::Group { children, clip: false } if f.opts.trace_views && !f.opts.outline && Self::trace_view(f, n) != TraceView::Result => { - self.draw_trace_view(ctx, f, children, Self::trace_view(f, n), knockout) + self.draw_trace_view(ctx, f, children, (Self::trace_view(f, n), n.trace_split()), knockout) } NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } => { self.draw_children(ctx, f, children, knockout) @@ -641,9 +641,56 @@ impl Renderer { } /// An Image Trace object's `children` (the hidden source image, then the traced shapes) as - /// `view` shows them on screen. - fn draw_trace_view(&mut self, ctx: &mut RenderContext, f: &Frame, children: &[Arc], view: TraceView, knockout: bool) { + /// `view` shows them on screen, with `split`, the Split view's divider + /// ([`TraceView::split_of`]). + fn draw_trace_view(&mut self, ctx: &mut RenderContext, f: &Frame, children: &[Arc], (view, split): (TraceView, f64), knockout: bool) { let Some((source, shapes)) = children.split_first() else { return }; + if view == TraceView::Split { + // Each side is drawn once under a plain clip (no layer and no second render), in the + // image's own pixels so the divider turns with the image: the source image on the part + // of the image left of the divider, and the traced shapes everywhere else, art past any + // of the image's edges included. Without an image, with one of no size or that can't + // be inverted, or with the divider at the image's left edge, the traced shapes draw as + // they are. + let NodeKind::Image(im) = &source.kind else { return self.draw_children(ctx, f, shapes, knockout) }; + let (w, h) = (f64::from(im.width), f64::from(im.height)); + let at = w * split.clamp(0.0, 1.0); + let det = im.xf.determinant(); + if w <= 0.0 || h <= 0.0 || at <= 0.0 || !det.is_finite() || det.abs() < 1e-12 { + return self.draw_children(ctx, f, shapes, knockout); + } + // The result's side covers the image and the traced shapes' cached bounds, two screen + // pixels more so anti-aliased edges are not cut, in the image's pixels, less the + // source's side. + let inverse = im.xf.inverse(); + let (mut x0, mut x1, mut y0, mut y1) = (0.0_f64, w, 0.0_f64, h); + for c in shapes { + if let Some(b) = self.bounds_of(f.symbols, c).map(|b| b.inflate(f.px * 2.0, f.px * 2.0)) { + for q in [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)] { + let p = inverse * kurbo::Point::new(q.0, q.1); + if p.x.is_finite() && p.y.is_finite() { + (x0, x1, y0, y1) = (x0.min(p.x), x1.max(p.x), y0.min(p.y), y1.max(p.y)); + } + } + } + } + let part = |p: &mut BezPath, x0: f64, x1: f64, y0: f64, y1: f64| { + p.move_to(im.xf * kurbo::Point::new(x0, y0)); + p.line_to(im.xf * kurbo::Point::new(x1, y0)); + p.line_to(im.xf * kurbo::Point::new(x1, y1)); + p.line_to(im.xf * kurbo::Point::new(x0, y1)); + p.close_path(); + }; + let (mut left, mut right) = (BezPath::new(), BezPath::new()); + part(&mut left, 0.0, at, 0.0, h); + part(&mut right, x0, x1, y0, y1); + part(&mut right, 0.0, at, 0.0, h); + let comp = Composite { clip: Some((&left, FillRule::NonZero)), blends: true, ..Default::default() }; + self.group(ctx, f, comp, &mut |r, c, fr| r.draw_forced_arc(c, fr, source)); + let comp = Composite { clip: Some((&right, FillRule::EvenOdd)), blends: true, ..Default::default() }; + self.group(ctx, f, comp, &mut |r, c, fr| r.draw_children(c, fr, shapes, knockout)); + return; + } if view.shows_source() && matches!(source.kind, NodeKind::Image(_)) { self.draw_forced_arc(ctx, f, source); } diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 2a0e6c9a93..d63f9e91b4 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -224,6 +224,33 @@ fn hidden_and_culled() { assert_eq!(rr.stats.culled, 1); } +#[test] +fn a_render_leaves_out_every_object_of_a_large_hidden_set() { + // 2,000 one-pixel-wide strips; the strips in even columns are in `hidden`. + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let mut hidden = std::collections::HashSet::new(); + for row in 0..20 { + for col in 0..100 { + let r = Rect::new(f64::from(col), f64::from(row * 5), f64::from(col + 1), f64::from(row * 5 + 5)); + let n = rect_node(&mut d, r, Paint::solid(Color::BLACK), Paint::None, 0.0); + let id = d.insert(Some(l), usize::MAX, n).unwrap(); + if col % 2 == 0 { + hidden.insert(id); + } + } + } + assert_eq!(hidden.len(), 1_000); + let opts = RenderOptions { hidden, ..Default::default() }; + let r = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts); + for row in 0..20 { + for col in 0..100 { + let want = if col % 2 == 0 { [0, 0, 0, 0] } else { [0, 0, 0, 255] }; + assert_eq!(r.pixel(col, row * 5 + 2), want, "column {col}, row {row}"); + } + } +} + /// A document with symbol "Far" holding a red rectangle `art`, and an instance of it moved by /// (-50, -50): its 20 × 20 square, (-60, -60) to (-40, -40), lies outside a view of the page. fn far_instance(art: Rect) -> Document { @@ -841,6 +868,79 @@ fn trace_source_applies_the_hidden_image_mask() { assert_eq!(img.pixel(70, 50), [255, 255, 255, 255]); } +/// The Split view draws the source image left of its divider and the traced shapes right of it, +/// along the image's own width (also when the image is turned), with traced art past any of the +/// image's edges drawn whatever the divider, in the same frames a renderer that keeps its caches +/// draws, and in a zoomed and scrolled view and a turned view; exports draw the tracing result. +#[test] +fn split_view_draws_the_source_on_one_side_of_the_divider_and_the_result_on_the_other() { + use vectorcraft_doc::{ImageBlob, ImageObject}; + let mut png = vec![]; + image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let red = |p: [u8; 4]| p[0] > 200 && p[1] < 60 && p[2] < 60; + let blue = |p: [u8; 4]| p[2] > 200 && p[0] < 60; + // A red 80 × 80 source image at 10, 10, turned a half turn about its center when `turned`, with + // a blue traced square over all of it. + for turned in [false, true] { + let mut d = Document::new(100.0, 100.0); + d.images.insert("red".into(), ImageBlob::new("image/png", png.clone())); + let turn = if turned { Affine::rotate_about(std::f64::consts::PI, kurbo::Point::new(50.0, 50.0)) } else { Affine::IDENTITY }; + let xf = turn * Affine::translate((10.0, 10.0)) * Affine::scale(80.0); + let im = ImageObject { key: "red".into(), width: 1, height: 1, xf, link: None, placement: Default::default(), pixels: None }; + let mut source = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + source.visible = false; + let shape = rect_node(&mut d, Rect::new(10.0, 10.0, 90.0, 90.0), Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0); + // Traced art past the image's right edge on the page (a stroke along it, say). + let past = rect_node(&mut d, Rect::new(92.0, 46.0, 98.0, 54.0), Paint::solid(Color::rgb(0.0, 1.0, 0.0)), Paint::None, 0.0); + // And above the image's top edge, near its left edge. + let above = rect_node(&mut d, Rect::new(14.0, 2.0, 26.0, 8.0), Paint::solid(Color::rgb(0.0, 1.0, 0.0)), Paint::None, 0.0); + let mut g = Node::group(d.alloc_id(), vec![Arc::new(source), Arc::new(shape), Arc::new(past), Arc::new(above)]); + let id = g.id; + g.extras_mut().trace = Some(Box::new(serde_json::json!({ "view": "split", "split": 0.25 }))); + d.insert(Some(d.layers[0].id), 0, g).unwrap(); + let screen = RenderOptions { trace_views: true, background: Some([255; 4]), ..Default::default() }; + let export = RenderOptions { background: Some([255; 4]), ..Default::default() }; + let mut kept = Renderer::new(); + for split in [0.25, 0.0, 1.0, 0.25] { + if let Some(n) = d.node_mut(id) { + n.extras_mut().trace = Some(Box::new(serde_json::json!({ "view": "split", "split": split }))); + } + // The divider in page space: 30 across from the image's left edge, or from its right + // edge on the page once the image is turned. + let at = if turned { 90.0 - 80.0 * split } else { 10.0 + 80.0 * split }; + // The view: as is, zoomed in twice and scrolled, and turned a half turn about the page's + // middle; `px` finds the pixel showing page point (x, y). + let views: [(Affine, u32); 3] = [ + (Affine::IDENTITY, 100), + (Affine::translate((5.0, 7.0)) * Affine::scale(2.0), 210), + (Affine::rotate_about(std::f64::consts::PI, kurbo::Point::new(50.0, 50.0)), 100), + ]; + for (view, size) in views { + let px = |r: &Rendered, x: f64, y: f64| { + let q = view * kurbo::Point::new(x, y); + r.pixel(q.x.floor() as u32, q.y.floor() as u32) + }; + for r in [kept.render(&d, size, size, view, &screen), Renderer::new().render(&d, size, size, view, &screen)] { + for x in [12.5, 30.5, 48.5, 52.5, 70.5, 88.5] { + let p = px(&r, x, 50.5); + let source = if turned { x > at } else { x < at }; + assert!(if source { red(p) } else { blue(p) }, "turned {turned}, split {split}, view {view:?}, x = {x}: {p:?}"); + } + assert_eq!(px(&r, 5.5, 50.5), [255; 4], "nothing outside the image"); + // The art past the image's edges shows on either side of the divider. + let green = |p: [u8; 4]| p[1] > 200 && p[0] < 60 && p[2] < 60; + for (x, y) in [(95.5, 50.5), (20.5, 5.5)] { + let p = px(&r, x, y); + assert!(green(p), "turned {turned}, split {split}, view {view:?}, ({x}, {y}): {p:?}"); + } + } + } + let r = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &export); + assert!([12u32, 50, 88].iter().all(|x| blue(r.pixel(*x, 50))), "exports draw the result"); + } + } +} + #[test] fn artboards_white_on_pasteboard() { let d = Document::new(50.0, 50.0); diff --git a/crates/render/tests/it/golden.rs b/crates/render/tests/it/golden.rs index d6962e0e67..a9dcb7af63 100644 --- a/crates/render/tests/it/golden.rs +++ b/crates/render/tests/it/golden.rs @@ -473,7 +473,7 @@ fn invisible_and_hidden_nodes_are_not_drawn() { let mut b = DocBuilder::new(100.0, 100.0); let id = b.rect(Rect::new(0.0, 0.0, 100.0, 100.0), Color::BLACK, |_| {}); let d = b.build(); - let opts = vectorcraft_render::RenderOptions { background: Some([255, 255, 255, 255]), hidden: vec![id], ..Default::default() }; + let opts = vectorcraft_render::RenderOptions { background: Some([255, 255, 255, 255]), hidden: [id].into(), ..Default::default() }; let r = vectorcraft_render::Renderer::new().render(&d, 100, 100, vectorcraft_geom::Affine::IDENTITY, &opts); assert_eq!(Image::from_rendered(&r).ink(), 0); } 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/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/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/src/fontdb.rs b/crates/text/src/fontdb.rs index 59c99f8901..b7efa856c8 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}; @@ -56,7 +56,7 @@ use face::Instances; #[cfg(test)] pub(crate) use face::MAX_LIVE_INSTANCES; pub(crate) use face::PathAlignHeights; -pub use face::{FALLBACK_FAMILY, FontFace, IcfMargins}; +pub use face::{FALLBACK_FAMILY, FontFace, IcfMargins, OutlineFormat}; pub(crate) use glyph_pen::FlipPen; pub use gsub::{GlyphCategory, GlyphCategoryKind, GlyphOrigin, JoiningPosition, Substitution, SubstitutionKind}; #[cfg(not(target_arch = "wasm32"))] @@ -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/face.rs b/crates/text/src/fontdb/face.rs index f02ebea3fc..5c21fbb4f1 100644 --- a/crates/text/src/fontdb/face.rs +++ b/crates/text/src/fontdb/face.rs @@ -753,4 +753,54 @@ impl FontFace { use skrifa::raw::TableProvider; self.skrifa().is_some_and(|f| f.glyf().is_ok()) } + /// The kind of outlines the face's glyphs are drawn from ([`outline_format_of`]). + pub fn outline_format(&self) -> Option { + self.skrifa().and_then(|f| outline_format_of(&f)) + } +} + +/// The kind of outlines a face's glyphs are drawn from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OutlineFormat { + /// Quadratic outlines in a `glyf` table. + TrueType, + /// PostScript outlines in a `CFF ` or `CFF2` table. + Cff, +} + +/// The kind of outlines `font`'s glyphs are drawn from: TrueType when it has a `glyf` table, else +/// CFF when it has a `CFF ` or `CFF2` table. None for a font with neither (outlines in `VARC` +/// alone, color bitmaps only). +pub(crate) fn outline_format_of(font: &skrifa::FontRef<'_>) -> Option { + let has = |tag: &[u8; 4]| font.table_data(skrifa::Tag::new(tag)).is_some(); + if has(b"glyf") { + Some(OutlineFormat::TrueType) + } else if has(b"CFF ") || has(b"CFF2") { + Some(OutlineFormat::Cff) + } else { + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The outline format comes from the tables the font holds. + #[test] + fn outline_format_follows_the_outline_tables() { + let format = |tables: &[(&[u8; 4], &[u8])]| { + let font = crate::fontdb::sfnt_of(tables).unwrap_or_default(); + outline_format_of(&skrifa::FontRef::new(&font).unwrap()) + }; + let table = [0_u8; 4]; + assert_eq!(format(&[(b"glyf", &table), (b"loca", &table)]), Some(OutlineFormat::TrueType)); + assert_eq!(format(&[(b"CFF ", &table)]), Some(OutlineFormat::Cff)); + assert_eq!(format(&[(b"CFF2", &table)]), Some(OutlineFormat::Cff)); + assert_eq!(format(&[(b"VARC", &table)]), None); + assert_eq!(format(&[(b"sbix", &table)]), None); + // The built-in faces are TrueType. + let face = crate::FontDb::global().resolve("Source Sans 3", "Regular").map(|(f, _)| f).unwrap(); + assert_eq!(face.outline_format(), Some(OutlineFormat::TrueType)); + } } 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..deff6ce054 100644 --- a/crates/text/src/fontdb/traits.rs +++ b/crates/text/src/fontdb/traits.rs @@ -433,6 +433,31 @@ impl FontMatch { } } +/// The generic font family names that SVG and HTML files name in place of a font and no font file +/// provides; compared in any ASCII case ([`is_generic_family`]). The names follow CSS Fonts Module +/// Level 4, except `emoji`, which that module dropped and this list keeps. The list does not match +/// the functional `generic(...)` forms, and it 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..fee74054c1 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -36,6 +36,7 @@ mod vertical; mod warichu; pub(crate) use bidi::{is_rtl, para_bidi, starts_bidi}; +pub(crate) use breaking::is_hanging_punctuation; use breaking::tab_advance; #[cfg(test)] use breaking::{break_line, candidates}; @@ -62,30 +63,22 @@ fn continues_cluster(prev: Option<&SGlyph>, g: Option<&SGlyph>) -> bool { /// ([`upright_extent`]) as a share of `upright`, the length in font units its own width runs down. /// Empty for a glyph of one character. fn ligature_carets(text: &str, g: &SGlyph, rtl: bool, upright: Option) -> Vec<(usize, f64)> { - use unicode_segmentation::UnicodeSegmentation; - let Some(s) = text.get(g.byte..g.byte + g.len).filter(|_| g.len > 1) else { return Vec::new() }; - let starts: Vec = s.grapheme_indices(true).skip(1).map(|(i, _)| g.byte + i).collect(); - if starts.is_empty() { - return Vec::new(); - } - let parts = starts.len() + 1; - let from_font = if let Some(length) = upright { - let (cell, top) = upright_extent(g); - g.face - .vertical_ligature_carets(g.gid, starts.len(), top, cell) - .filter(|c| c.len() == starts.len() && length > 0.0) - .map(|c| c.into_iter().map(|d| d / length).collect::>()) - .filter(|c| c.iter().all(|f| *f > 0.0 && *f < 1.0)) - } else { - let advance = g.face.advance(g.gid); - g.face - .ligature_carets(g.gid, starts.len()) - .filter(|c| c.len() == starts.len() && advance > 0.0) - .map(|c| c.into_iter().map(|x| if rtl { 1.0 - x / advance } else { x / advance }).collect::>()) - }; - let mut at = from_font.unwrap_or_else(|| (1..parts).map(|j| j as f64 / parts as f64).collect()); - at.sort_by(f64::total_cmp); - starts.into_iter().zip(at).collect() + craft_font_catalog::ligature_caret_stops(text, g.byte, g.len, |count| { + if let Some(length) = upright { + let (cell, top) = upright_extent(g); + g.face + .vertical_ligature_carets(g.gid, count, top, cell) + .filter(|c| c.len() == count && length > 0.0) + .map(|c| c.into_iter().map(|d| d / length).collect::>()) + .filter(|c| c.iter().all(|f| *f > 0.0 && *f < 1.0)) + } else { + let advance = g.face.advance(g.gid); + g.face + .ligature_carets(g.gid, count) + .filter(|c| c.len() == count && advance > 0.0) + .map(|c| c.into_iter().map(|x| if rtl { 1.0 - x / advance } else { x / advance }).collect::>()) + } + }) } /// Does glyph `g`, standing upright in vertical type, take a cell of its own down the column? Every diff --git a/crates/text/src/layout/bidi.rs b/crates/text/src/layout/bidi.rs index 3f9872983d..e4574c42d4 100644 --- a/crates/text/src/layout/bidi.rs +++ b/crates/text/src/layout/bidi.rs @@ -81,34 +81,9 @@ pub(super) fn visual_order(bidi: Option<&BidiInfo<'_>>, paragraph_start: usize, return vec![]; } let levels = bidi.reordered_levels(para, line.start.saturating_sub(paragraph_start)..line.end.saturating_sub(paragraph_start)); - // A list marker (length 0) is a cluster of its own. - let mut clusters: Vec> = Vec::new(); - for (i, g) in glyphs.iter().enumerate() { - if i > 0 && glyphs.get(i - 1).is_some_and(|p| p.byte == g.byte && (p.len == 0) == (g.len == 0)) { - if let Some(c) = clusters.last_mut() { - c.end = i + 1; - } - } else { - clusters.push(i..i + 1); - } - } - // A list marker is at the paragraph's level, and at a right-to-left one its tab is drawn - // before (left of) its characters. - let cluster_levels: Vec<_> = clusters - .iter() - .filter_map(|c| glyphs.get(c.start)) - .map(|g| if g.len == 0 { g.level } else { levels.get(g.byte.saturating_sub(paragraph_start)).copied().unwrap_or(g.level) }) - .collect(); - let reversed = |i: usize| glyphs.get(clusters.get(i).map_or(0, |c| c.start)).is_some_and(|g| g.len == 0 && g.level.is_rtl()); - unicode_bidi::BidiInfo::reorder_visual(&cluster_levels) - .into_iter() - .filter_map(|i| clusters.get(i).map(|c| (c.clone(), reversed(i)))) - .flat_map(|(c, rev)| { - let mut v: Vec = c.collect(); - if rev { - v.reverse(); - } - v - }) - .collect() + craft_font_catalog::visual_order( + glyphs.iter().map(|g| craft_font_catalog::VisualGlyph { byte: g.byte, len: g.len, level: g.level }), + paragraph_start, + &levels, + ) } diff --git a/crates/text/src/layout/breaking.rs b/crates/text/src/layout/breaking.rs index 375bc343a2..bfc984f83e 100644 --- a/crates/text/src/layout/breaking.rs +++ b/crates/text/src/layout/breaking.rs @@ -1,11 +1,76 @@ use super::region::Region; use super::vertical::stands_upright; use super::{ - Affine, BezPath, Breakpoint, Burasagari, EPS, FirstBaseline, FontDb, HyphenationOptions, Kinsoku, KinsokuShoriType, LeadingModel, SGlyph, - hyphen_glyph, is_cjk, no_line_end, no_line_start, points_for, soft_line_start, + Affine, BezPath, Breakpoint, Burasagari, EPS, FirstBaseline, FontDb, HyphenationOptions, Kinsoku, KinsokuShoriType, LeadingModel, ParaStyle, + SGlyph, hyphen_glyph, is_cjk, no_line_end, no_line_start, points_for, soft_line_start, }; use crate::justify::is_format_control; +/// The kinsoku rules a paragraph is composed with: a built-in Kinsoku Set (None, Hard or Soft), or +/// a custom set (Type › Kinsoku Shori Settings…). +#[derive(Clone, Copy, Debug)] +pub(crate) enum KinsokuRules<'a> { + BuiltIn(Kinsoku), + Custom(&'a vectorcraft_doc::KinsokuSet), +} + +impl<'a> KinsokuRules<'a> { + /// The rules of paragraph `para`: its custom set when it has one, else its Kinsoku Set. + pub(crate) fn of(para: &'a ParaStyle) -> Self { + match ¶.kinsoku_set { + Some(set) => Self::Custom(set), + None => Self::BuiltIn(para.kinsoku), + } + } + + /// Kinsoku None: no character is kept off a line's ends, and Bunri-Kinshi has no effect. + pub(crate) fn is_none(self) -> bool { + matches!(self, Self::BuiltIn(Kinsoku::None)) + } + + /// May `c` not start a line? Hard: every character of [`no_line_start`]; Soft: those + /// [`soft_line_start`] doesn't let start one; a custom set: its Cannot Start Line characters. + pub(crate) fn cannot_start(self, c: char) -> bool { + match self { + Self::BuiltIn(Kinsoku::None) => false, + Self::BuiltIn(Kinsoku::Hard) => no_line_start(c), + Self::BuiltIn(Kinsoku::Soft) => no_line_start(c) && !soft_line_start(c), + Self::Custom(set) => set.cannot_start(c), + } + } + + /// May `c` not end a line? Hard and Soft: an opening bracket ([`no_line_end`]); a custom set: + /// its Cannot End Line characters. + pub(crate) fn cannot_end(self, c: char) -> bool { + match self { + Self::BuiltIn(Kinsoku::None) => false, + Self::BuiltIn(Kinsoku::Hard | Kinsoku::Soft) => no_line_end(c), + Self::Custom(set) => set.cannot_end(c), + } + } + + /// May `c` hang outside a line's end with Burasagari? An East Asian comma or full stop (、。,. + /// and the half-width 、。), or a custom set's Hanging Punctuation characters. + pub(crate) fn hangs(self, c: char) -> bool { + match self { + Self::BuiltIn(_) => is_hanging_punctuation(c), + Self::Custom(set) => set.hangs(c), + } + } +} + +impl From for KinsokuRules<'_> { + fn from(k: Kinsoku) -> Self { + Self::BuiltIn(k) + } +} + +/// The punctuation Burasagari hangs with the built-in Kinsoku Sets: the East Asian comma and full +/// stop, full width and half width. +pub(crate) fn is_hanging_punctuation(c: char) -> bool { + matches!(c, '、' | '。' | ',' | '.' | '、' | '。') +} + /// Vertical metrics of a line: (ascent, descent, leading, cap height, x height). #[derive(Clone, Copy, Debug, PartialEq)] pub(super) struct Metrics { @@ -351,12 +416,13 @@ pub(super) fn leader_outline(db: &FontDb, g: &SGlyph, leader: &str, origin: f64, /// Width of the word starting at glyph `i`: its advances up to the first place a line may break /// (spaces left out, the hyphen of a soft hyphen in), the least room a line needs not to break /// inside it. As in [`break_line`], kinsoku keeps a character that may not end a line with the one -/// after it, a No Break run (its spaces inside it included) is one word up to a forced line break, +/// after it, spaces between them included, a No Break run (its spaces inside it included) is one word up to a forced line break, /// and a cluster is never split. A soft hyphen just before a forced line break adds no hyphen. A list marker at `i` (glyphs of length 0) counts whole, with the word after it. A word /// that ends where a line may end is measured as the line is set: without the spaces at its end, /// and with its last glyph as narrow as `line_end` sets it; one that ends at a soft hyphen or past -/// the measured glyphs is not. -pub(super) fn word_width(g: &[SGlyph], i: usize, line_end: &[f64], kinsoku: Kinsoku) -> f64 { +/// the measured glyphs is not. With `burasagari`, the word may end after hanging punctuation. +pub(super) fn word_width<'k>(g: &[SGlyph], i: usize, line_end: &[f64], kinsoku: impl Into>, burasagari: Burasagari) -> f64 { + let kinsoku = kinsoku.into(); /// Glyphs measured at most: a word wrapped over many lines is measured again from each line's /// start, and one this long is broken inside whatever cell it meets. const MAX_GLYPHS: usize = 1024; @@ -375,7 +441,15 @@ pub(super) fn word_width(g: &[SGlyph], i: usize, line_end: &[f64], kinsoku: Kins return set(w, trailing, ink); } if gl.is_space() && (end == start || !splits_no_break(g, end)) { - return set(w, trailing, ink); + // A line breaks after one of these spaces only where kinsoku allows it, as in + // [`break_line`]; where it allows none (after 「, or before 」), the word goes on past them. + let run = end + g[end..].iter().take(start + MAX_GLYPHS - end).take_while(|h| h.is_space()).count(); + if end == start || (end..run).any(|k| g[k].break_after() && g[k].len > 0 && kinsoku_allows(g, k, kinsoku) && !splits_no_break(g, k + 1)) { + return set(w, trailing, ink); + } + let spaces: f64 = g[end..run].iter().map(|h| h.adv).sum(); + (w, trailing, end) = (w + spaces, trailing + spaces, run); + continue; } let forced_next = g.get(end + 1).is_some_and(|n| n.ch == '\u{2028}'); if gl.is_soft_hyphen() && !forced_next && kinsoku_allows(g, end, kinsoku) && !splits_no_break(g, end + 1) { @@ -389,7 +463,10 @@ pub(super) fn word_width(g: &[SGlyph], i: usize, line_end: &[f64], kinsoku: Kins (trailing, ink) = (0.0, end); } let cluster_ends = g.get(end).is_none_or(|next| next.byte != gl.byte); - if gl.break_after() && cluster_ends && kinsoku_allows(g, end - 1, kinsoku) && !splits_no_break(g, end) { + // Hanging punctuation of one glyph may end the line with Burasagari, as in [`break_line`]. + let alone = cluster_ends && end.checked_sub(2).and_then(|k| g.get(k)).is_none_or(|p| p.byte != gl.byte); + let hang_break = burasagari != Burasagari::None && alone && hangs(gl, kinsoku); + if (gl.break_after() || hang_break) && cluster_ends && kinsoku_allows(g, end - 1, kinsoku) && !splits_no_break(g, end) { return set(w, trailing, ink); } } @@ -442,7 +519,7 @@ fn drawn_last(g: &[SGlyph], i: usize, j: usize, end: usize) -> bool { /// end in the visual order of the line's levels ([`drawn_last`]) and the line before the mark fits /// as drawn. #[allow(clippy::too_many_arguments)] -pub(super) fn break_line( +pub(super) fn break_line<'k>( text: &str, g: &[SGlyph], i: usize, @@ -451,31 +528,16 @@ pub(super) fn break_line( x_start: f64, hyphenate: Option<(&HyphenationOptions, f64)>, burasagari: Burasagari, - kinsoku: Kinsoku, + kinsoku: impl Into>, kinsoku_type: KinsokuShoriType, hanging: bool, vertical: bool, 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 kinsoku = kinsoku.into(); + 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 }; @@ -567,13 +629,14 @@ pub(super) fn break_line( let measured = if tabbed && fits.is_some() { (ink + cluster_ink).max(stops_reached) } else { x + cluster_width }; overflowed |= tabbed && fits.is_some() && j > first && !gl.is_space() && x + cluster_width - end_credit > width + EPS; if j > first && !gl.is_space() && measured - end_credit > width + EPS { - // It ends the line with the spaces after it, when the mark is all the characters kept - // together (the line's last character is the mark, which is what hangs). Once the line - // holds a tab and is measured as drawn, the mark hangs only where it is drawn at the - // line's right end (its cluster is last in the line's visual order, [`drawn_last`]) and - // the line before it fits as drawn with no line-end trim on its last glyph; otherwise the - // line ends at a legal break that fits as drawn. - let alone = g[j..cluster_end].iter().all(|h| h.byte == gl.byte); + // It ends the line with the spaces after it, when it hangs alone: not with the rest of a + // No Break run or an inseparable sequence it starts, and only as one glyph, the one the + // line's geometry hangs. Once the line holds a tab and is measured as drawn, the mark + // hangs only where it is drawn at the line's right end (its cluster is last in the + // line's visual order, [`drawn_last`]) and the line before it fits as drawn with no + // line-end trim on its last glyph; otherwise the line ends at a legal break that fits as + // drawn. + let alone = cluster_end == j + 1; let hangs_as_drawn = || match fits.filter(|_| tabbed) { None => true, Some(fits) => { @@ -584,7 +647,7 @@ pub(super) fn break_line( drawn_last(g, i, j, cluster_end) && line_end_credit(g, line_end, body) == 0.0 && fits(j, false) } }; - if burasagari != Burasagari::None && hangs(gl) && alone && kinsoku_allows(g, cluster_end - 1, kinsoku) && hangs_as_drawn() { + if burasagari != Burasagari::None && alone && hangs(gl, kinsoku) && kinsoku_allows(g, cluster_end - 1, kinsoku) && hangs_as_drawn() { let mut end = cluster_end; while g.get(end).is_some_and(SGlyph::is_space) { end += 1; @@ -602,7 +665,10 @@ pub(super) fn break_line( ink += cluster_ink; back += cluster_back; let last = &g[cluster_end - 1]; - if last.break_after() && last.len > 0 && kinsoku_allows(g, cluster_end - 1, kinsoku) && !splits_no_break(g, cluster_end) { + // Hanging punctuation that would hang alone where it overflows may end the line where it + // fits too: a custom set's may be a character no other rule breaks after. + let hang_break = burasagari != Burasagari::None && cluster_end == j + 1 && hangs(last, kinsoku); + if (last.break_after() || hang_break) && last.len > 0 && kinsoku_allows(g, cluster_end - 1, kinsoku) && !splits_no_break(g, cluster_end) { // Once the line holds a tab, whether a break fits as drawn is settled when the line ends. let hyphenated = last.is_soft_hyphen(); if !hyphenated || (tabbed && fits.is_some()) || x + hyphen_glyph(last).adv <= width + EPS { @@ -677,11 +743,12 @@ pub(super) fn break_line( } /// Can glyph `g` hang outside the line (burasagari)? An East Asian comma or full stop, full width -/// (、。,.) or half width (、。); not a closing bracket, nor Latin punctuation (Latin text keeps -/// its line breaks and composer). Never an inline graphic (U+FFFC), nor a character of a -/// tate-chu-yoko or warichu block. -pub(super) fn hangs(g: &SGlyph) -> bool { - g.inline.is_none() && matches!(g.ch, '、' | '。' | ',' | '.' | '、' | '。') && g.tcy.is_none() && g.wari.is_none() +/// (、。,.) or half width (、。), or with a custom set a character of its Hanging Punctuation +/// ([`KinsokuRules::hangs`]); with the built-in sets not a closing bracket, nor Latin punctuation +/// (Latin text keeps its line breaks and composer). Never an inline graphic (U+FFFC), nor a +/// character of a tate-chu-yoko or warichu block. +pub(super) fn hangs(g: &SGlyph, kinsoku: KinsokuRules<'_>) -> bool { + g.inline.is_none() && kinsoku.hangs(g.ch) && g.tcy.is_none() && g.wari.is_none() } /// Optical Margin Alignment: the share of glyph `g`'s advance that hangs outside the margin when @@ -771,7 +838,7 @@ fn line_end_credit(g: &[SGlyph], line_end: &[f64], end: usize) -> f64 { /// May [`break_line`] end a line after glyph `end - 1` (and the spaces after it)? At the paragraph's /// end or a forced line break, and where it records a break without a hyphen. -fn may_end_after(g: &[SGlyph], end: usize, kinsoku: Kinsoku) -> bool { +fn may_end_after(g: &[SGlyph], end: usize, kinsoku: KinsokuRules<'_>) -> bool { let mut e = end; while g.get(e).is_some_and(SGlyph::is_space) { e += 1; @@ -791,20 +858,25 @@ fn splits_no_break(g: &[SGlyph], end: usize) -> bool { /// Does kinsoku allow a line break after glyph `j`? Not after an opening bracket, nor before a /// closing one, a comma, a full stop, a small kana… (the character is pushed to the next line -/// with the one before it). -fn kinsoku_allows(g: &[SGlyph], j: usize, kinsoku: Kinsoku) -> bool { - g.get(j).is_some_and(|gl| kinsoku_between(gl.ch, g.get(j + 1).map(|n| n.ch), kinsoku)) +/// with the one before it). A line that breaks after spaces is drawn without them, so the +/// character before them is the one that ends it: up to [`KINSOKU_SPACES_BACK`] spaces are looked +/// past, and after a longer run of spaces the space itself counts. +fn kinsoku_allows(g: &[SGlyph], j: usize, kinsoku: KinsokuRules<'_>) -> bool { + let Some(gl) = g.get(j) else { return false }; + let before = if gl.is_space() { g[..j].iter().rev().take(KINSOKU_SPACES_BACK).find(|h| !h.is_space()).map_or(gl.ch, |h| h.ch) } else { gl.ch }; + kinsoku_between(before, g.get(j + 1).map(|n| n.ch), kinsoku) } +/// The most spaces [`kinsoku_allows`] looks past for the character that ends a line, so a long run +/// of spaces is not read again at each of its breaks. +const KINSOKU_SPACES_BACK: usize = 64; + /// Kinsoku for a break between `before` and `after` (none: the end of the paragraph): Hard keeps /// every character of the set off the line start and end, Soft lets 々, ー and small kana start a -/// line, None allows the break. -fn kinsoku_between(before: char, after: Option, kinsoku: Kinsoku) -> bool { - match kinsoku { - Kinsoku::None => true, - Kinsoku::Hard => !no_line_end(before) && after.is_none_or(|c| !no_line_start(c)), - Kinsoku::Soft => !no_line_end(before) && after.is_none_or(|c| !no_line_start(c) || soft_line_start(c)), - } +/// line, a custom set keeps its own characters off them ([`KinsokuRules`]), and None allows the +/// break. +fn kinsoku_between(before: char, after: Option, kinsoku: KinsokuRules<'_>) -> bool { + !kinsoku.cannot_end(before) && after.is_none_or(|c| !kinsoku.cannot_start(c)) } /// The share of an em by which a push-in ([`push_in`]) may close each gap next to a CJK character @@ -839,13 +911,13 @@ fn push_in( x: f64, width: f64, pushed_out: Option, - kinsoku: Kinsoku, + kinsoku: KinsokuRules<'_>, kinsoku_type: KinsokuShoriType, hanging: bool, vertical: bool, line_end: &[f64], ) -> Option { - if kinsoku == Kinsoku::None || kinsoku_type == KinsokuShoriType::PushOutOnly { + if kinsoku.is_none() || kinsoku_type == KinsokuShoriType::PushOutOnly { return None; } let before = g.get(j.checked_sub(1)?)?; @@ -949,13 +1021,30 @@ pub(super) fn squeeze_em(g: &SGlyph, vertical: bool) -> f64 { #[cfg(test)] #[test] fn kinsoku_keeps_closing_marks_off_line_starts_and_opening_ones_off_line_ends() { + let hard = KinsokuRules::BuiltIn(Kinsoku::Hard); for (a, b) in [('字', '。'), ('弧', '」'), ('」', '、'), ('ャ', 'ー'), ('カ', 'ッ'), ('「', 'か'), ('(', '雅')] { - assert!(!kinsoku_between(a, Some(b), Kinsoku::Hard), "{a}{b}"); + assert!(!kinsoku_between(a, Some(b), hard), "{a}{b}"); } for (a, b) in [('。', '雅'), ('」', 'は'), ('字', '「'), ('の', '演')] { - assert!(kinsoku_between(a, Some(b), Kinsoku::Hard), "{a}{b}"); + assert!(kinsoku_between(a, Some(b), hard), "{a}{b}"); } - assert!(kinsoku_between('。', None, Kinsoku::Hard)); + assert!(kinsoku_between('。', None, hard)); +} + +/// A custom set keeps its own characters off a line's ends, and nothing else: here 字 may not +/// start a line and 弧 may not end one, while 。 and 「 may. +#[cfg(test)] +#[test] +fn a_custom_kinsoku_set_keeps_its_own_characters_off_line_ends() { + let mut set = vectorcraft_doc::KinsokuSet { name: "Custom".into(), cannot_start: vec!['字'], cannot_end: vec!['弧'], ..Default::default() }; + set.normalize(); + let custom = KinsokuRules::Custom(&set); + assert!(!kinsoku_between('の', Some('字'), custom)); + assert!(!kinsoku_between('弧', Some('の'), custom)); + for (a, b) in [('字', '。'), ('「', 'か'), ('字', 'の')] { + assert!(kinsoku_between(a, Some(b), custom), "{a}{b}"); + } + assert!(!custom.is_none()); } /// Soft kinsoku lets 々, ー and small kana (JLREQ cl-09's 々, cl-10, cl-11) start a line and keeps @@ -963,13 +1052,14 @@ fn kinsoku_keeps_closing_marks_off_line_starts_and_opening_ones_off_line_ends() #[cfg(test)] #[test] fn soft_kinsoku_lets_small_kana_and_the_prolonged_sound_mark_start_a_line() { + let [none, hard, soft] = [Kinsoku::None, Kinsoku::Hard, Kinsoku::Soft].map(KinsokuRules::BuiltIn); for (a, b) in [('ャ', 'ー'), ('カ', 'ッ'), ('時', '々'), ('ト', 'ㇰ'), ('か', 'ゃ')] { - assert!(!kinsoku_between(a, Some(b), Kinsoku::Hard), "{a}{b}"); - assert!(kinsoku_between(a, Some(b), Kinsoku::Soft), "{a}{b}"); + assert!(!kinsoku_between(a, Some(b), hard), "{a}{b}"); + assert!(kinsoku_between(a, Some(b), soft), "{a}{b}"); } for (a, b) in [('字', '。'), ('弧', '」'), ('「', 'か'), ('カ', 'ッ'), ('カ', 'ー'), ('字', 'ゝ')] { - assert!(!kinsoku_between(a, Some(b), Kinsoku::Soft), "{a}{b}"); - assert!(kinsoku_between(a, Some(b), Kinsoku::None), "{a}{b}"); + assert!(!kinsoku_between(a, Some(b), soft), "{a}{b}"); + assert!(kinsoku_between(a, Some(b), none), "{a}{b}"); } } @@ -1017,7 +1107,13 @@ fn word_hyphen_breaks(text: &str, g: &[SGlyph], ws: usize, we: usize, opts: &Hyp /// paragraph's Hyphenation options) when it is given. No break comes before a space: a line that /// may end after a dash, a Thai word or a space ends after the spaces that follow it, as in /// [`break_line`]. -pub(super) fn candidates(text: &str, g: &[SGlyph], hyphenate: Option<&HyphenationOptions>, kinsoku: Kinsoku) -> Vec { +pub(super) fn candidates<'k>( + text: &str, + g: &[SGlyph], + hyphenate: Option<&HyphenationOptions>, + kinsoku: impl Into>, +) -> Vec { + let kinsoku = kinsoku.into(); let mut v = vec![]; let mut ws = 0; for (j, gl) in g.iter().enumerate() { diff --git a/crates/text/src/layout/flow.rs b/crates/text/src/layout/flow.rs index 36881e20d8..856ed12229 100644 --- a/crates/text/src/layout/flow.rs +++ b/crates/text/src/layout/flow.rs @@ -1,25 +1,32 @@ use super::bidi::{is_rtl, para_bidi_with, visual_order}; use super::breaking::{ - Metrics, PUSH_IN_SQUEEZE, Pen, break_line, candidates, drawn_after_tab, drawn_width, hangs, leader_outline, optical_hangs, optical_hangs_rtl, - optical_punct, optical_share, roman_share, squeeze_em, tab_advance, word_width, + KinsokuRules, Metrics, PUSH_IN_SQUEEZE, Pen, break_line, candidates, drawn_after_tab, drawn_width, hangs, leader_outline, optical_hangs, + optical_hangs_rtl, optical_punct, optical_share, roman_share, squeeze_em, tab_advance, word_width, }; use super::region::Region; use super::vertical::{ EM_CENTER, MojikumiRules, align_shift, compress_punctuation, dot_quarter, glyph_em, halve_punctuation, punct_half, space_japanese_and_latin, }; use super::{ - Affine, BidiInfo, Burasagari, CharStyle, Ctx, EPS, Flex, Justify, Kinsoku, KinsokuShoriType, LeadingModel, LineFit, LineInfo, ListMarker, - ParaStyle, Params, Point, Punct, Range, SGlyph, SingleWordJustify, TextObject, apply_desired, cap_x_heights, compose, fit_line, hyphen_glyph, - is_cjk, is_word_space, kashida, mark_word_ends, no_line_end, no_line_start, style_metrics, + Affine, BidiInfo, Burasagari, CharStyle, Ctx, EPS, Flex, Justify, KinsokuShoriType, LeadingModel, LineFit, LineInfo, ListMarker, ParaStyle, + Params, Point, Punct, Range, SGlyph, SingleWordJustify, TextObject, apply_desired, cap_x_heights, compose, fit_line, hyphen_glyph, is_cjk, + is_word_space, kashida, mark_word_ends, style_metrics, }; use crate::justify::is_format_control; -use crate::shape::{keep_inseparable_pairs, keep_korean_words, repeat_base, repeated_char, shape_range}; +use crate::shape::{keep_inseparable_pairs, keep_inseparable_sequences, keep_korean_words, repeat_base, repeated_char, shape_range}; use std::cell::Cell; /// Does paragraph `para` push characters in (Kinsoku Shori Type Push In First or Push Out First, /// with kinsoku on)? fn pushes_in(para: &ParaStyle) -> bool { - para.kinsoku != Kinsoku::None && para.kinsoku_type != KinsokuShoriType::PushOutOnly + !KinsokuRules::of(para).is_none() && para.kinsoku_type != KinsokuShoriType::PushOutOnly +} + +/// May paragraph `para` push one of glyphs `sg` in onto a line: does it push characters in, and +/// hold a character its kinsoku rules keep off a line's start or end? +pub(super) fn may_push_in(para: &ParaStyle, sg: &[SGlyph]) -> bool { + let kinsoku = KinsokuRules::of(para); + pushes_in(para) && sg.iter().any(|g| kinsoku.cannot_start(g.ch) || kinsoku.cannot_end(g.ch)) } /// Paragraphs longer than this (glyphs) are always broken line by line. @@ -55,9 +62,10 @@ fn compose_para( let composer = cx.opts.composer.unwrap_or(para.composer); // A paragraph whose commas or full stops may hang is composed line by line (as the Japanese // single-line composer does). - let may_hang = para.burasagari != Burasagari::None && sg.iter().any(hangs); + let kinsoku = KinsokuRules::of(para); + let may_hang = para.burasagari != Burasagari::None && sg.iter().any(|g| hangs(g, kinsoku)); // So is a paragraph that may push characters kinsoku keeps off a line's ends in onto a line. - let may_push_in = pushes_in(para) && sg.iter().any(|g| no_line_start(g.ch) || no_line_end(g.ch)); + let may_push_in = may_push_in(para, sg); // A tab's width depends on where it falls in its line, which the composer's fixed glyph widths // can't follow: such a paragraph is broken line by line ([`break_line`] measures its tabs). // The tab of a list marker is on the first line, with the marker, and has a fixed width. @@ -100,7 +108,7 @@ fn compose_para( // Only the first line's first word is known here. Later lines are placed as the composed // lines need: each fits its width, so its first word does too. It is measured as the line // loop measures it, with Mojikumi's narrower start and end. - let word = if first { word_width(sg, 0, line_end, para.kinsoku) - start_credit(0) } else { 0.0 }; + let word = if first { word_width(sg, 0, line_end, kinsoku, para.burasagari) - start_credit(0) } else { 0.0 }; let Some((b, x0, x1, _)) = sim.place(m, ind_l, para.right_indent, word) else { break }; let w = x1 - x0 - ind_l - para.right_indent; widths.push(w); @@ -119,7 +127,7 @@ fn compose_para( let width = |k: usize| widths.get(k).copied().unwrap_or(last); // Lines from `uniform_from` on are interchangeable (same width). let uniform_from = widths.iter().rposition(|&w| (w - last).abs() > EPS).map_or(0, |k| k + 1); - let cands = candidates(cx.text, sg, para.hyphenate.then_some(¶.hyphenation), para.kinsoku); + let cands = candidates(cx.text, sg, para.hyphenate.then_some(¶.hyphenation), kinsoku); let justify_last = para.justify == Justify::JustifyAll; let hyphen_limit = usize::try_from(para.hyphenation.hyphen_limit).unwrap_or(usize::MAX); let params = |tolerance| Params { justify_last, ragged, tolerance, uniform_from, hyphen_limit }; @@ -277,8 +285,12 @@ fn prepare_paragraph<'a, 'text>( keep_korean_words(&mut sg); } // Bunri-Kinshi keeps inseparable pairs on one line, while kinsoku is on. - if para.bunri_kinshi && para.kinsoku != Kinsoku::None { - keep_inseparable_pairs(text, &mut sg); + // A custom set keeps its own inseparable sequences instead. + match KinsokuRules::of(para) { + _ if !para.bunri_kinshi => {} + KinsokuRules::Custom(set) => keep_inseparable_sequences(text, &mut sg, &set.inseparable), + rules if !rules.is_none() => keep_inseparable_pairs(text, &mut sg), + _ => {} } // Japanese composition (the paragraph's Mojikumi set): every punctuation mark set half width, // or consecutive punctuation sharing one half-em space… @@ -442,7 +454,8 @@ fn place_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, context: &mut PlacementC glyph.lead += half; } // The line's first word, as narrow as the line sets it at both ends. - let word = word_width(sg, *i, line_end, para.kinsoku); + let kinsoku = KinsokuRules::of(para); + let word = word_width(sg, *i, line_end, kinsoku, para.burasagari); // A composed line in a frame whose lines are not all as wide is placed at its own tallest // metrics, as the composer placed it (`shaped::Shaped`): its room is the room across its height. let composed_line = composed.as_ref().and_then(|lines| lines.get(*para_line)).is_some_and(|&(end, _)| end > *i); @@ -502,7 +515,7 @@ fn place_flow_line(cx: &mut Ctx<'_>, pen: &mut Pen<'_>, context: &mut PlacementC // A right-to-left paragraph draws a burasagari mark inside its line // ([`prepare_line_geometry`]): the line ends where it fits with the mark. if *rtl { Burasagari::None } else { para.burasagari }, - para.kinsoku, + kinsoku, ty, *hanging, cx.vertical, @@ -782,7 +795,7 @@ fn prepare_line_geometry(cx: &Ctx<'_>, t: &TextObject, paragraph: &ParagraphData let hang = (paragraph.regions.is_some() && !paragraph.rtl && hyphen.is_none() && trimmed > index + 1) .then(|| sg.get(trimmed - 1)) .flatten() - .filter(|g| hangs(g)) + .filter(|g| hangs(g, KinsokuRules::of(para))) .map(|g| g.adv - end_trim) .filter(|_| match para.burasagari { Burasagari::None => false, diff --git a/crates/text/src/layout/shaped.rs b/crates/text/src/layout/shaped.rs index 61c28b1465..86caea418f 100644 --- a/crates/text/src/layout/shaped.rs +++ b/crates/text/src/layout/shaped.rs @@ -15,7 +15,7 @@ use std::cell::Cell; use std::collections::HashMap; use std::rc::Rc; -use super::breaking::{Metrics, Pen, word_width}; +use super::breaking::{KinsokuRules, Metrics, Pen, word_width}; use super::flow::line_indents; use super::{ParaStyle, SGlyph}; use crate::composer::{Exhausted, Measure}; @@ -278,7 +278,7 @@ fn past_end<'r>(p: &Para<'_>, start: &Start<'r>) -> Option> { /// frame's end ([`past_end`]) when no frame cell has room for it. fn place<'r>(p: &Para<'_>, start: &Start<'r>, m: Metrics) -> Result>, Exhausted> { let (ind_l, ind_r) = line_indents(p.para, start.first, p.mirror); - let word = word_width(p.sg, start.pos, p.line_end, p.para.kinsoku) - (p.start_credit)(start.pos); + let word = word_width(p.sg, start.pos, p.line_end, KinsokuRules::of(p.para), p.para.burasagari) - (p.start_credit)(start.pos); let mut pen = start.pen.clone(); loop { match pen.place(m, ind_l, ind_r, word) { diff --git a/crates/text/src/layout/wrapping_tests.rs b/crates/text/src/layout/wrapping_tests.rs index c7d8ff8a4b..96ccc3e5c7 100644 --- a/crates/text/src/layout/wrapping_tests.rs +++ b/crates/text/src/layout/wrapping_tests.rs @@ -300,12 +300,12 @@ fn word_width_measures_across_a_soft_hyphen_inside_a_no_break_run() { for g in &mut glyphs { g.sx = 0.001; } - let plain = breaking::word_width(&glyphs, 0, &[], Kinsoku::None); + let plain = breaking::word_width(&glyphs, 0, &[], Kinsoku::None, Burasagari::None); assert!(plain < 30.0, "without the mark the word ends at the soft hyphen: {plain}"); for g in &mut glyphs { g.no_break = true; } - let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None); + let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None, Burasagari::None); assert!((marked - 30.0).abs() < 1e-9, "the marked run is measured whole: {marked}"); } @@ -317,7 +317,7 @@ fn word_width_stops_at_a_forced_line_break() { for g in &mut glyphs { g.no_break = true; } - let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None); + let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None, Burasagari::None); assert!((marked - 10.0).abs() < 1e-9, "the marked run ends at the forced line break: {marked}"); let mut glyphs = synthetic_glyphs(&[(0, 1, 10.0, 'A'), (1, 2, 0.0, '\u{00ad}'), (3, 3, 5.0, '\u{2028}'), (6, 1, 10.0, 'B')]); @@ -325,12 +325,12 @@ fn word_width_stops_at_a_forced_line_break() { for g in &mut glyphs { g.sx = 0.001; } - let plain = breaking::word_width(&glyphs, 0, &[], Kinsoku::None); + let plain = breaking::word_width(&glyphs, 0, &[], Kinsoku::None, Burasagari::None); assert!((plain - 10.0).abs() < 1e-9, "no hyphen before the forced line break: {plain}"); for g in &mut glyphs { g.no_break = true; } - let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None); + let marked = breaking::word_width(&glyphs, 0, &[], Kinsoku::None, Burasagari::None); assert!((marked - 10.0).abs() < 1e-9, "the marked run ends at the forced line break: {marked}"); } @@ -1342,8 +1342,8 @@ fn korean_words_break_at_spaces_unless_line_break_anywhere() { let cands = candidates(text, &off, None, Kinsoku::Hard); assert_eq!(compose(&off, &|_| 50.0, &|_| 0.0, &|_| 0.0, &cands, &[], ¶ms), Some(vec![(4, false), (7, false)])); // The first word is measured whole, as the line loop measures it. - assert_eq!(breaking::word_width(&off, 0, &[], Kinsoku::Hard), 30.0); - assert_eq!(breaking::word_width(&korean(text, true), 0, &[], Kinsoku::Hard), 10.0); + assert_eq!(breaking::word_width(&off, 0, &[], Kinsoku::Hard, Burasagari::None), 30.0); + assert_eq!(breaking::word_width(&korean(text, true), 0, &[], Kinsoku::Hard, Burasagari::None), 10.0); // A word wider than the line still breaks, at the syllable that overflows. assert_eq!(greedy(&korean("가나다라마바", false), 25.0), 2); // A soft return still ends the line. @@ -1449,8 +1449,8 @@ fn bunri_kinshi_keeps_jlreq_pairs_in_both_composers() { }; assert_eq!(greedy(&pairs(text, false), 35.0), 3, "off: the line ends between the dashes"); assert_eq!(greedy(&pairs(text, true), 35.0), 2, "on: both dashes go to the next line"); - assert_eq!(breaking::word_width(&pairs("——あ", true), 0, &[], Kinsoku::Hard), 20.0); - assert_eq!(breaking::word_width(&pairs("——あ", false), 0, &[], Kinsoku::Hard), 10.0); + assert_eq!(breaking::word_width(&pairs("——あ", true), 0, &[], Kinsoku::Hard, Burasagari::None), 20.0); + assert_eq!(breaking::word_width(&pairs("——あ", false), 0, &[], Kinsoku::Hard, Burasagari::None), 10.0); let params = Params { justify_last: false, ragged: true, tolerance: f64::INFINITY, uniform_from: 0, hyphen_limit: 0 }; let on = pairs("あい——う", true); let cands = candidates("あい——う", &on, None, Kinsoku::Hard); @@ -1500,6 +1500,241 @@ fn bunri_kinshi_progresses_with_an_overlong_pair_and_no_break() { assert_eq!(line(text, &pairs(text, true), 0, 46.5, Kinsoku::Hard, PushInFirst), 3); } +/// A custom Kinsoku Shori set (Type › Kinsoku Shori Settings…) with these categories. +fn custom_set(cannot_start: &str, cannot_end: &str, hanging: &str, inseparable: &[&str]) -> vectorcraft_doc::KinsokuSet { + let mut set = vectorcraft_doc::KinsokuSet { + name: "Custom".into(), + cannot_start: cannot_start.chars().collect(), + cannot_end: cannot_end.chars().collect(), + hanging: hanging.chars().collect(), + inseparable: inseparable.iter().map(|s| s.to_string()).collect(), + }; + set.normalize(); + set +} + +/// New Set from Hard or Soft starts with their characters: a custom set made from either breaks +/// every line where it does, in both composers, with every Kinsoku Shori Type and with and without +/// Burasagari, and keeps the same inseparable pairs with Bunri-Kinshi. One made from None is empty. +#[test] +fn a_set_made_from_hard_or_soft_breaks_lines_as_they_do() { + use KinsokuShoriType::{PushInFirst, PushOutFirst, PushOutOnly}; + let texts = ["一二三四五六七八九十一二三四五」六", "あカッー々ャ「か」、。(雅)", "あい——う〳〵え……カッー", "一二三四(五六)ab\u{201c}c\u{201d}。"]; + for base in [Kinsoku::Hard, Kinsoku::Soft] { + let set = crate::shape::kinsoku_set_from(base, "From"); + let custom = breaking::KinsokuRules::Custom(&set); + for text in texts { + let mut built_in = full_width(text); + crate::shape::keep_inseparable_pairs(text, &mut built_in); + let mut own = full_width(text); + crate::shape::keep_inseparable_sequences(text, &mut own, &set.inseparable); + let kept = |g: &[SGlyph]| g.iter().map(|g| g.keeps_next).collect::>(); + assert_eq!(kept(&built_in), kept(&own), "{base:?} {text}"); + let ends = |c: Vec| c.iter().map(|b| b.end).collect::>(); + assert_eq!(ends(candidates(text, &built_in, None, base)), ends(candidates(text, &own, None, custom)), "{base:?} {text}"); + for ty in [PushInFirst, PushOutFirst, PushOutOnly] { + for burasagari in [Burasagari::None, Burasagari::Standard] { + for width in (15..=160).step_by(5).map(f64::from) { + let at = |g: &[SGlyph], k: breaking::KinsokuRules<'_>| { + break_line(text, g, 0, width, &[], 0.0, None, burasagari, k, ty, false, false, &[], None).0 + }; + assert_eq!(at(&built_in, base.into()), at(&own, custom), "{base:?} {ty:?} {burasagari:?} {width} {text}"); + } + } + } + } + } + let empty = crate::shape::kinsoku_set_from(Kinsoku::None, "Empty"); + assert!(empty.cannot_start.is_empty() && empty.cannot_end.is_empty() && empty.hanging.is_empty() && empty.inseparable.is_empty()); +} + +/// A custom set keeps its own Cannot Start Line characters off a line's start and its Cannot End +/// Line characters off its end, and lets every other character start or end one: here 四 never +/// starts a line and 三 never ends one, while 」, which Hard keeps off a line's start, may start +/// one with an empty set. +#[test] +fn a_custom_set_keeps_its_own_characters_off_line_ends() { + use KinsokuShoriType::PushOutOnly; + let end = |text: &str, width: f64, k: breaking::KinsokuRules<'_>| { + break_line(text, &full_width(text), 0, width, &[], 0.0, None, Burasagari::None, k, PushOutOnly, false, false, &[], None).0 + }; + let text = "一二三四五六"; + let start = custom_set("四", "", "", &[]); + let finish = custom_set("", "三", "", &[]); + let empty = custom_set("", "", "", &[]); + assert_eq!(end(text, 35.0, Kinsoku::Hard.into()), 3); + assert_eq!(end(text, 35.0, breaking::KinsokuRules::Custom(&start)), 2, "四 does not start the next line"); + assert_eq!(end(text, 35.0, breaking::KinsokuRules::Custom(&finish)), 2, "三 does not end the line"); + let bracket = "一二三」四"; + assert_eq!(end(bracket, 35.0, Kinsoku::Hard.into()), 2, "Hard keeps 」 off the next line's start"); + assert_eq!(end(bracket, 35.0, breaking::KinsokuRules::Custom(&empty)), 3, "the empty set lets 」 start it"); + // A space after 三 is not drawn at the end of the line, so a break after it would still end + // the line with 三. + let spaced = "一二三 四"; + assert_eq!(end(spaced, 35.0, breaking::KinsokuRules::Custom(&finish)), 2, "三 does not end the line before a space"); + assert_eq!(end(spaced, 35.0, breaking::KinsokuRules::Custom(&empty)), 4); + let ends = candidates(text, &full_width(text), None, breaking::KinsokuRules::Custom(&start)).iter().map(|b| b.end).collect::>(); + assert_eq!(ends, [1, 2, 4, 5]); +} + +/// The least room a word needs ([`breaking::word_width`]) runs past spaces where kinsoku allows no +/// break after them, to the first break [`break_line`] may take: after 「 or a custom set's 三 with +/// spaces after it, and before a 」 that follows a space. Where the break after the space is +/// allowed, the word still ends before the space. +#[test] +fn word_width_runs_past_spaces_kinsoku_does_not_break_after() { + use KinsokuShoriType::PushOutOnly; + let finish = custom_set("", "三", "", &[]); + let empty = custom_set("", "", "", &[]); + for (text, k, word) in [ + ("「 四五", breaking::KinsokuRules::from(Kinsoku::Hard), 30.0), + ("「 四五", Kinsoku::Hard.into(), 40.0), + ("a 」二", Kinsoku::Hard.into(), 30.0), + ("三 四五", breaking::KinsokuRules::Custom(&finish), 30.0), + ("三 四五", breaking::KinsokuRules::Custom(&empty), 10.0), + ("一 二三", Kinsoku::Hard.into(), 10.0), + ] { + let g = full_width(text); + assert_eq!(breaking::word_width(&g, 0, &[], k, Burasagari::None), word, "{text}"); + // In a measure that wide, break_line's first line is that word, drawn without the spaces + // at its end. + let mut end = break_line(text, &g, 0, word, &[], 0.0, None, Burasagari::None, k, PushOutOnly, false, false, &[], None).0; + while end > 0 && g[end - 1].is_space() { + end -= 1; + } + assert_eq!(g[..end].iter().map(|h| h.adv).sum::(), word, "{text}"); + } + // A No Break run of spaces after 「 longer than the glyphs a word is measured over stops the + // measure there. + let long: String = std::iter::once('「').chain(std::iter::repeat_n(' ', 2000)).chain(['四']).collect(); + let mut g = full_width(&long); + for h in g.iter_mut().skip(1) { + h.no_break = true; + } + assert_eq!(breaking::word_width(&g, 0, &[], Kinsoku::Hard, Burasagari::None), 10240.0); +} + +/// Soft and a set made from it choose the same composer: small kana and the prolonged sound mark, +/// which Soft lets start a line, do not send a paragraph that pushes in to the single-line +/// composer with either, while Hard, which keeps them off a line's start, does. +#[test] +fn soft_and_a_set_made_from_it_push_in_the_same_characters() { + use KinsokuShoriType::{PushInFirst, PushOutOnly}; + let glyphs = full_width("あゃいーう"); + let para = |kinsoku: Kinsoku, own: bool, kinsoku_type: KinsokuShoriType| ParaStyle { + kinsoku, + kinsoku_set: own.then(|| Arc::new(crate::shape::kinsoku_set_from(kinsoku, "From"))), + kinsoku_type, + ..ParaStyle::default() + }; + assert!(!flow::may_push_in(¶(Kinsoku::Soft, false, PushInFirst), &glyphs), "built-in Soft"); + assert!(!flow::may_push_in(¶(Kinsoku::Soft, true, PushInFirst), &glyphs), "a set made from Soft"); + assert!(flow::may_push_in(¶(Kinsoku::Hard, false, PushInFirst), &glyphs), "built-in Hard"); + assert!(flow::may_push_in(¶(Kinsoku::Hard, true, PushInFirst), &glyphs), "a set made from Hard"); + assert!(!flow::may_push_in(¶(Kinsoku::Hard, false, PushOutOnly), &glyphs), "Push Out Only"); + let bracket = full_width("あい」う"); + assert!(flow::may_push_in(¶(Kinsoku::Soft, false, PushInFirst), &bracket), "Soft keeps 」 off a line's start"); +} + +/// With Burasagari, a custom set hangs its own Hanging Punctuation and not the comma and full stop +/// the built-in sets hang: 、 hangs outside a full line with Hard and with a set that lists it; with +/// a set that lists only ! it starts the next line, while ! hangs. +#[test] +fn a_custom_set_hangs_its_own_hanging_punctuation() { + use KinsokuShoriType::PushOutOnly; + let end = |text: &str, k: breaking::KinsokuRules<'_>| { + break_line(text, &full_width(text), 0, 30.0, &[], 0.0, None, Burasagari::Standard, k, PushOutOnly, false, false, &[], None).0 + }; + let comma = custom_set("", "", "、", &[]); + let bang = custom_set("", "", "!", &[]); + assert_eq!(end("一二三、四", Kinsoku::Hard.into()), 4); + assert_eq!(end("一二三、四", breaking::KinsokuRules::Custom(&comma)), 4, "、 hangs"); + assert_eq!(end("一二三、四", breaking::KinsokuRules::Custom(&bang)), 3, "、 does not hang"); + assert_eq!(end("一二三!四", breaking::KinsokuRules::Custom(&bang)), 4, "! hangs"); + // In a wider line where ! fits, the line still ends after it. + let text = "一二三!四"; + let wide = |b: Burasagari| { + break_line(text, &full_width(text), 0, 40.0, &[], 0.0, None, b, breaking::KinsokuRules::Custom(&bang), PushOutOnly, false, false, &[], None).0 + }; + assert_eq!(wide(Burasagari::Standard), 4, "! fits and ends the line"); + assert_eq!(wide(Burasagari::None), 3, "without Burasagari ! does not hang, and no line ends after it"); + // The first word, which places a line in a frame of uneven width, ends after ! as the line may. + let word = |b: Burasagari| breaking::word_width(&full_width("AB!CD"), 0, &[], breaking::KinsokuRules::Custom(&bang), b); + assert_eq!(word(Burasagari::Standard), 30.0); + assert_eq!(word(Burasagari::None), 50.0); + // A hanging character that starts an inseparable sequence kept with Bunri-Kinshi does not hang + // the rest of the sequence with it: the sequence goes to the next line. + let joined = custom_set("", "", "!", &["!あ"]); + let text = "一二三!あい"; + let mut g = full_width(text); + crate::shape::keep_inseparable_sequences(text, &mut g, &joined.inseparable); + let rules = breaking::KinsokuRules::Custom(&joined); + assert_eq!(break_line(text, &g, 0, 30.0, &[], 0.0, None, Burasagari::Standard, rules, PushOutOnly, false, false, &[], None).0, 3); + // A hanging character drawn with two glyphs does not hang: the line's geometry hangs only one + // glyph, so the other would stay past the measure. 三 goes to the next line with it. + let text = "一二三、四"; + let mut g = full_width(text); + g[3].adv = 5.0; + g.insert(3, g[3].clone()); + assert_eq!(break_line(text, &g, 0, 30.0, &[], 0.0, None, Burasagari::Standard, Kinsoku::Hard, PushOutOnly, false, false, &[], None).0, 2); + let g = full_width("、!"); + assert!(breaking::hangs(&g[1], breaking::KinsokuRules::Custom(&bang)) && !breaking::hangs(&g[0], breaking::KinsokuRules::Custom(&bang))); +} + +/// Bunri-Kinshi with a custom set: a line never breaks inside one of its inseparable sequences, +/// which may be longer than a pair and may overlap, and the built-in pairs are kept only when the +/// set lists them. +#[test] +fn a_custom_set_keeps_its_inseparable_sequences_on_one_line() { + let marked = |text: &str, sequences: &[&str]| { + let mut g = full_width(text); + crate::shape::keep_inseparable_sequences(text, &mut g, &sequences.iter().map(|s| s.to_string()).collect::>()); + g.iter().map(|g| g.keeps_next).collect::>() + }; + assert_eq!(marked("かあいうえ", &["あいう"]), [false, true, true, false, false]); + assert_eq!(marked("あいうえお", &["あい", "いう"]), [true, true, false, false, false], "overlapping sequences chain"); + assert_eq!(marked("あ——い", &["あい"]), [false; 4], "the built-in pairs are not kept by a set without them"); + assert_eq!(marked("", &["あい"]), Vec::::new()); + assert_eq!(marked("あいうえお", &["あい", "あいうえ"]), [true, true, true, false, false], "the longer of two sequences that start alike"); + assert_eq!(marked("あいう", &["あい", "あいか"]), [true, false, false], "the shorter where only it is found"); + // A set at the category limit whose sequences all start with one character. + let many: Vec = (0..2047u32).filter_map(|k| char::from_u32(0x4E00 + k)).map(|c| ['あ', c].iter().collect()).collect(); + let many: Vec<&str> = many.iter().map(String::as_str).chain(["あい"]).collect(); + assert_eq!(marked("あいあ一う", &many), [true, false, true, false, false]); + let text = "かあいうえ"; + let set = custom_set("", "", "", &["あいう"]); + let mut g = full_width(text); + crate::shape::keep_inseparable_sequences(text, &mut g, &set.inseparable); + let ends = candidates(text, &g, None, breaking::KinsokuRules::Custom(&set)).iter().map(|b| b.end).collect::>(); + assert_eq!(ends, [1, 4]); +} + +/// Bunri-Kinshi with a custom set compares at most 15 texts with the set's sequences for each +/// character of a paragraph, however many sequences start with one character: 2048 sequences of +/// 2 characters cost one lookup at each place, 256 of 16 characters cost 15, and a sequence longer +/// than a set holds is not looked for. +#[test] +fn inseparable_sequences_cost_a_bounded_number_of_lookups() { + let lookups = |text: &str, sequences: &[String]| { + let mut g = full_width(text); + crate::shape::SEQUENCE_LOOKUPS.with(|n| n.set(0)); + crate::shape::keep_inseparable_sequences(text, &mut g, sequences); + (crate::shape::SEQUENCE_LOOKUPS.with(std::cell::Cell::get), g.iter().filter(|g| g.keeps_next).count()) + }; + // A place n characters from the paragraph's end looks up min(n, 16) - 1 texts. + let cost = |chars: usize, longest: usize| (1..=chars).map(|n| n.min(longest) - 1).sum::(); + let text = "あ".repeat(1000); + let pairs: Vec = (0..2048u32).filter_map(|k| char::from_u32(0x4E00 + k)).map(|c| ['あ', c].iter().collect()).collect(); + assert_eq!(lookups(&text, &pairs), (999, 0)); + let long: Vec = (0..256u32).filter_map(|k| char::from_u32(0x4E00 + k)).map(|c| format!("{}{c}", "あ".repeat(15))).collect(); + assert_eq!(lookups(&text, &long), (cost(1000, 16), 0)); + assert!(cost(1000, 16) <= 1000 * 15); + let mut found = long.clone(); + found.push("あ".repeat(16)); + assert_eq!(lookups(&"あ".repeat(16), &found), (cost(16, 16), 15)); + assert_eq!(lookups(&"あ".repeat(17), &["あ".repeat(17)]), (cost(17, 16), 0), "17 characters are never found"); +} + /// Justification adds no gap between two glyphs of one warichu block, whichever of them is drawn /// first: right to left, the block's first glyph (the one that starts it) is drawn after the /// others. Between glyphs of two blocks, the gap stays. diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index f7f5d128ba..7b70b9c5a2 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,11 @@ 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, OutlineFormat, 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}; @@ -54,7 +56,7 @@ pub use svg_glyph::{SvgGlyphReader, set_svg_glyph_reader}; pub use kept::{KeptLayoutsFrame, LayoutStamp, keep_layout, take_kept_layout}; use kurbo::{Affine, BezPath, Point, Rect, Shape, Vec2}; pub use layout::{decorations, drawn, fit_first_line, fit_source_lines, layout, layout_with, scaled}; -pub use shape::{aki_space, inseparable, line_start_space, repeat_base, spacing_scale}; +pub use shape::{aki_space, inseparable, kinsoku_set_from, line_start_space, repeat_base, spacing_scale}; pub use vectorcraft_doc::TextObject; pub use vectorcraft_doc::{AreaFit, FirstBaseline, TextFlow, VerticalAlign}; diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs new file mode 100644 index 0000000000..d7c7be71d6 --- /dev/null +++ b/crates/text/src/retype.rs @@ -0,0 +1,945 @@ +//! 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 mut out = self.all_matches(shape); + out.truncate(MAX_CANDIDATES); + out + } + + /// Every glyph `shape` fits exactly, in every face, in the order of [`RetypeIndex::matches`], + /// which returns the first [`MAX_CANDIDATES`] of them. + pub fn all_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.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)); + } + + /// A glyph that more than [`MAX_CANDIDATES`] faces share: `matches` gives the first + /// [`MAX_CANDIDATES`] fits, and `all_matches` gives the fits in every face. + #[test] + fn all_matches_lists_every_face_a_shape_fits() { + let db = FontDb::with_font_dirs(vec![]); + let copies = MAX_CANDIDATES + 4; + let mut faces = vec![]; + for i in 0..copies { + let (family, postscript) = (format!("Copytest {i:02}"), format!("Copytest{i:02}-Regular")); + assert_eq!(db.add_font(crate::test_fonts::named_copy(false, (&family, "Regular", "Version 1.000", &postscript)).unwrap()), 1); + faces.push(db.face(&family, "Regular").unwrap()); + } + let face = faces[0].clone(); + let shape = Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for('o')); + let keys = std::iter::once(shape_key(&shape).unwrap()).collect(); + let index = RetypeIndex::build(&db, faces, &keys); + let ids = |ms: &[GlyphMatch]| ms.iter().map(|m| m.face.id()).collect::>().len(); + assert_eq!(index.matches(&shape).len(), MAX_CANDIDATES); + assert!(ids(&index.matches(&shape)) < copies); + let all = index.all_matches(&shape); + assert_eq!(ids(&all), copies, "every copy of the font fits the o"); + assert_eq!( + all[..MAX_CANDIDATES].iter().map(|m| m.face.id()).collect::>(), + index.matches(&shape).iter().map(|m| m.face.id()).collect::>() + ); + } +} diff --git a/crates/text/src/shape.rs b/crates/text/src/shape.rs index c9ae809da5..9dfff9a0d6 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; @@ -438,6 +438,89 @@ pub(crate) fn keep_inseparable_pairs(text: &str, sg: &mut [SGlyph]) { } } +#[cfg(test)] +thread_local! { + /// How many texts [`keep_inseparable_sequences`] has compared with a set's sequences on this + /// thread. + pub(crate) static SEQUENCE_LOOKUPS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Bunri-Kinshi with a custom Kinsoku Shori set: as [`keep_inseparable_pairs`], for the set's +/// inseparable `sequences` (each [`vectorcraft_doc::text::KINSOKU_SEQUENCE`] characters): a line +/// never breaks between two characters of one occurrence of a sequence in the paragraph's text. +/// Occurrences may overlap. The text is read once; at each place that starts a sequence, only the +/// text of each sequence length (at most [`vectorcraft_doc::text::KINSOKU_SEQUENCE`]'s end) is +/// looked up, however many sequences share a first character: at most 15 lookups for each +/// character of the paragraph. A sequence longer than a set can hold is never found. +pub(crate) fn keep_inseparable_sequences(text: &str, sg: &mut [SGlyph], sequences: &[String]) { + let (Some(first), Some(last)) = (sg.iter().map(|g| g.byte).min(), sg.iter().map(|g| g.byte + g.len).max()) else { return }; + let Some(longest) = sequences.iter().map(|s| s.chars().count()).max() else { return }; + let longest = longest.min(*vectorcraft_doc::text::KINSOKU_SEQUENCE.end()); + let known: std::collections::HashSet<&str> = sequences.iter().map(String::as_str).collect(); + let starts: std::collections::HashSet = sequences.iter().filter_map(|s| s.chars().next()).collect(); + let Some(para) = text.get(first..last) else { return }; + // The bytes (of `text`) where a character inside an occurrence starts, after its first. + let mut inside = std::collections::HashSet::new(); + for (at, c) in para.char_indices() { + if !starts.contains(&c) { + continue; + } + let rest = ¶[at..]; + // Every sequence found here is the start of the longest one found here, so that one marks + // the characters of them all. + let mut found = None; + for end in rest.char_indices().take(longest).map(|(k, ch)| k + ch.len_utf8()).skip(1) { + #[cfg(test)] + SEQUENCE_LOOKUPS.with(|n| n.set(n.get() + 1)); + if known.contains(&rest[..end]) { + found = Some(end); + } + } + if let Some(end) = found { + inside.extend(rest[..end].char_indices().skip(1).map(|(k, _)| first + at + k)); + } + } + if inside.is_empty() { + return; + } + for k in 1..sg.len() { + let (a, b) = (&sg[k - 1], &sg[k]); + if a.byte == b.byte || a.inline.is_some() || b.inline.is_some() || a.byte + a.len != b.byte { + continue; + } + if inside.contains(&b.byte) { + sg[k - 1].keeps_next = true; + } + } +} + +/// The characters, hanging punctuation and inseparable sequences of a built-in Kinsoku Set +/// (`base`), as a custom set named `name` holds them: New Set's starting point. A set made from +/// Hard or Soft breaks lines as that set does; one made from None is empty. +pub fn kinsoku_set_from(base: vectorcraft_doc::Kinsoku, name: &str) -> vectorcraft_doc::KinsokuSet { + use vectorcraft_doc::Kinsoku; + let mut set = vectorcraft_doc::KinsokuSet { name: name.to_string(), ..Default::default() }; + if base == Kinsoku::None { + return set; + } + // Every character the built-in sets name is in the Basic Multilingual Plane. + for c in (0..=0xFFFF_u32).filter_map(char::from_u32) { + if no_line_start(c) && !(base == Kinsoku::Soft && soft_line_start(c)) { + set.cannot_start.push(c); + } + if no_line_end(c) { + set.cannot_end.push(c); + } + if crate::layout::is_hanging_punctuation(c) { + set.hanging.push(c); + } + } + let pairs = [('\u{2014}', '\u{2014}'), ('\u{2026}', '\u{2026}'), ('\u{2025}', '\u{2025}'), ('\u{3033}', '\u{3035}'), ('\u{3034}', '\u{3035}')]; + set.inseparable = pairs.iter().filter(|&&(a, b)| inseparable(a, b)).map(|&(a, b)| [a, b].iter().collect()).collect(); + set.normalize(); + set +} + /// Is `a` followed by `b` an inseparable pair that Bunri-Kinshi keeps on one line? VectorCraft's /// set is the pairs W3C JLREQ lists for its class cl-08 (https://www.w3.org/TR/jlreq/#cl-08): two /// em dashes, two horizontal ellipses, two two-dot leaders, and the upper half of a vertical kana @@ -673,7 +756,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 +776,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 +1380,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 +1392,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 +1685,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/three-d/src/lib.rs b/crates/three-d/src/lib.rs index c6b00ed851..c99a437efd 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -12,8 +12,9 @@ pub mod fold; mod solid; mod visibility; pub use solid::{ - Bevel, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, MeshFace, PlanarFace, TOO_COMPLEX_SOLID, View, extrude, extrude_face_map, - extrude_mesh_face, extrude_side_size, inflate, inflate_each, inflate_together, plane, plane_face_map, plane_mesh_face, + Bevel, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, MapCell, MeshFace, PlanarFace, SolidSurface, SurfaceKind, TOO_COMPLEX_SOLID, + View, extrude, extrude_face_map, extrude_mesh_face, extrude_side_size, extrude_surfaces, inflate, inflate_each, inflate_together, plane, + plane_face_map, plane_mesh_face, }; pub use visibility::{VisibleFace, visible_faces}; mod shading; @@ -22,7 +23,7 @@ mod lights; pub use lights::{Light, Lights, MAX_LIGHTS}; mod caps; mod mesh; -pub use mesh::{Mesh, MeshedSolid, extrude_mesh, extrude_meshed, inflate_meshed, inflate_meshes, plane_mesh, revolve_mesh}; +pub use mesh::{Mesh, MeshedSolid, extrude_mesh, extrude_meshed, inflate_meshed, inflate_meshes, plane_mesh, revolve_mesh, revolve_mesh_surface}; mod shadow; pub use shadow::{ MAX_SHADOW_FACES, Shadow, ShadowCaster, ShadowPlane, ShadowPosition, SolidFaces, TOO_COMPLEX_SHADOW, extrude_shadowed, inflate_shadowed, @@ -478,6 +479,15 @@ fn surface_span(sweep: f64, edge: Edge) -> f64 { } } +/// Where the four corners of the quad that the profile's edge from `a` to `b` sweeps in one step +/// about `axis` lie on the side surface ([`SurfaceCell`]), in the quad's order (`a`, `b`, then `b` +/// and `a` one step on): y is `along`, the surface y of each end of the edge, and x is the step's +/// surface angle at each end, `angle`, times the corner's own distance from the axis. +fn surface_corners(a: Point, b: Point, axis: f64, [va, vb]: [f64; 2], [t0, t1]: [f64; 2]) -> [Point; 4] { + let (ra, rb) = ((a.x - axis).abs(), (b.x - axis).abs()); + [Point::new(t0 * ra, va), Point::new(t0 * rb, vb), Point::new(t1 * rb, vb), Point::new(t1 * ra, va)] +} + /// The surface y ([`SurfaceCell`]) of each end of each piece of a contour's profile `profile` /// about `axis`: the length along the profile from its middle, counted from just after the /// pieces that lie on the axis (which sweep no surface and add no length) on a closed contour. @@ -980,7 +990,22 @@ fn revolve_face_limit(o: Revolve) -> usize { /// each turned out of the region `rule` fills. fn revolve_faces(path: &PathData, rule: FillRule, bounds: Rect, options: Revolve, mesh: Option<&mut Vec>) -> Result, String> { let draw = mesh.is_none(); - revolve_sweep(path, rule, bounds, options, draw, mesh).map(|(faces, _)| faces) + revolve_sweep(path, rule, bounds, options, draw, mesh, None).map(|(faces, _)| faces) +} + +/// The faces of Revolve's surface before projection, kept in `faces` as [`revolve_faces`] keeps +/// them, and in `surface` where the corners of each face of the side lie on the side surface +/// ([`SurfaceCell`]), as the drawn faces place them. Only a sweep with [`Revolve::map_surface`] lays +/// out its side; only the longest contour of a compound profile has one. +pub(crate) fn revolve_surface_faces( + path: &PathData, + rule: FillRule, + bounds: Rect, + options: Revolve, + faces: &mut Vec, + surface: &mut SurfaceQuads, +) -> Result<(), String> { + revolve_sweep(path, rule, bounds, options, false, Some(faces), Some(surface)).map(|_| ()) } #[cfg(test)] @@ -1037,11 +1062,19 @@ fn cap_outward(profile: &[Point], index: usize, center_y: f64) -> Option<(Point, /// Keep for a mesh the faces of one contour's profile `s`, which runs round the region it sweeps as /// `turn` says (its holes' walls turned the other way): a quad for each edge at each step, then for /// each end in `caps` (0 the first, 1 the last) the disk, or for a sweep of less than a full turn -/// the sector with its center on the axis. `keep` keeps one face with its outward normal; its -/// error, or an edge with invalid coordinates, stops the faces. -fn keep_profile(at: &Sweeping, s: &Swept, turn: f64, caps: &[usize], mut keep: impl FnMut(Vec, V3) -> Result<(), String>) -> Result<(), String> { +/// the sector with its center on the axis. `keep` keeps one face with its outward normal and, for a +/// quad of the side when `surface` lays it out, where each of its corners lies on the side surface +/// ([`SurfaceCell`]); its error, or an edge with invalid coordinates, stops the faces. +fn keep_profile( + at: &Sweeping, + s: &Swept, + turn: f64, + caps: &[usize], + surface: Option>, + mut keep: impl FnMut(Vec, V3, Option<[Point; 4]>) -> Result<(), String>, +) -> Result<(), String> { let (o, steps) = (at.o, at.steps); - for (pair, hole) in s.points.windows(2).zip(&s.holes) { + for (i, (pair, hole)) in s.points.windows(2).zip(&s.holes).enumerate() { let [a, b] = pair else { continue }; let turn = if *hole { -turn } else { turn }; if ![a.x, a.y, b.x, b.y].iter().all(|v| v.is_finite() && v.abs() <= 1e8) { @@ -1053,7 +1086,9 @@ fn keep_profile(at: &Sweeping, s: &Swept, turn: f64, caps: &[usize], mut keep: i // swept to the middle of the step. let (dr, dy) = ((b.x - a.x) * turn, (b.y - a.y) * turn); let (sin, cos) = (at.sweep * (j as f64 + 0.5) / steps as f64).sin_cos(); - keep(vec![v0, v1, v2, v3], o.rotate(V3(dy * cos, -dr, dy * sin)))?; + // The corners on the side surface, as the drawn faces place them. + let uv = surface.map(|(along, angle)| surface_corners(*a, *b, at.axis, along.get(i).copied().unwrap_or_default(), angle(j))); + keep(vec![v0, v1, v2, v3], o.rotate(V3(dy * cos, -dr, dy * sin)), uv)?; } } for &index in caps { @@ -1064,11 +1099,19 @@ fn keep_profile(at: &Sweeping, s: &Swept, turn: f64, caps: &[usize], mut keep: i } else { cap.insert(0, o.rotate(V3(0.0, end.y - at.center_y, 0.0))); } - keep(cap, o.rotate(V3(0.0, outward, 0.0)))?; + keep(cap, o.rotate(V3(0.0, outward, 0.0)), None)?; } Ok(()) } +/// How a contour's side lies on the side surface ([`SurfaceCell`]): the surface y of each end of +/// each piece of its profile ([`along_profile`]) and the surface angle at each end of a step. +type SurfaceLayout<'a> = (&'a [[f64; 2]], &'a dyn Fn(usize) -> [f64; 2]); + +/// Where the corners of the faces of Revolve's mesh lie on its side surface: the index of a face +/// among the faces kept, and the surface point of each of its four corners, in order. +pub(crate) type SurfaceQuads = Vec<(usize, [Point; 4])>; + /// Twice the signed area of the polygon `ring`. fn ring_area(ring: &[Point]) -> f64 { ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()).map(|(p, q)| p.x * q.y - q.x * p.y).sum() @@ -1325,7 +1368,9 @@ fn lose_mesh(draw: bool, mesh: &mut Option<&mut Vec>, lost: &mut O /// [`revolve`]'s faces when `draw`, and with `mesh` the surface's faces before projection kept /// there from the same sweep, each turned out of the region `rule` fills. While faces are drawn, an /// error keeping faces for the mesh stops only the mesh: the error comes back beside the faces -/// drawn, and `mesh` keeps no more faces. Without `draw` that error is the result. +/// drawn, and `mesh` keeps no more faces. Without `draw` that error is the result. With `surface`, +/// the faces kept of the side of the contour that carries the graphics are listed there with their +/// corners on the side surface ([`revolve_surface_faces`]). fn revolve_sweep( path: &PathData, rule: FillRule, @@ -1333,6 +1378,7 @@ fn revolve_sweep( options: Revolve, draw: bool, mut mesh: Option<&mut Vec>, + mut surface: Option<&mut SurfaceQuads>, ) -> Result<(Vec, Option), String> { #[cfg(test)] REVOLVED.with(|n| n.set(n.get() + 1)); @@ -1536,7 +1582,15 @@ fn revolve_sweep( let turn = prepare(&mut kept); cuts.add(&kept, sp.closed, true); let caps: Vec = rings.iter().enumerate().filter_map(|(i, r)| r.as_ref().map(|_| i)).collect(); - let kept = keep_profile(&at, &kept, turn, &caps, |face, normal| keep(m, face, normal)); + let along = (surface.is_some() && surface_contour == Some(contour)).then(|| along_profile(&kept.points, axis, sp.closed)); + let layout = along.as_deref().map(|along| (along, &surface_angle as &dyn Fn(usize) -> [f64; 2])); + let kept = keep_profile(&at, &kept, turn, &caps, layout, |face, normal, uv| { + keep(m, face, normal)?; + if let (Some(uv), Some(s)) = (uv, surface.as_deref_mut()) { + s.push((m.len() - 1, uv)); + } + Ok(()) + }); if let Err(e) = kept { lose_mesh(draw, &mut mesh, &mut lost, e)?; } @@ -1551,7 +1605,7 @@ fn revolve_sweep( for (i, ((pair, [ta, tb]), hole)) in profile.windows(2).zip(drawn.tangents.iter().copied()).zip(drawn.holes.iter().copied()).enumerate() { let [a, b] = pair else { continue }; let turn = if hole { -turn } else { turn }; - let [va, vb] = along.get(i).copied().unwrap_or_default(); + let ends = along.get(i).copied().unwrap_or_default(); if ![a.x, a.y, b.x, b.y].iter().all(|v| v.is_finite() && v.abs() <= 1e8) { return Err("Revolve profile contains invalid coordinates".into()); } @@ -1561,10 +1615,7 @@ fn revolve_sweep( let last = (i + 2 == profile.len()).then(|| rings.last().and_then(Option::as_ref).and_then(|r| r.arcs.get(j))).flatten(); // Where the corners lie on the unrolled side surface, and whether the face shows // its outside: the edge's outward normal swept to the middle of the step. - // x is the angle times the corner's own distance from the axis. - let [t0, t1] = surface_angle(j); - let (ra, rb) = ((a.x - axis).abs(), (b.x - axis).abs()); - let corners = [Point::new(t0 * ra, va), Point::new(t0 * rb, vb), Point::new(t1 * rb, vb), Point::new(t1 * ra, va)]; + let corners = surface_corners(*a, *b, axis, ends, surface_angle(j)); let on_surface = surface_contour == Some(contour); let outward = { let (dr, dy) = ((b.x - a.x) * turn, (b.y - a.y) * turn); diff --git a/crates/three-d/src/mesh.rs b/crates/three-d/src/mesh.rs index fbc5546d18..a5cf621d9c 100644 --- a/crates/three-d/src/mesh.rs +++ b/crates/three-d/src/mesh.rs @@ -127,6 +127,21 @@ pub fn revolve_mesh(path: &PathData, rule: FillRule, bounds: Rect, options: Revo mesh(&faces) } +/// [`revolve_mesh`], with where each corner of each triangle of the side lies on the side surface +/// unrolled ([`crate::SurfaceCell`]), as the effect places a graphic mapped onto the side: one +/// entry for each triangle, in order, `None` for a triangle of an end cap, of a cut side or of a +/// contour other than the one that carries the graphics. Only a sweep with +/// [`Revolve::map_surface`] lays out its side; without it every entry is `None`. +pub fn revolve_mesh_surface(path: &PathData, rule: FillRule, bounds: Rect, options: Revolve) -> Result { + let (mut faces, mut surface) = (vec![], vec![]); + crate::revolve_surface_faces(path, rule, bounds, options, &mut faces, &mut surface)?; + mesh_on(&faces, Some(&surface)) +} + +/// A mesh with, for each of its triangles, the surface point of each corner, or `None` +/// ([`revolve_mesh_surface`]). +pub type SurfaceMesh = (Mesh, Vec>); + /// The area-weighted normal of `contours` (Newell's method). pub(crate) fn newell(contours: &[Vec]) -> V3 { let mut n = V3::default(); @@ -147,9 +162,28 @@ fn up(v: V3) -> [f64; 3] { /// `faces` (view space) as one mesh, each cut into triangles turned to its normal, which is written /// at unit length whatever length it is given (a face given no normal takes its corners' own). fn mesh(faces: &[Face3]) -> Result { + mesh_on(faces, None).map(|(mesh, _)| mesh) +} + +/// [`mesh`], with for each triangle where its corners lie on a surface: `surface` lists faces by +/// their index in `faces` (in increasing order) with a surface point for each corner of the face's +/// one contour, and a triangle of such a face takes its corners' points. `None` for a triangle of +/// any other face. Without `surface` the list is empty. +fn mesh_on(faces: &[Face3], surface: Option<&[(usize, [Point; 4])]>) -> Result { + let track = surface.is_some(); + let surface = surface.unwrap_or_default(); let mut out = Mesh::default(); + let mut on = vec![]; let mut work = 0usize; - for (contours, normal) in faces { + let mut cells = surface.iter().peekable(); + for (k, (contours, normal)) in faces.iter().enumerate() { + while cells.next_if(|(i, _)| *i < k).is_some() {} + let cell = cells.next_if(|(i, _)| *i == k).map(|(_, uv)| uv); + // The surface point of a corner of a triangle: the point of the face's corner it is. + let point = |v: V3| { + let corners = contours.first()?; + corners.iter().zip(cell?).find(|(c, _)| c.0 == v.0 && c.1 == v.1 && c.2 == v.2).map(|(_, p)| *p) + }; let geometric = newell(contours); let given = normal.unit(); let n = if given.dot(given) > 0.5 { given } else { geometric.unit() }; @@ -157,20 +191,36 @@ fn mesh(faces: &[Face3]) -> Result { continue; } let [nx, ny, nz] = up(n); - for [a, b, c] in triangulate(contours, geometric, &mut work)? { + // A face on the surface is cut along its diagonal from corner 0 to corner 2, as the canvas + // cuts it to place the graphics: the surface's layout of a quad whose ends lie at different + // distances from the axis is not one affine map, so the other diagonal would move them. + let quad = match contours.as_slice() { + [only] if cell.is_some() => <[V3; 4]>::try_from(only.as_slice()).ok(), + _ => None, + }; + let triangles = match quad { + Some([v0, v1, v2, v3]) => vec![[v0, v1, v2], [v0, v2, v3]], + None => triangulate(contours, geometric, &mut work)?, + }; + for [a, b, c] in triangles { let (pa, pb, pc) = (up(a), up(b), up(c)); let cross = V3(pb[0] - pa[0], pb[1] - pa[1], pb[2] - pa[2]).cross(V3(pc[0] - pa[0], pc[1] - pa[1], pc[2] - pa[2])); if cross.dot(cross) < 1e-24 { continue; } - let (pb, pc) = if cross.dot(V3(nx, ny, nz)) < 0.0 { (pc, pb) } else { (pb, pc) }; + let turned = cross.dot(V3(nx, ny, nz)) < 0.0; + let (pb, pc) = if turned { (pc, pb) } else { (pb, pc) }; + let (b, c) = if turned { (c, b) } else { (b, c) }; let base = u32::try_from(out.positions.len()).map_err(|_| "The 3D object is too complex to export".to_string())?; out.positions.extend([pa, pb, pc]); out.normals.extend([[nx, ny, nz]; 3]); out.triangles.push([base, base + 1, base + 2]); + if track { + on.push(point(a).zip(point(b)).zip(point(c)).map(|((a, b), c)| [a, b, c])); + } } } - Ok(out) + Ok((out, on)) } /// A corner of a face: its position on the plane the face is cut in, and in 3D. diff --git a/crates/three-d/src/mesh/tests.rs b/crates/three-d/src/mesh/tests.rs index d17101f66e..907c9f91b2 100644 --- a/crates/three-d/src/mesh/tests.rs +++ b/crates/three-d/src/mesh/tests.rs @@ -317,6 +317,116 @@ fn a_partial_revolve_caps_its_ends_with_sectors_and_closes_its_cut_sides() { assert!(!closed(&hollow)); } +/// A vertical line 40 pt from the axis, from y 10 to 90: an open cylinder of radius 40 about the +/// axis at x 0, its middle height 50. +fn tube() -> (PathData, Rect) { + let mut b = BezPath::new(); + b.move_to((40.0, 10.0)); + b.line_to((40.0, 90.0)); + (PathData::from_bezpath(&b), Rect::new(0.0, 10.0, 40.0, 90.0)) +} + +#[test] +fn a_revolved_sides_corners_lie_where_the_canvas_places_the_unrolled_side() { + let (p, r) = tube(); + let o = Revolve { map_surface: true, ..Revolve::default() }; + let (m, on) = revolve_mesh_surface(&p, FillRule::NonZero, r, o).unwrap(); + assert_eq!(on.len(), m.triangles.len()); + assert_eq!(m.triangles.len(), revolve_mesh(&p, FillRule::NonZero, r, o).unwrap().triangles.len()); + let step = 40.0 * std::f64::consts::TAU / 64.0; + let (mut side, mut caps) = (0, 0); + for (t, points) in m.triangles.iter().zip(&on) { + let c = corners(&m, *t); + let Some(points) = points else { + // The end caps: flat at the top and bottom of the tube. + assert!(c.iter().all(|q| (q[1].abs() - 40.0).abs() < 1e-9), "{c:?}"); + caps += 1; + continue; + }; + side += 1; + for (q, uv) in c.iter().zip(points) { + // y runs down the profile from its middle (the mesh is y up), and x around the axis is + // the angle from the front (90°, toward the viewer), increasing to the viewer's right, + // times the radius. + assert!((uv.y + q[1]).abs() < 1e-9, "{q:?} {uv:?}"); + let turned = std::f64::consts::FRAC_PI_2 - q[2].atan2(q[0]); + let around = (turned + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI; + let seam = (uv.x.abs() - 40.0 * std::f64::consts::PI).abs() < step + 1e-6; + assert!((uv.x - 40.0 * around).abs() < 1e-6 || seam, "{q:?} {uv:?}"); + } + // No triangle reaches across the cut at the back: each spans one step around the axis. + let (lo, hi) = points.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(p.x), hi.max(p.x))); + assert!(hi - lo < step + 1e-6, "{points:?}"); + } + assert_eq!((side, caps > 0), (2 * 64, true)); + // The cut is at the back: the side runs half a turn each way from the front. + let xs = on.iter().flatten().flatten().map(|p| p.x); + let (lo, hi) = xs.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), x| (lo.min(x), hi.max(x))); + assert!((lo + 40.0 * std::f64::consts::PI).abs() < 1e-6 && (hi - 40.0 * std::f64::consts::PI).abs() < 1e-6, "{lo} {hi}"); +} + +#[test] +fn a_revolved_sides_layout_matches_its_drawn_faces_at_every_turn() { + let (p, r) = tube(); + for o in [ + Revolve { map_surface: true, angle: 90.0, ..Revolve::default() }, + Revolve { map_surface: true, angle: 250.0, offset: 15.0, edge: Edge::Right, rotation_x: -20.0, rotation_y: 35.0, ..Revolve::default() }, + ] { + let (m, on) = revolve_mesh_surface(&p, FillRule::NonZero, r, o).unwrap(); + // The drawn faces' surface points, which the canvas places the graphics by. + let drawn: Vec = crate::revolve(&p, r, o).unwrap().iter().filter_map(|f| f.surface.as_ref()).flat_map(|c| c.uv.clone()).collect(); + let near = |q: Point| drawn.iter().any(|d| d.distance(q) < 1e-6); + let points: Vec = on.iter().flatten().flatten().copied().collect(); + assert!(!points.is_empty() && points.iter().all(|q| near(*q)), "{o:?}"); + assert!(drawn.iter().all(|d| points.iter().any(|q| q.distance(*d) < 1e-6)), "{o:?}"); + // The end sectors and the two cut sides carry no surface points. + assert!(on.iter().any(Option::is_none) && on.len() == m.triangles.len()); + } + // Without the layout, no triangle carries one. + let (_, on) = revolve_mesh_surface(&p, FillRule::NonZero, r, Revolve::default()).unwrap(); + assert!(on.iter().all(Option::is_none)); +} + +#[test] +fn a_tapered_sides_triangles_are_the_drawn_faces_triangles() { + // A cone's side: each face's ends lie at different distances from the axis, so its layout on + // the surface is not one affine map, and each triangle must take the corners the canvas cuts + // the face into. + let mut b = BezPath::new(); + b.move_to((10.0, 10.0)); + b.line_to((40.0, 90.0)); + let p = PathData::from_bezpath(&b); + let r = Rect::new(0.0, 10.0, 40.0, 90.0); + let o = Revolve { map_surface: true, ..Revolve::default() }; + let key = |t: &[Point]| { + let mut k: Vec<(i64, i64)> = t.iter().map(|q| ((q.x * 1e6).round() as i64, (q.y * 1e6).round() as i64)).collect(); + k.sort_unstable(); + k + }; + let drawn: Vec<_> = crate::revolve(&p, r, o).unwrap().iter().filter_map(|f| f.surface.as_ref()).map(|c| key(&c.uv)).collect(); + assert!(drawn.iter().all(|k| k.len() == 3), "the canvas draws the smooth side in triangles"); + let (_, on) = revolve_mesh_surface(&p, FillRule::NonZero, r, o).unwrap(); + let side: Vec<_> = on.iter().flatten().collect(); + assert_eq!(side.len(), drawn.len()); + assert!(side.iter().all(|t| drawn.contains(&key(t.as_slice())))); +} + +#[test] +fn only_the_longest_contour_of_a_revolved_profile_lies_on_the_side_surface() { + let mut b = BezPath::new(); + b.move_to((40.0, 10.0)); + b.line_to((40.0, 90.0)); + b.move_to((20.0, 30.0)); + b.line_to((20.0, 50.0)); + let p = PathData::from_bezpath(&b); + let r = Rect::new(0.0, 10.0, 40.0, 90.0); + let (m, on) = revolve_mesh_surface(&p, FillRule::NonZero, r, Revolve { map_surface: true, cap_ends: false, ..Revolve::default() }).unwrap(); + for (t, points) in m.triangles.iter().zip(&on) { + let radius = corners(&m, *t).iter().map(|q| q[0].hypot(q[2])).fold(0.0f64, f64::max); + assert_eq!(points.is_some(), radius > 30.0, "{radius}"); + } +} + #[test] fn a_revolved_surface_has_unit_normals_facing_out_whatever_its_length_and_direction() { // A wall 100 pt tall and one 0.5 pt tall, each drawn up and down the page. diff --git a/crates/three-d/src/shadow.rs b/crates/three-d/src/shadow.rs index 00ae75d169..38d2be50c7 100644 --- a/crates/three-d/src/shadow.rs +++ b/crates/three-d/src/shadow.rs @@ -369,7 +369,7 @@ pub fn inflate_shadowed( /// [`crate::revolve`] gives one. pub fn revolve_shadowed(path: &PathData, bounds: Rect, options: Revolve) -> Result<(Vec, SolidFaces), String> { let mut kept = vec![]; - let (faces, lost) = crate::revolve_sweep(path, options.fill_rule, bounds, options, true, Some(&mut kept))?; + let (faces, lost) = crate::revolve_sweep(path, options.fill_rule, bounds, options, true, Some(&mut kept), None)?; let projection = Some(crate::revolve_projection(bounds, options.sanitized())); Ok((faces, SolidFaces { faces: lost.map_or(Ok(kept), Err), projection })) } diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index 1057d024bd..be13429151 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -28,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, extrude_side_size, plane}; +pub use build::{extrude, extrude_side_size, extrude_surfaces, plane}; pub use face_map::{FaceMap, MeshFace, extrude_face_map, extrude_mesh_face, plane_face_map, plane_mesh_face}; pub(crate) use inflate::inflate_faces; #[cfg(test)] @@ -219,6 +219,9 @@ 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, + /// Lay out the solid's numbered surfaces ([`extrude_surfaces`]): each facet of a wall or a + /// bevel band then carries its [`MapCell`]. A solid with a twist or a taper has none. + pub map_surfaces: 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, @@ -226,10 +229,44 @@ pub struct Extrude { impl Default for Extrude { fn default() -> Self { - Self { depth: 50.0, twist: 0.0, taper: 1.0, cap: true, bevel: None, hidden: false, map_surface: false } + Self { depth: 50.0, twist: 0.0, taper: 1.0, cap: true, bevel: None, hidden: false, map_surfaces: false, map_surface: false } } } +/// Where a facet lies on one of its solid's numbered surfaces, laid out flat: the surface's index, +/// the facet's corners on the page, and the point of the flat surface at each corner, in points +/// (x along the surface from its left edge as it is seen from outside the solid, y from the edge +/// nearer the front of the solid). +#[derive(Clone, Debug, PartialEq)] +pub struct MapCell { + pub surface: usize, + pub page: Vec, + pub uv: Vec, +} + +/// What a numbered surface of a solid is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SurfaceKind { + /// The front or back cap, or a plane's only face. + End(PlanarFace), + /// A side wall: the part of the side between two corners of the outline. + Wall, + /// The bevel between the front cap and a side wall. + Bevel, + /// Revolve's swept side. + Side, +} + +/// One numbered surface of a solid: its kind and its size laid out flat, in points. An end also +/// has the center of its bounds in the art's plane. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SolidSurface { + pub kind: SurfaceKind, + pub width: f64, + pub height: f64, + pub center: Option, +} + /// Inflate's options. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Inflate { @@ -322,6 +359,10 @@ pub struct Facet { /// 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. pub plane: Option, + /// Where the facet lies on one of its solid's numbered surfaces. `None` unless the solid was + /// built with its surfaces laid out ([`Extrude::map_surfaces`], [`Revolve::map_surface`]), + /// and for the ends, whose art is placed through a [`FaceMap`]. + pub cell: Option>, /// The contours in view space, before projection, for tests that measure depths. #[cfg(test)] view: Vec>, @@ -394,7 +435,11 @@ impl Facet { /// Revolve's face `face` as a facet: its polygon, curved outline, depth, plane, normal and lighting. /// A face that joins the profile's ends round the axis is a side; a cap is an end. pub(crate) fn of_face(face: crate::Face) -> Self { + // The side is the surface's only numbered surface. A face that shows its inside carries + // no cell. + let cell = face.surface.filter(|c| c.outward && !face.cap).map(|c| Box::new(MapCell { surface: 0, page: c.page, uv: c.uv })); Facet { + cell, contours: vec![face.points], depth: face.depth, brightness: face.brightness, diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index ed68f9508e..d883ad14b8 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -7,8 +7,8 @@ use super::rings::{ }; 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, + Bevel, DepthPlane, Extrude, Facet, FillRule, MAX_FACES, MAX_SOLID_FACES, MapCell, ParamCurve, PathData, PlanarFace, Point, Rect, Revolve, + SolidSurface, SurfaceKind, V3, View, eye_distance, perspective_scale, }; use crate::shadow::Projection; @@ -102,6 +102,16 @@ pub(super) struct Builder<'a> { /// The faces kept for the mesh passed [`MAX_SOLID_FACES`] while the facets were built too: the /// mesh is too complex, and `mesh` keeps no more faces. pub(super) lost: bool, + /// The cells the facets of the next band carry ([`Builder::curved_band`]). + pub(super) cells: Option, +} + +/// The cells of one band's facets: for each edge of the ring, its numbered surface and where the +/// edge starts and ends along it (`None` for an edge of no length), and where the band's two rings +/// lie across the surface. +pub(super) struct BandCells { + edges: Vec>, + across: (f64, f64), } /// Where a face goes in the order the facets are drawn, back to front. @@ -123,7 +133,16 @@ pub(super) enum Order { impl<'a> Builder<'a> { /// A builder for one solid seen by `camera`, keeping what `keep` asks for. pub(super) fn new(camera: &'a Camera, closed: bool, hidden: bool, keep: Keep) -> Self { - Self { camera, closed, hidden, facets: vec![], mesh: (keep != Keep::Facets).then(Vec::new), draw: keep != Keep::Faces, lost: false } + Self { + camera, + closed, + hidden, + facets: vec![], + mesh: (keep != Keep::Facets).then(Vec::new), + draw: keep != Keep::Faces, + lost: false, + cells: None, + } } /// Add a face of view-space contours with outward normal `n` (view space), drawn in `order`. @@ -215,6 +234,7 @@ impl<'a> Builder<'a> { surface: None, membrane: None, plane, + cell: None, #[cfg(test)] view, }); @@ -301,6 +321,12 @@ impl<'a> Builder<'a> { && let Some(f) = self.facets.last_mut() { f.side = true; + // An edge drawn in one piece carries its place on its numbered surface. + let cell = self.cells.as_ref().filter(|_| pieces == 1).and_then(|c| Some((c.edges.get(i).copied().flatten()?, c.across))); + if let (Some(((surface, u0, u1), (v0, v1))), Some(page)) = (cell, f.contours.first()) { + let uv = vec![Point::new(u0, v0), Point::new(u1, v0), Point::new(u1, v1), Point::new(u0, v1)]; + f.cell = Some(Box::new(MapCell { surface, page: page.clone(), uv })); + } if let Some(s) = side.as_ref() && let (Some([x0, x1]), Some(page)) = (s.x.get(i).copied(), f.contours.first()) { @@ -535,6 +561,16 @@ struct Step { face: f64, } +/// How far the walls are inset (negative: outset). With the bevel inside, the cap is inset by its +/// width and the wall is the outline; outside, the cap is the outline and the wall is outset by +/// the width. +fn wall_inset(o: &Extrude) -> f64 { + match o.bevel.filter(|b| b.width > 0.0 || b.height > 0.0) { + Some(b) if !b.inside => -b.width, + _ => 0.0, + } +} + /// The outline's steps from the front cap's edge to the back cap's edge. fn steps(o: &Extrude) -> Vec { let d = o.depth.max(1e-6); @@ -564,12 +600,7 @@ fn steps(o: &Extrude) -> Vec { } pts }; - // With the bevel inside, the cap is inset by its width and the wall is the outline; outside, - // the cap is the outline and the wall is outset by the width. - let wall = match bevel { - Some(b) if !b.inside => -b.width, - _ => 0.0, - }; + let wall = wall_inset(o); // A twist turns a bevel's steps too: each step between two samples is cut into steps that // turn no further than 6°, as the walls' slices do at most. let refine = |pts: Vec<(f64, f64)>| -> Vec<(f64, f64)> { @@ -695,6 +726,8 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio }) .collect(); let mut budget = Budget::default(); + // The numbered surfaces of the sides, for a solid whose walls stay flat. + let layout = (o.map_surfaces && o.twist == 0.0 && o.taper == 1.0).then(|| (sides(&traced, wall_inset(&o)), band_spans(&steps, o.depth))); // With graphics on the side, the longest contour's pieces carry where they lie on it unrolled. let unrolled = o .map_surface @@ -709,6 +742,17 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio 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 }; + b.cells = layout.as_ref().and_then(|(sides, spans)| { + let (bevel, v0, v1) = spans.get(k).copied().flatten()?; + // Without a wall span the walls are not numbered, and the bevels follow the caps. + let walls = has_walls(spans); + if !bevel && !walls { + return None; + } + let base = caps + if bevel && walls { sides.lengths.len() } else { 0 }; + let edges = sides.edges.get(r)?.iter().map(|e| e.map(|(section, u0, u1)| (base + section, u0, u1))).collect(); + Some(BandCells { edges, across: (v0, v1) }) + }); // A band between two front bevel steps borders the front, one reaching a back bevel // step the back; the rest are walls. let face = if s1.face < 0.0 { @@ -726,6 +770,7 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio b.curved_band(a, c, pieces, |i| outward(ring, i, face), curves, side)?; } } + b.cells = None; if o.cap { // A cap turned toward the viewer covers the walls it overlaps, even those nearer than its // center: twisted walls, and the walls of a fill inside the solid of its stroke. @@ -744,6 +789,152 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio Ok(b.finish()) } +/// The turn of the outline, in degrees, past which the side wall on one side of a point is another +/// numbered surface than the wall on its other side. +const CORNER: f64 = 20.0; + +/// How the sides of a solid's rings divide into numbered surfaces: for each ring, each edge's +/// surface (counted through the rings in order) and where the edge starts and ends along it, and +/// each surface's length. A surface runs from one corner of its ring to the next, and a ring with +/// no corner is one surface from its first point. The edges of one curve of the outline are never +/// parted. An edge of no length belongs to no surface. An edge starts farther along its surface +/// than it ends: the surface is measured from its left edge as it is seen from outside the solid. +/// Lengths are measured on the ring moved to the walls' inset `wall`, so a wall set out by a bevel +/// is laid out at its own length, and a bevel band at the length of the wall below it. +struct Sides { + edges: Vec>>, + lengths: Vec, +} + +fn sides(rings: &[Ring], wall: f64) -> Sides { + let mut out = Sides { edges: vec![], lengths: vec![] }; + for ring in rings { + let n = ring.points.len(); + let point = |i: usize| ring.points.get(i % n.max(1)).copied().unwrap_or_default(); + let at_wall = inset(&ring.points, wall); + let wall_point = |i: usize| at_wall.get(i % n.max(1)).copied().unwrap_or_default(); + // An edge of the outline with no length (a corner cut square) stays off every surface. + let length = |i: usize| if point(i).distance(point(i + 1)) > 1e-9 { wall_point(i).distance(wall_point(i + 1)) } else { 0.0 }; + let direction = |i: usize| { + let d = point(i + 1) - point(i); + let l = d.hypot(); + (l > 1e-9).then(|| d / l) + }; + let curve = |i: usize| ring.spans.get(i % n.max(1)).copied().flatten().map(|s| s.curve); + // Point `i` is a corner when the edge that leaves it turns from the last edge with a + // length before it, and the two do not follow one curve. + let corner = |i: usize| { + let Some(leaving) = direction(i) else { return false }; + let Some(before) = (1..n).map(|k| i + n - k).find(|e| direction(*e).is_some()) else { return false }; + let one_curve = matches!((curve(before), curve(i)), (Some(a), Some(b)) if a == b); + !one_curve && direction(before).is_some_and(|d| d.dot(leaving) < CORNER.to_radians().cos()) + }; + let start = (0..n).find(|i| corner(*i)).unwrap_or(0); + let mut edges = vec![None; n]; + let mut along = 0.0; + out.lengths.push(0.0); + for k in 0..n { + let i = (start + k) % n; + if k > 0 && corner(i) { + out.lengths.push(0.0); + along = 0.0; + } + let l = length(i); + if let Some(slot) = edges.get_mut(i).filter(|_| l > 1e-9) { + *slot = Some((out.lengths.len() - 1, along, along + l)); + } + along += l; + if let Some(total) = out.lengths.last_mut() { + *total = along; + } + } + // A ring runs from right to left as its side is seen from outside the solid, so each edge + // is placed from its surface's far end. + for (surface, from, to) in edges.iter_mut().flatten() { + let length = out.lengths.get(*surface).copied().unwrap_or(0.0); + (*from, *to) = (length - *from, length - *to); + } + out.edges.push(edges); + } + out +} + +/// Where the band between each two neighboring steps lies across its numbered surface: whether it +/// is part of the front bevel (else of the wall), and the distances of its two rings from the +/// surface's edge nearer the front. `None` for a band of a back bevel. +fn band_spans(steps: &[Step], depth: f64) -> Vec> { + let (mut bevel_at, mut wall_at) = (0.0, 0.0); + steps + .windows(2) + .map(|pair| { + let [s0, s1] = pair else { return None }; + if s1.face < 0.0 { + return None; + } + let across = (s1.inset - s0.inset).hypot((s1.t - s0.t) * depth); + let bevel = s0.face > 0.0 && s1.face > 0.0; + let at = if bevel { &mut bevel_at } else { &mut wall_at }; + let from = *at; + *at += across; + Some((bevel, from, *at)) + }) + .collect() +} + +/// Whether the bands of `spans` ([`band_spans`]) hold a wall with some width across it: a bevel as +/// deep as the solid leaves none. +fn has_walls(spans: &[Option<(bool, f64, f64)>]) -> bool { + spans.iter().flatten().any(|(bevel, from, to)| !bevel && to > from) +} + +/// The numbered surfaces of the solid [`extrude`] builds from `path`, in order: the front and back +/// caps of a solid with caps, then each side wall, ring by ring from each ring's first corner, then +/// the bevel above each wall in the same order. A plane (no depth) has its front only, and a solid +/// with a twist or a taper has only its caps. A solid whose bevel is as deep as the solid has no +/// walls. The facets of a solid built with +/// [`Extrude::map_surfaces`] carry these indexes ([`MapCell`]). +pub fn extrude_surfaces(path: &PathData, rule: FillRule, bounds: Rect, options: Extrude) -> Result, String> { + check_bounds(bounds)?; + let o = options.sanitized(); + let end = + |face: PlanarFace, b: Rect| SolidSurface { kind: SurfaceKind::End(face), width: b.width(), height: b.height(), center: Some(b.center()) }; + if o.depth <= 0.0 { + return Ok(path.bounds().map(|b| end(PlanarFace::Front, b)).into_iter().collect()); + } + 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)?; + 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)?.iter().map(|r| square_corners(r, side)).collect(); + // A solid past the face limit is refused, as [`extrude_faces`] refuses it. + let edges = traced.iter().map(|r| r.points.len()).fold(0usize, usize::saturating_add); + if edges.saturating_mul(bands).saturating_add(caps) > MAX_SOLID_FACES { + return Err(TOO_COMPLEX_SURFACE.into()); + } + let mut out = vec![]; + if o.cap { + for (step, face) in [(steps.first(), PlanarFace::Front), (steps.last(), PlanarFace::Back)] { + let Some(step) = step else { continue }; + let mut points = traced.iter().flat_map(|r| inset(&r.points, step.inset)); + let Some(first) = points.next() else { continue }; + out.push(end(face, points.fold(Rect::from_points(first, first), |b, p| b.union_pt(p)))); + } + } + if o.twist != 0.0 || o.taper != 1.0 { + return Ok(out); + } + let sides = sides(&traced, wall_inset(&o)); + let spans = band_spans(&steps, o.depth); + let across = |bevel: bool| spans.iter().flatten().filter(|s| s.0 == bevel).map(|s| s.2).fold(0.0, f64::max); + let walls = has_walls(&spans).then_some((SurfaceKind::Wall, false)); + let kinds = walls.into_iter().chain(spans.iter().flatten().any(|s| s.0).then_some((SurfaceKind::Bevel, true))); + for (kind, bevel) in kinds { + out.extend(sides.lengths.iter().map(|l| SolidSurface { kind, width: *l, height: across(bevel), center: None })); + } + Ok(out) +} + /// 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. diff --git a/crates/three-d/src/solid/tests.rs b/crates/three-d/src/solid/tests.rs index 6e9cce82fc..2caed84391 100644 --- a/crates/three-d/src/solid/tests.rs +++ b/crates/three-d/src/solid/tests.rs @@ -554,6 +554,7 @@ 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_surfaces: false, map_surface: true, }; let f = extrude(&p, FillRule::EvenOdd, b, wild, View { rotation_x: f64::NAN, perspective: 900.0, ..front() }).unwrap(); diff --git a/crates/three-d/src/solid/tests_side.rs b/crates/three-d/src/solid/tests_side.rs index f2d7ec722a..47c519ca05 100644 --- a/crates/three-d/src/solid/tests_side.rs +++ b/crates/three-d/src/solid/tests_side.rs @@ -1,6 +1,6 @@ use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect}; -use super::super::{Bevel, Extrude, View, extrude, extrude_side_size}; +use super::super::{Bevel, Extrude, View, extrude, extrude_side_size, extrude_surfaces}; use super::{across_steps, along_ring, longest}; fn square(r: Rect, hole: Option) -> PathData { @@ -94,3 +94,30 @@ fn the_side_measures_around_the_outline_and_across_the_bevels() { 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)); } + +#[test] +fn the_surfaces_of_a_solid_past_the_face_limit_are_refused_as_its_side_is() { + // A star of `n` thin spikes: a bevel outside cuts each sharp tip square, adding a corner there. + let star = |n: usize| { + let mut b = BezPath::new(); + for i in 0..2 * n { + let a = i as f64 * std::f64::consts::PI / n as f64; + let r = if i % 2 == 0 { 1000.0 } else { 100.0 }; + if i == 0 { b.move_to((r * a.cos(), r * a.sin())) } else { b.line_to((r * a.cos(), r * a.sin())) } + } + b.close_path(); + PathData::from_bezpath(&b) + }; + let bounds = Rect::new(-1000.0, -1000.0, 1000.0, 1000.0); + let o = Extrude { depth: 40.0, bevel: Some(Bevel { width: 1.0, height: 1.0, ..Bevel::default() }), ..Extrude::default() }; + let fits = |n: usize| extrude_side_size(&star(n), FillRule::NonZero, bounds, o).is_some(); + // The fewest spikes past the limits, as the side's size counts them. + let (mut lo, mut hi) = (3usize, 100_000usize); + assert!(fits(lo) && !fits(hi)); + while hi - lo > 1 { + let mid = (lo + hi) / 2; + if fits(mid) { lo = mid } else { hi = mid } + } + assert!(extrude_surfaces(&star(lo), FillRule::NonZero, bounds, o).is_ok()); + assert!(extrude_surfaces(&star(hi), FillRule::NonZero, bounds, o).is_err(), "{hi} spikes"); +} diff --git a/crates/three-d/src/tests.rs b/crates/three-d/src/tests.rs index ace8566816..069013c808 100644 --- a/crates/three-d/src/tests.rs +++ b/crates/three-d/src/tests.rs @@ -327,6 +327,16 @@ fn only_the_longest_contour_of_a_compound_profile_carries_the_side_surface() { let (w, h) = revolve_surface_size(&PathData::from_bezpath(&bp), b, Revolve::default()).unwrap(); assert!((w - 10.0 * std::f64::consts::PI).abs() < 1e-9 && (h - 80.0).abs() < 1e-3, "{w} {h}"); } +#[test] +fn a_side_quad_lies_on_the_surface_at_its_corners_distances_from_the_axis() { + // An edge from 30 to 50 pt right of an axis at 10, at surface y -5 and 15, over a step from + // 0.25 to 0.5 radians: x is each angle times each corner's own distance from the axis. + let corners = surface_corners(Point::new(30.0, 0.0), Point::new(50.0, 20.0), 10.0, [-5.0, 15.0], [0.25, 0.5]); + assert_eq!(corners, [Point::new(5.0, -5.0), Point::new(10.0, 15.0), Point::new(20.0, 15.0), Point::new(10.0, -5.0)]); + // Left of the axis the distances are the same. + let left = surface_corners(Point::new(-10.0, 0.0), Point::new(-30.0, 20.0), 10.0, [-5.0, 15.0], [0.25, 0.5]); + assert_eq!(left, corners); +} /// The square ring of [`a_ring_profile_is_measured_from_its_outer_side_at_mid_height`] with an /// anchor in the middle of its inner side. fn split_square() -> [Point; 6] { diff --git a/crates/tools/src/addons.rs b/crates/tools/src/addons.rs index ca8645ffc8..c0223aedb9 100644 --- a/crates/tools/src/addons.rs +++ b/crates/tools/src/addons.rs @@ -17,6 +17,7 @@ pub mod polygonal_lasso; pub mod shared_edge; pub mod slide_anchor; pub mod smart_pen; +pub mod tangent_circle; pub mod trim; use crate::{Tool, ToolInfo}; @@ -31,6 +32,7 @@ pub const PATH_TOOLS: &[ToolInfo] = &[ ToolInfo { id: corner_tool::ID, label: "Corner Tool", shortcut: None, icon: "dc-rounded-rect" }, ToolInfo { id: slide_anchor::ID, label: "Slide Anchor Along Path", shortcut: None, icon: "dc-anchor" }, ToolInfo { id: shared_edge::ID, label: "Shared Edge Merge Tool", shortcut: None, icon: "dc-join" }, + ToolInfo { id: tangent_circle::ID, label: "Tangent Circle Tool", shortcut: None, icon: "circle" }, ]; /// Smart Pen's tool, a flyout group of its own. @@ -66,6 +68,7 @@ pub fn create(id: &str) -> Option> { shared_edge::ID => Box::new(shared_edge::SharedEdgeTool::default()), slide_anchor::ID => Box::new(slide_anchor::SlideAnchorTool::default()), smart_pen::ID => Box::new(smart_pen::SmartPenTool::default()), + tangent_circle::ID => Box::new(tangent_circle::TangentCircleTool::default()), trim::ID => Box::new(trim::TrimTool::default()), enclosing_lasso::ID => Box::new(enclosing_lasso::EnclosingLassoTool::default()), contour::ID => Box::new(contour::ContourTool::default()), 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/tangent_circle.rs b/crates/tools/src/addons/tangent_circle.rs new file mode 100644 index 0000000000..a8d24d8853 --- /dev/null +++ b/crates/tools/src/addons/tangent_circle.rs @@ -0,0 +1,720 @@ +//! Tangent Circle tool (Path Precision Tools): click a path segment, then another, selected or +//! not, to draw the circle that is tangent to the first segment where it was clicked and touches the +//! second ([`circles_through`]). With Shift held over the second segment the circle has the tool's +//! `radius` instead, anywhere along the first segment ([`circles_of_radius`]). A drag from the +//! second segment sets the radius to the drag's length, the circle again anywhere along the first +//! segment: Shift steps it by a round number of points about 4 screen pixels long, and Cmd/Ctrl +//! pressed during the drag moves it by a tenth of the pointer's movement (held at the press, +//! Cmd/Ctrl lends the selection tool as it does for every tool). The segments on either side of the +//! second one count with it (the first one excepted), and of the circles found the one touching +//! them nearest the pointer (in a drag, nearest the press) is drawn. While the pointer is over the +//! second segment the circle shows with its center and radii; where there is none, or none that its +//! three points can draw, a note says so. The circle is a new ellipse with the current paint, drawn +//! with `shape.circleThroughPoints` in one undo step, so Align New Objects to Pixel Grid leaves it +//! in place; the first segment stays picked until the circle is drawn, also when drawing fails or the +//! press on the second segment is dropped. Escape, an edit or Undo outside the tool, or another +//! document forgets the first segment. + +use kurbo::{CubicBez, Shape}; +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; +use vectorcraft_geom::{BezPath, ParamCurve, Point}; +use vectorcraft_pathops::addons::pathtools::{SegmentCircle, circles_of_radius, circles_through}; + +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; + +/// The tool's id. +pub const ID: &str = "tangentCircle"; +/// The radius Shift asks for to start with (pt). +pub const RADIUS: f64 = 36.0; +/// The radius the `radius` option takes (pt). +pub const RADIUS_RANGE: (f64, f64) = (0.01, 1e6); +/// How far (screen pixels) the pointer moves from the second click before a drag sets the radius. +const DRAG_PX: f64 = 3.0; +/// About how long (screen pixels) one step of a Shift drag is. +const STEP_PX: f64 = 4.0; +/// How much of the pointer's movement a Cmd/Ctrl drag gives the radius. +const SLOW: f64 = 0.1; +/// The note shown over a second segment that gives no circle. +pub const NO_CIRCLE: &str = "No tangent circle here"; +const BLUE: [u8; 3] = [0x4f, 0x9d, 0xff]; +const RED: [u8; 3] = [0xe0, 0x3c, 0x3c]; +const GREY: [u8; 3] = [0x80, 0x80, 0x80]; + +/// A segment under the pointer: where on it, and the segment itself. +#[derive(Clone, Debug, PartialEq)] +struct Pick { + id: NodeId, + subpath: usize, + segment: usize, + t: f64, + p: Point, + curve: CubicBez, +} + +/// A press on the second segment, kept while the button is down. +#[derive(Clone, Debug, PartialEq)] +struct Press { + /// The segments a circle may touch. + second: Vec, + /// Where the press was. + at: Point, + /// Whether Shift was held when the click's circle was last looked for. + shift: bool, + /// How far the pointer was from the press last time, and the radius the drag set (none until + /// the pointer moves far enough). + reach: f64, + radius: Option, +} + +pub struct TangentCircleTool { + radius: f64, + first: Option, + hover: Option, + press: Option, + /// Whether the press in progress picked the first segment. + picking: bool, + /// The circle the second segment gives, and whether one was looked for. + found: Option, + looked: bool, + pointer: Point, + /// The circles the last second segment gave (its path, subpath and segment, and the radius + /// asked for), so that moving along it only picks among them. + cache: Option<(CacheKey, Vec)>, +} + +type CacheKey = (NodeId, usize, usize, Option); + +impl Default for TangentCircleTool { + fn default() -> Self { + Self { radius: RADIUS, first: None, hover: None, press: None, picking: false, found: None, looked: false, pointer: Point::ZERO, cache: None } + } +} + +/// The path segment under `p`, of any editable path. +fn pick_at(cx: &ToolContext, p: Point) -> Option { + let (id, subpath, segment, t) = crate::draw2::hit_segment(cx, p, cx.pick_tol())?; + let sp = cx.doc.node(id)?.path_data()?.subpaths.get(subpath)?; + if segment >= sp.segment_count() { + return None; + } + let curve = sp.segment(segment); + Some(Pick { id, subpath, segment, t, p: curve.eval(t), curve }) +} + +/// The segments a circle may touch when `second` is picked: it and the segments on either side of +/// it, without `first`. None when `second` is the first segment again. +fn second_set(cx: &ToolContext, first: &Pick, second: &Pick) -> Vec { + if (first.id, first.subpath, first.segment) == (second.id, second.subpath, second.segment) { + return vec![]; + } + let Some(sp) = cx.doc.node(second.id).and_then(|n| n.path_data()).and_then(|p| p.subpaths.get(second.subpath)) else { return vec![] }; + let n = sp.segment_count(); + let i = second.segment; + let mut indices = vec![i]; + if i > 0 || sp.closed { + indices.push((i + n - 1) % n); + } + if i + 1 < n || sp.closed { + indices.push((i + 1) % n); + } + indices.sort_unstable(); + indices.dedup(); + let is_first = |k: usize| first.id == second.id && first.subpath == second.subpath && first.segment == k; + indices.into_iter().filter(|k| *k < n && !is_first(*k)).map(|k| sp.segment(k)).collect() +} + +/// Of `circles`, the one touching the second segments nearest `at`, leaving out those [`draw`] cannot +/// draw within `tol`. +fn nearest_to(circles: Vec, at: Point, tol: f64) -> Option { + circles.into_iter().filter(|c| draw(c, tol).is_some()).min_by(|a, b| (a.second - at).hypot().total_cmp(&(b.second - at).hypot())) +} + +/// How far (screen pixels) the circle three points give back may be from the circle found. +const DRAW_PX: f64 = 0.05; +/// What the tool is told once its circle is drawn: then it forgets the first segment. +const DRAWN: &str = "tangentCircle.drawn"; + +/// The circles on `first` and `second`: tangent at the first pick, or of `radius`. +fn circles(first: &Pick, second: &[CubicBez], radius: Option) -> Vec { + match radius { + Some(r) => circles_of_radius(first.curve, second, r), + None => circles_through(first.curve, first.t, second), + } +} + +/// The step a Shift drag rounds the radius to: 1, 2 or 5 times a power of 10, at least `least`. +fn round_step(least: f64) -> f64 { + if !(least.is_finite() && least > 0.0) { + return 1.0; + } + let e = 10f64.powf(least.log10().floor()); + [1.0, 2.0, 5.0, 10.0].into_iter().map(|m| m * e).find(|s| *s >= least).unwrap_or(10.0 * e) +} + +/// Draw circle `c`: through three points spread around it, with `shape.circleThroughPoints`, which +/// leaves it where it is with Align New Objects to Pixel Grid on, so that it stays tangent. None +/// when the three points do not give the circle back to within `tol` (a circle too small for its +/// distance from the origin, or too large, in floating point). +fn draw(c: &SegmentCircle, tol: f64) -> Option { + let (at, r) = (c.circle.center, c.circle.radius); + let points: Vec = [90.0f64, 210.0, 330.0] + .iter() + .map(|deg| { + let (s, k) = deg.to_radians().sin_cos(); + Point::new(at.x + r * k, at.y + r * s) + }) + .collect(); + let (back, rb) = vectorcraft_geom::shapes::circle_through(points[0], points[1], points[2])?; + if !(back.distance(at) <= tol && (rb - r).abs() <= tol) { + return None; + } + let points: Vec<[f64; 2]> = points.iter().map(|p| [p.x, p.y]).collect(); + Some(Action::Exec("shape.circleThroughPoints".into(), json!({ "points": points }))) +} + +fn segment_path(c: &CubicBez) -> BezPath { + let mut bp = BezPath::new(); + bp.move_to(c.p0); + bp.curve_to(c.p1, c.p2, c.p3); + bp +} + +impl TangentCircleTool { + /// The radius a drag gives, with Shift in round steps. + fn shown_radius(cx: &ToolContext, r: f64, shift: bool) -> f64 { + if !shift { + return r; + } + let step = round_step(cx.tol(STEP_PX)); + // Less than half a step rounds to 0: no circle, as without Shift. + (r / step).round() * step + } + + /// The circles `pick` gives as the second segment, with Shift's `radius`: worked out again only + /// when the segment or the radius changes. + fn circles_on(&mut self, cx: &ToolContext, pick: &Pick, radius: Option) -> Vec { + let key = (pick.id, pick.subpath, pick.segment, radius.map(f64::to_bits)); + if let Some((k, found)) = &self.cache + && *k == key + { + return found.clone(); + } + let Some(first) = &self.first else { return vec![] }; + let found = circles(first, &second_set(cx, first, pick), radius); + self.cache = Some((key, found.clone())); + found + } + + /// Look for the circle the pointer at `p` would give over `hover`, before any press. + fn look(&mut self, cx: &ToolContext, p: Point, mods: Mods) { + self.found = None; + self.looked = false; + let Some(hover) = self.hover.clone().filter(|_| self.first.is_some()) else { return }; + let found = self.circles_on(cx, &hover, mods.shift.then_some(self.radius)); + self.found = nearest_to(found, p, cx.tol(DRAW_PX)); + self.looked = true; + } + + /// The pointer at `ev` during a press on the second segment: once it is far enough from the + /// press, the radius follows it (Cmd/Ctrl: a tenth of its movement; Shift: round steps). + fn drag_to(&mut self, cx: &ToolContext, ev: &PointerEvent) { + let radius = self.radius; + let (Some(first), Some(press)) = (&self.first, &mut self.press) else { return }; + let reach = ev.pos.distance(press.at); + let gear = if ev.mods.cmd { SLOW } else { 1.0 }; + let r = match press.radius { + None if reach <= cx.tol(DRAG_PX) => { + // Shift pressed or let go before the drag starts: the click's circle, with or + // without the tool's radius. + if ev.mods.shift != press.shift { + press.shift = ev.mods.shift; + let found = circles(first, &press.second, press.shift.then_some(radius)); + self.found = nearest_to(found, press.at, cx.tol(DRAW_PX)); + } + return; + } + None => reach * gear, + Some(r) => (r + (reach - press.reach) * gear).max(0.0), + }; + press.reach = reach; + press.radius = Some(r); + let shown = Self::shown_radius(cx, r, ev.mods.shift); + // Dragged back to the press: a radius of 0, and no circle. + self.found = if shown > 0.0 { nearest_to(circles(first, &press.second, Some(shown)), press.at, cx.tol(DRAW_PX)) } else { None }; + } + + fn forget(&mut self) { + self.first = None; + self.press = None; + self.picking = false; + self.found = None; + self.looked = false; + self.cache = None; + } +} + +impl Tool for TangentCircleTool { + fn id(&self) -> &'static str { + ID + } + + fn busy(&self) -> bool { + self.press.is_some() + } + + fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + self.pointer = ev.pos; + match ev.kind { + PointerKind::Move => { + self.hover = pick_at(cx, ev.pos); + self.look(cx, ev.pos, ev.mods); + vec![] + } + PointerKind::Down => { + let Some(pick) = pick_at(cx, ev.pos) else { return vec![] }; + let Some(first) = self.first.clone() else { + self.first = Some(pick); + self.picking = true; + self.hover = None; + self.found = None; + self.looked = false; + return vec![]; + }; + let second = second_set(cx, &first, &pick); + let found = self.circles_on(cx, &pick, ev.mods.shift.then_some(self.radius)); + self.found = nearest_to(found, ev.pos, cx.tol(DRAW_PX)); + self.looked = true; + self.hover = None; + self.press = Some(Press { second, at: ev.pos, shift: ev.mods.shift, reach: 0.0, radius: None }); + vec![] + } + PointerKind::Drag => { + self.drag_to(cx, ev); + vec![] + } + PointerKind::Up => { + // The release's own position and keys set the radius of a drag. + self.drag_to(cx, ev); + self.picking = false; + if self.press.take().is_none() { + return vec![]; + } + // No circle, or one the three points cannot draw: the first segment stays picked, + // for another try. It also stays when the command fails: only a drawn circle tells + // the tool (`notify`) to forget it. + let Some(action) = self.found.take().and_then(|c| draw(&c, cx.tol(DRAW_PX))) else { return vec![] }; + self.looked = false; + vec![action, Action::Notify(DRAWN.into())] + } + // The canvas sends a double-click after the second click's `Up`, which drew the circle. + PointerKind::DoubleClick | PointerKind::TripleClick => vec![], + } + } + + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + if key == ToolKey::Escape && self.first.is_some() { + self.forget(); + } + vec![] + } + + /// A dropped press (a canceled touch, a second finger) undoes only what that press did: a press + /// on the second segment draws nothing and the first segment stays picked, and a press that + /// picked the first segment leaves none picked. + fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + if self.press.take().is_some() { + self.found = None; + self.looked = false; + } else if std::mem::take(&mut self.picking) { + self.forget(); + } + vec![] + } + + fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { + key == ToolKey::Escape && self.first.is_some() + } + + fn notify(&mut self, _cx: &ToolContext, what: &str) { + if what == DRAWN { + self.forget(); + } + } + + /// An edit, Undo or Redo outside the tool, or another document: the first segment may be gone. + fn history_moved(&mut self) { + self.forget(); + self.hover = None; + } + + /// The segment and the circle shown depend on what lies under the pointer, which panning, + /// zooming or an edit changes. + fn wants_rehover(&self) -> bool { + true + } + + fn hover_ended(&mut self, _cx: &ToolContext) { + self.hover = None; + if self.press.is_none() { + self.found = None; + self.looked = false; + } + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + let mut out = vec![]; + if let Some(first) = &self.first { + out.push(Overlay::Path { path: segment_path(&first.curve), color: BLUE, width: 2.0, dashed: false }); + out.push(Overlay::Anchor { p: first.p, color: BLUE, filled: true, size: 7.0 }); + } + if let Some(hover) = &self.hover { + out.push(Overlay::Path { path: segment_path(&hover.curve), color: BLUE, width: 1.0, dashed: false }); + out.push(Overlay::Anchor { p: hover.p, color: BLUE, filled: false, size: 7.0 }); + } + if let Some(press) = &self.press + && press.radius.is_some() + { + out.push(Overlay::Line { a: press.at, b: self.pointer, color: GREY, dashed: false }); + } + if let Some(c) = &self.found { + let (at, r) = (c.circle.center, c.circle.radius); + // A tolerance of at least a ten-thousandth of the radius keeps a huge circle to a few + // dozen segments. + let tol = cx.tol(0.1).max(r * 1e-4); + out.push(Overlay::Path { path: kurbo::Circle::new(at, r).to_path(tol), color: RED, width: 1.0, dashed: false }); + let arm = cx.tol(4.0); + out.push(Overlay::Line { a: at - kurbo::Vec2::new(arm, 0.0), b: at + kurbo::Vec2::new(arm, 0.0), color: RED, dashed: false }); + out.push(Overlay::Line { a: at - kurbo::Vec2::new(0.0, arm), b: at + kurbo::Vec2::new(0.0, arm), color: RED, dashed: false }); + out.push(Overlay::Line { a: at, b: c.first, color: RED, dashed: true }); + out.push(Overlay::Line { a: at, b: c.second, color: RED, dashed: true }); + out.push(Overlay::Measure { p: self.pointer, text: format!("R: {}", cx.len(r)) }); + } else if self.looked { + // A label, which the canvas shows in the interface language. + out.push(Overlay::Label { p: self.pointer, text: NO_CIRCLE.into(), color: RED }); + } + out + } + + fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { + Cursor::Crosshair + } + + fn options(&self) -> Value { + json!({ "radius": self.radius }) + } + + fn set_option(&mut self, key: &str, v: &Value) { + if key == "radius" + && let Some(r) = v.as_f64().filter(|r| (RADIUS_RANGE.0..=RADIUS_RANGE.1).contains(r)) + { + self.radius = r; + } + } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "radius" => c::number(key, v, RADIUS_RANGE.0, RADIUS_RANGE.1), + _ => Err(c::unknown(key)), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::*; + use vectorcraft_doc::{Appearance, Document, Node, Selection}; + use vectorcraft_geom::{PathData, SubPath}; + + /// Two open lines, (100, 100)–(300, 100) and (100, 140)–(300, 140), and an L from (100, 300) + /// over to (300, 300) and down to (300, 400). + fn doc() -> Document { + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let lines: [&[(f64, f64)]; 3] = + [&[(100.0, 100.0), (300.0, 100.0)], &[(100.0, 140.0), (300.0, 140.0)], &[(100.0, 300.0), (300.0, 300.0), (300.0, 400.0)]]; + for pts in lines { + let id = d.alloc_id(); + let pts: Vec = pts.iter().map(|(x, y)| Point::new(*x, *y)).collect(); + d.insert(Some(l), 0, Node::path(id, PathData::single(SubPath::polyline(&pts, false)), Appearance::default_art())).unwrap(); + } + d + } + + fn ev(kind: PointerKind, x: f64, y: f64) -> PointerEvent { + PointerEvent::new(kind, x, y) + } + + fn shifted(kind: PointerKind, x: f64, y: f64) -> PointerEvent { + let mut e = ev(kind, x, y); + e.mods.shift = true; + e + } + + /// A release, with the tool told what its actions tell it, as the session does once the command + /// before the `Notify` has run. + fn up(t: &mut TangentCircleTool, cx: &ToolContext, e: &PointerEvent) -> Vec { + let acts = t.pointer(cx, e); + for a in &acts { + if let Action::Notify(what) = a { + t.notify(cx, what); + } + } + acts + } + + /// The circle an action list draws, as the box around it: (x, y, width, height). + fn drawn(actions: &[Action]) -> (f64, f64, f64, f64) { + let [Action::Exec(cmd, p), Action::Notify(what)] = actions else { panic!("{actions:?}") }; + assert_eq!((cmd.as_str(), what.as_str()), ("shape.circleThroughPoints", DRAWN)); + let pts: Vec = p["points"].as_array().unwrap().iter().map(|q| Point::new(q[0].as_f64().unwrap(), q[1].as_f64().unwrap())).collect(); + let (at, r) = vectorcraft_geom::shapes::circle_through(pts[0], pts[1], pts[2]).unwrap(); + (at.x - r, at.y - r, 2.0 * r, 2.0 * r) + } + + fn close(a: (f64, f64, f64, f64), b: (f64, f64, f64, f64)) -> bool { + [(a.0, b.0), (a.1, b.1), (a.2, b.2), (a.3, b.3)].iter().all(|(x, y)| (x - y).abs() < 1e-4) + } + + #[test] + fn two_clicks_draw_the_circle_tangent_at_the_first_click() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + assert_eq!(t.cursor(&cx, Point::ZERO, Mods::default()), Cursor::Crosshair); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)).is_empty(), "the first segment"); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)).is_empty()); + // Over the second line: the circle through (150, 100) touching it shows, 20 pt in radius. + t.pointer(&cx, &ev(PointerKind::Move, 200.0, 139.0)); + let ov = t.overlays(&cx); + assert!(ov.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("R: 20.00"))), "{ov:?}"); + assert!(ov.iter().filter(|o| matches!(o, Overlay::Line { dashed: true, .. })).count() == 2, "the radii: {ov:?}"); + // Moving along the same segment picks among the circles already found. + let kept = t.cache.clone(); + assert!(kept.as_ref().is_some_and(|(_, c)| c.len() == 1)); + t.pointer(&cx, &ev(PointerKind::Move, 250.0, 139.0)); + assert_eq!(t.cache, kept); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)).is_empty()); + let released = t.pointer(&cx, &ev(PointerKind::Up, 200.0, 139.0)); + assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "{released:?}"); + // Until the command has run and the tool is told, the first segment stays: a command that + // fails leaves it picked. + assert!(t.first.is_some() && !t.busy()); + t.notify(&cx, DRAWN); + assert!(t.first.is_none() && t.overlays(&cx).is_empty(), "ready for the next circle"); + // A quick second click on the second segment: the canvas sends its `Up` and then a + // double-click, which draws nothing more. + for (kind, x, y) in [(PointerKind::Down, 150.0, 101.0), (PointerKind::Up, 150.0, 101.0), (PointerKind::Down, 200.0, 139.0)] { + assert!(t.pointer(&cx, &ev(kind, x, y)).is_empty()); + } + let released = up(&mut t, &cx, &ev(PointerKind::Up, 200.0, 139.0)); + assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "{released:?}"); + assert!(t.pointer(&cx, &ev(PointerKind::DoubleClick, 200.0, 139.0)).is_empty()); + assert!(t.first.is_none() && !t.busy()); + } + + #[test] + fn shift_uses_the_radius_and_a_corner_takes_its_fillet() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + t.set_option("radius", &json!(10)); + assert_eq!(t.options()["radius"], json!(10.0)); + // `tool.setOption` refuses a value outside 0.01 to 1000000, or one that is not a number, + // and any other option; set anyway, such a value leaves the radius as it is. + for good in [json!(0.01), json!(36), json!(1e6)] { + assert_eq!(t.check_option("radius", &good), Ok(()), "{good}"); + } + for bad in [json!(0), json!(0.005), json!(2e6), json!(-5), json!("12"), Value::Null] { + assert_eq!(t.check_option("radius", &bad), Err("`radius` must be a number from 0.01 to 1000000".into()), "{bad}"); + t.set_option("radius", &bad); + assert_eq!(t.options()["radius"], json!(10.0), "{bad}"); + } + assert!(t.check_option("size", &json!(10)).is_err()); + // The L's two segments: the circle of radius 10 in its corner. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 300.0)); + t.pointer(&cx, &shifted(PointerKind::Down, 300.0, 350.0)); + let released = up(&mut t, &cx, &shifted(PointerKind::Up, 300.0, 350.0)); + assert!(close(drawn(&released), (280.0, 300.0, 20.0, 20.0)), "{released:?}"); + // Shift pressed or let go during a click counts at the release: with a radius of 5 no + // circle reaches the line 40 pt away, and without Shift the click's circle is 20 pt. + let mut t = TangentCircleTool::default(); + t.set_option("radius", &json!(5)); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)); + t.pointer(&cx, &shifted(PointerKind::Drag, 200.0, 139.0)); + assert!(t.pointer(&cx, &shifted(PointerKind::Up, 200.0, 139.0)).is_empty(), "nothing drawn"); + assert!(t.first.is_some()); + t.pointer(&cx, &shifted(PointerKind::Down, 200.0, 139.0)); + let released = t.pointer(&cx, &ev(PointerKind::Up, 200.0, 139.0)); + assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "{released:?}"); + } + + #[test] + fn a_drag_sets_the_radius_with_shift_steps_and_a_slow_drag() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, 300.0, 350.0)); + assert!(t.busy()); + // A drag 12.3 pt long asks for that radius; Shift rounds it (4 px at 100%: steps of 5). + assert!(t.pointer(&cx, &ev(PointerKind::Drag, 300.0, 362.3)).is_empty()); + assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Line { dashed: false, color, .. } if *color == GREY))); + assert!((t.found.unwrap().circle.radius - 12.3).abs() < 1e-6); + t.pointer(&cx, &shifted(PointerKind::Drag, 300.0, 362.3)); + assert!((t.found.unwrap().circle.radius - 10.0).abs() < 1e-9); + // Cmd/Ctrl: 10 pt more of drag adds 1 pt. + let mut slow = ev(PointerKind::Drag, 300.0, 372.3); + slow.mods.cmd = true; + t.pointer(&cx, &slow); + assert!((t.found.unwrap().circle.radius - 13.3).abs() < 1e-6, "{:?}", t.found); + let released = up(&mut t, &cx, &ev(PointerKind::Up, 300.0, 372.3)); + assert!(close(drawn(&released), (286.7 - 13.3, 300.0, 26.6, 26.6)), "{released:?}"); + // A drag back past its press asks for no radius: no circle, not one through the first click. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, 300.0, 350.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 300.0, 360.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 300.0, 350.0)); + assert!(t.found.is_none(), "{:?}", t.found); + t.pointer(&cx, &shifted(PointerKind::Drag, 300.0, 350.0)); + assert!(t.found.is_none(), "with Shift too: {:?}", t.found); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 300.0, 350.0)).is_empty()); + // A release away from the last drag event: the release sets the radius. + t.pointer(&cx, &ev(PointerKind::Down, 300.0, 350.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 300.0, 360.0)); + let released = up(&mut t, &cx, &ev(PointerKind::Up, 300.0, 365.0)); + assert!(close(drawn(&released), (300.0 - 30.0, 300.0, 30.0, 30.0)), "{released:?}"); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 300.0)); + // Cmd/Ctrl held from the start: a 20 pt drag gives 2 pt. + t.pointer(&cx, &ev(PointerKind::Down, 300.0, 350.0)); + let mut slow = ev(PointerKind::Drag, 300.0, 370.0); + slow.mods.cmd = true; + t.pointer(&cx, &slow); + assert!((t.found.unwrap().circle.radius - 2.0).abs() < 1e-6, "{:?}", t.found); + assert_eq!(round_step(2.0), 2.0); + assert_eq!(round_step(0.3), 0.5); + assert_eq!(round_step(7.0), 10.0); + } + + #[test] + fn no_circle_says_so_and_escape_forgets_the_first_segment() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + // The first segment again (on the L, whose other segment is beside it): no circle. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 300.0)); + t.pointer(&cx, &shifted(PointerKind::Move, 200.0, 300.0)); + assert!(t.found.is_none() && t.looked, "{:?}", t.found); + t.key(&cx, ToolKey::Escape, Mods::default()); + // Nothing under the pointer: nothing picked. + assert!(t.pointer(&cx, &ev(PointerKind::Down, 50.0, 50.0)).is_empty()); + assert!(t.first.is_none()); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 100.0)); + // Shift with a radius of 5: no circle reaches the line 40 pt away. + t.set_option("radius", &json!(5)); + t.pointer(&cx, &shifted(PointerKind::Move, 200.0, 140.0)); + assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == NO_CIRCLE))); + assert!(t.wants_rehover(), "the note follows what lies under a still pointer"); + t.pointer(&cx, &shifted(PointerKind::Down, 200.0, 140.0)); + assert!(t.pointer(&cx, &shifted(PointerKind::Up, 200.0, 140.0)).is_empty(), "nothing drawn"); + assert!(t.first.is_some(), "the first segment stays for another try"); + assert!(t.claims_key(&cx, ToolKey::Escape)); + t.key(&cx, ToolKey::Escape, Mods::default()); + assert!(t.first.is_none() && !t.claims_key(&cx, ToolKey::Escape)); + // An edit the tool did not make (or Undo, or another document) forgets it too. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 100.0)); + assert!(t.first.is_some()); + t.history_moved(); + assert!(t.first.is_none() && t.overlays(&cx).is_empty()); + } + + #[test] + fn a_dropped_press_undoes_only_what_it_did() { + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + // A press on the second segment, dropped: nothing drawn, and the first segment stays. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)); + assert!(t.busy()); + assert!(t.drop_press(&cx).is_empty()); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 200.0, 139.0)).is_empty(), "the release that follows draws nothing"); + assert!(t.first.is_some() && !t.busy()); + // The next click there draws the circle. + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)); + let released = t.pointer(&cx, &ev(PointerKind::Up, 200.0, 139.0)); + assert!(close(drawn(&released), (130.0, 100.0, 40.0, 40.0)), "{released:?}"); + t.notify(&cx, DRAWN); + // A press that picked the first segment, dropped: no segment stays picked. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + assert!(t.drop_press(&cx).is_empty()); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + assert!(t.first.is_none()); + // A dropped press that picked nothing leaves the first segment picked. + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 50.0, 50.0)); + assert!(t.drop_press(&cx).is_empty()); + t.pointer(&cx, &ev(PointerKind::Up, 50.0, 50.0)); + assert!(t.first.is_some()); + } + + #[test] + fn a_circle_the_three_points_cannot_draw_keeps_the_first_segment() { + // A circle the geometry found, moved to (x, 0) and given radius `r`. + let line = |y: f64| CubicBez::new(Point::new(0.0, y), Point::new(30.0, y), Point::new(60.0, y), Point::new(90.0, y)); + let found = circles_of_radius(line(0.0), &[line(40.0)], 20.0); + let circle = |x: f64, r: f64| { + let mut c = found[0]; + (c.circle.center, c.circle.radius, c.first, c.second) = (Point::new(x, 0.0), r, Point::new(x, -r), Point::new(x, r)); + c + }; + assert!(draw(&circle(100.0, 20.0), 1e-3).is_some()); + // At 10⁹ pt from the origin, where coordinates step by about 1.2e-7 pt, a radius of 5e-8 pt + // rounds the three points onto one line. + assert!(draw(&circle(1e9, 5e-8), 1e-3).is_none()); + // The preview leaves such a circle out, even nearest the pointer: no red circle for a click + // that draws nothing. + let at = Point::new(1e9, 0.0); + assert_eq!(nearest_to(vec![circle(1e9, 5e-8), circle(100.0, 20.0)], at, 1e-3), Some(circle(100.0, 20.0))); + assert_eq!(nearest_to(vec![circle(1e9, 5e-8)], at, 1e-3), None); + let d = doc(); + let (sel, p) = (Selection::default(), paint()); + let cx = cx(&d, &sel, &p); + let mut t = TangentCircleTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Up, 150.0, 101.0)); + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 139.0)); + t.found = Some(circle(1e9, 5e-8)); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 200.0, 139.0)).is_empty(), "nothing drawn"); + assert!(t.first.is_some(), "the first segment stays for another try"); + // A huge circle (segments 10³⁰ pt apart) shows with a few dozen segments, not millions. + t.found = Some(circle(0.0, 1e30)); + let segments: Vec = t + .overlays(&cx) + .iter() + .filter_map(|o| match o { + Overlay::Path { path, color, .. } if *color == RED => Some(path.elements().len()), + _ => None, + }) + .collect(); + assert!(matches!(segments[..], [n] if n < 100), "{segments:?}"); + } +} diff --git a/crates/tools/src/catalog.rs b/crates/tools/src/catalog.rs index cd6cbf627a..ed22d1be9b 100644 --- a/crates/tools/src/catalog.rs +++ b/crates/tools/src/catalog.rs @@ -34,6 +34,7 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ t("addAnchor", "Add Anchor Point Tool", Some("+"), "tool-pen-add"), t("deleteAnchor", "Delete Anchor Point Tool", Some("-"), "tool-pen-delete"), t("anchorPoint", "Anchor Point Tool", Some("Shift+C"), "tool-anchor"), + t(crate::quickpen::ID, "Quick Pen Tool", Some("Alt+P"), "tool-quick-pen"), ], &[t("curvature", "Curvature Tool", Some("Shift+~"), "tool-curvature")], &[ @@ -57,6 +58,7 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ 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(crate::curvature_circle::ID, "Curvature Circle Tool", None, "tool-curvature-circle"), t("polygon", "Polygon Tool", None, "tool-polygon"), t("star", "Star Tool", None, "tool-star"), t("flare", "Flare Tool", None, "tool-flare"), @@ -154,6 +156,48 @@ pub fn tool_info(id: &str) -> Option<&'static ToolInfo> { all_tools().find(|t| t.id == id) } +/// One sentence on what each tool does, by tool id, for the tool card that General › Show Tool Cards +/// shows on hover. +const DESCRIPTIONS: &[(&str, &str)] = &[ + ("selection", "Selects whole objects and groups to move, resize or rotate them."), + ("directSelection", "Selects anchor points and path segments to reshape a path."), + ("pen", "Draws paths point by point, with straight segments and smooth curves."), + ("curvature", "Draws smooth curves through the points you click."), + ("type", "Adds text at a point, or in a frame you drag."), + ("rectangle", "Draws rectangles and squares."), + ("roundedRectangle", "Draws rectangles with rounded corners."), + ("ellipse", "Draws ellipses and circles."), + ("polygon", "Draws polygons with sides of equal length."), + ("star", "Draws stars."), + ("rotate", "Turns objects around a reference point."), + ("reflect", "Flips objects across an axis through a reference point."), + ("scale", "Resizes objects from a reference point."), + ("shear", "Slants objects from a reference point."), + ("hand", "Moves the view of the document."), + ("zoom", "Magnifies or reduces the view."), + ("eyedropper", "Copies the color and other attributes of one object to the selection."), + ("gradient", "Sets the direction and length of a gradient."), + ("artboard", "Creates, selects and resizes artboards."), + ("width", "Changes the width of a stroke along its length."), + ("puppetWarp", "Bends art by dragging pins placed on it."), + ("warp", "Pushes the outlines of paths in the direction you drag."), + ("twirl", "Twists the outlines of paths into swirls."), + ("pucker", "Pulls the outlines of paths in toward the brush."), + ("bloat", "Pushes the outlines of paths out from the brush."), + ("scallop", "Adds curved details along the outlines of paths."), + ("crystallize", "Adds spiky details along the outlines of paths."), + ("wrinkle", "Adds wrinkles along the outlines of paths."), + ("perspectiveSelection", "Moves, copies and resizes objects on the perspective grid."), + ("blend", "Makes a series of steps between two or more objects."), + ("dimension", "Places dimension lines that show measured lengths."), +]; + +/// One sentence on what the tool does, for its tool card; none for a tool without one, which keeps +/// its one-line tool tip. +pub fn tool_description(id: &str) -> Option<&'static str> { + DESCRIPTIONS.iter().find(|(tool, _)| *tool == id).map(|&(_, text)| text) +} + /// Tool for a single-key shortcut such as "V" or "Shift+M". pub fn tool_for_shortcut(s: &str) -> Option<&'static ToolInfo> { all_tools().find(|t| t.shortcut == Some(s)) @@ -202,4 +246,15 @@ mod tests { assert!(is_selection_tool("groupSelection") && !is_selection_tool("pen")); assert!(edits_anchors("pen") && !edits_anchors("rectangle")); } + + #[test] + fn descriptions_belong_to_tools() { + for (i, (id, text)) in DESCRIPTIONS.iter().enumerate() { + assert!(tool_info(id).is_some(), "{id} is not a tool id"); + assert!(DESCRIPTIONS[..i].iter().all(|(other, _)| other != id), "{id} is described twice"); + assert_eq!(tool_description(id), Some(*text)); + } + assert_eq!(tool_description("nonsense"), None); + assert_eq!(tool_description("slice"), None); + } } diff --git a/crates/tools/src/circle.rs b/crates/tools/src/circle.rs index 9e467b35d6..40f52290f4 100644 --- a/crates/tools/src/circle.rs +++ b/crates/tools/src/circle.rs @@ -8,7 +8,8 @@ //! 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 +//! step. A press let go within 2 screen points of where it was pressed is a click, also after a +//! drag. 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 @@ -137,10 +138,11 @@ impl CircleTool { vec![Action::Exec(c, v)] } - /// Is the press a drag at `ev`: dragged already, or `ev` is [`DRAG_PX`] or more from the press? + /// Is the press let go at `ev` a drag: is `ev` [`DRAG_PX`] or more from the press? A release + /// nearer the press is a click, also after a drag that came back to it. 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), + Some(Press::First { from, .. } | Press::Second { from, .. }) => ev.pos.distance(from) >= cx.tol(DRAG_PX), None => false, } } @@ -156,9 +158,27 @@ impl Tool for CircleTool { 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 }); + // click, or a release within DRAG_PX of the press (also after a drag), keeps the points of + // the press. + if ev.kind == PointerKind::Up { + if self.drags(cx, ev) { + self.pointer(cx, &PointerEvent { kind: PointerKind::Drag, ..*ev }); + } else if let Some(press) = &mut self.press { + let (at, on_first) = match press { + Press::First { at, dragged, .. } => { + *dragged = false; + (*at, false) + } + Press::Second { at, on_first, dragged, .. } => { + *dragged = false; + (*at, *on_first) + } + }; + // A click on the first point places nothing: the pointer goes back to that point, so + // the tool shows no circle. + self.pointer = if on_first { self.first } else { Some(at) }; + self.snap.clear(); + } } match ev.kind { PointerKind::Move => { diff --git a/crates/tools/src/circle/tests.rs b/crates/tools/src/circle/tests.rs index e262d242ef..9d68bdbe27 100644 --- a/crates/tools/src/circle/tests.rs +++ b/crates/tools/src/circle/tests.rs @@ -120,6 +120,69 @@ fn a_drag_ends_where_it_is_let_go() { assert_eq!(t.pointer(&cx, &ev(up, (381.0, 360.0), Mods::default())), circle(&[(300.0, 300.0), (380.0, 360.0)])); } +/// A release within 2 screen points of the press is a click also after a drag that came back to +/// it: a second press draws the circle on the diameter to the press, a press on the first point +/// places nothing, and a first press places the first point. +#[test] +fn a_release_near_the_press_is_a_click_after_a_drag() { + 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!(drag(&mut t, &cx, (380.0, 300.0), &[(300.0, 360.0), (381.0, 300.0)], Mods::default()), circle(&[(300.0, 300.0), (380.0, 300.0)])); + click(&mut t, &cx, (300.0, 300.0)); + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(300.0, 380.0), (301.0, 300.0)], Mods::default()), vec![]); + assert!(t.ends_on_escape(&cx), "the first point stays"); + assert_eq!(click(&mut t, &cx, (380.0, 360.0)), circle(&[(300.0, 300.0), (380.0, 360.0)])); + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0), (301.0, 300.0)], Mods::default()), vec![]); + assert!(t.ends_on_escape(&cx), "the press placed the first point"); + assert_eq!(click(&mut t, &cx, (380.0, 360.0)), circle(&[(300.0, 300.0), (380.0, 360.0)])); + // Let go near the press straight from far away, the tool shows no circle to the last drag. + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (380.0, 300.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (301.0, 300.0), Mods::default())), vec![]); + assert_eq!(preview(&t.overlays(&cx)), None); + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (300.0, 380.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (301.0, 300.0), Mods::default())), vec![]); + assert_eq!(preview(&t.overlays(&cx)), None); + assert!(t.ends_on_escape(&cx)); +} + +/// A click within 3 screen points of the first point, also one dragged away and let go where it +/// was pressed, places nothing and leaves no circle shown. +#[test] +fn a_click_near_the_first_point_shows_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, (300.0, 300.0)); + assert_eq!(drag(&mut t, &cx, (302.0, 300.0), &[(302.0, 380.0), (302.0, 300.0)], Mods::default()), vec![]); + assert_eq!(preview(&t.overlays(&cx)), None); + assert_eq!(click(&mut t, &cx, (302.0, 300.0)), vec![]); + assert_eq!(preview(&t.overlays(&cx)), None); + assert!(t.ends_on_escape(&cx), "the first point stays"); + assert_eq!(click(&mut t, &cx, (380.0, 360.0)), circle(&[(300.0, 300.0), (380.0, 360.0)])); +} + +/// A press on the first point, dragged to snap to the rectangle's corner anchor and let go near +/// the press, leaves no guides of the drag. +#[test] +fn a_release_near_the_press_hides_the_guides_of_the_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, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (201.0, 201.0), Mods::default())); + assert!(!t.snap.guides().is_empty(), "the drag snapped to the corner anchor"); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (301.0, 300.0), Mods::default())), vec![]); + assert!(t.snap.guides().is_empty(), "{:?}", t.snap.guides()); +} + /// 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] diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index 0946ad7a2d..50553a87bc 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -222,6 +222,10 @@ pub struct ToolContext<'a> { pub glyph_snap: GlyphSnap, /// View → Show Corner Widget: paths show draggable Live Corners widgets in their corners. pub corner_widgets: bool, + /// The Control bar's Show Shape Widgets: selected live shapes show their corner, pie and side + /// widgets to the Selection tool and the shape tools. Direct Selection's corner widgets follow + /// [`Self::corner_widgets`] alone. + pub shape_widgets: bool, /// Which paint proxy is in front (true = Fill): the one the Gradient tool edits. pub fill_active: bool, /// The selected gradient stop (`gradient.selectStop`), marked on the gradient annotator. @@ -350,6 +354,10 @@ pub struct ToolContext<'a> { /// The objects of the Global Edit in progress (Select › Start Global Edit), the one it started /// from first, each with its transform; empty while Global Edit is off. pub global_edit: &'a [(NodeId, vectorcraft_geom::Affine)], + /// While an interaction is in progress: the document as it was when the interaction began, + /// which each preview of the interaction replaces the document with before it applies. None + /// outside an interaction. + pub interaction_doc: Option<&'a Document>, } impl ToolContext<'_> { @@ -442,6 +450,7 @@ impl ToolContext<'_> { scope: self.isolation, skip_guides: !self.guides, clip_outlines: false, + area_type_interior: false, } } diff --git a/crates/tools/src/corners.rs b/crates/tools/src/corners.rs index c60c6a7487..ab234cf507 100644 --- a/crates/tools/src/corners.rs +++ b/crates/tools/src/corners.rs @@ -132,9 +132,11 @@ impl CornerWidgets { Self::of(doc, selection, zoom, any_path)?.within_angle(max_angle) } - /// The widgets the active tool can drag (Direct Selection: `any_path`). + /// The widgets the active tool can drag (Direct Selection: `any_path`). The live shapes' widgets + /// of the other tools also need Show Shape Widgets. pub fn for_tool(cx: &ToolContext, any_path: bool) -> Option { - Self::showing(cx.doc, cx.selection, cx.zoom, any_path, cx.corner_widgets, cx.corner_widget_max_angle) + let on = cx.corner_widgets && (any_path || cx.shape_widgets); + Self::showing(cx.doc, cx.selection, cx.zoom, any_path, on, cx.corner_widget_max_angle) } /// The centres of the widgets that show. diff --git a/crates/tools/src/corners/tests.rs b/crates/tools/src/corners/tests.rs index e555782d12..21b240b453 100644 --- a/crates/tools/src/corners/tests.rs +++ b/crates/tools/src/corners/tests.rs @@ -406,6 +406,28 @@ fn widgets_off_or_elsewhere_keep_the_tools_behaviour() { assert_eq!(a[0], Action::Begin("Move".into())); } +/// With Show Shape Widgets off, a live rectangle's widgets hide from the Selection tool and the +/// shape tools, and a drag from one moves the object; Direct Selection still shows and drags them +/// while Show Corner Widget is on. +#[test] +fn hidden_shape_widgets_leave_direct_selections_corners() { + let (d, id) = live_rect(0.0, Affine::translate((100.0, 100.0))); + let s = selected(id); + let p = paint(); + let c = ToolContext { shape_widgets: false, ..cx(&d, &s, &p) }; + let at = Point::new(110.0, 110.0); + assert!(CornerWidgets::for_tool(&c, false).is_none()); + assert!(!over_widget(&c, at, false) && double_click(&c, at, false).is_none()); + assert!(CornerWidgets::for_tool(&c, true).is_some_and(|w| w.visible().count() == 4)); + assert!(over_widget(&c, at, true)); + let mut t = crate::create("selection"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 130.0, 110.0))[0], Action::Begin("Move".into())); + // Show Corner Widget off hides Direct Selection's too. + let off = ToolContext { corner_widgets: false, ..c }; + assert!(CornerWidgets::for_tool(&off, true).is_none()); +} + /// #511: Direct Selection shows a widget in each of a star's ten corners (the Selection tool /// none: a star isn't a live shape); dragging a tip's inward rounds them all as one step. #[test] diff --git a/crates/tools/src/curvature_circle.rs b/crates/tools/src/curvature_circle.rs new file mode 100644 index 0000000000..b484651181 --- /dev/null +++ b/crates/tools/src/curvature_circle.rs @@ -0,0 +1,242 @@ +//! The Curvature Circle tool draws the circle that touches a path at a point and bends as the path +//! bends there (`shape.curvatureCircle`). +//! +//! The pointer snaps to the nearest path within 5 screen points, or within Smart Guides › Snapping +//! Tolerance when that is larger, and the tool shows the circle that matches the path there: a +//! dashed outline (solid once it is more than 50,000 screen points around), its center as a small +//! cross, a line from the center to the point it touches and, with Measurement Labels on, its +//! radius by the pointer, with an asterisk when the segment is the usual cubic of a circular arc +//! of 90° or less and the circle has the arc's own radius. A click draws it, in one undo step, and a +//! press dragged 2 screen points or more, or canceled with Escape, draws nothing. The circle goes on +//! the side the path bends toward; with Shift held at the press, on the other side. On a straight +//! stretch, at a cusp, at a corner, or where the circle would reach past the canvas, the pointer +//! shows "Straight segment", "Cusp", "Corner" or "Circle too large" instead, and a click draws +//! nothing. The pointer passes over the circles the tool drew until another tool is chosen or an +//! edit, Undo or Redo is made outside the tool. + +use std::collections::HashSet; + +use serde_json::json; +use vectorcraft_doc::{MAX_COORD, NodeId}; +use vectorcraft_geom::curvature::{CurvatureCircle, NoCircle, curvature_circle_on}; +use vectorcraft_geom::{Point, Rect, Vec2, shapes}; + +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; + +pub const ID: &str = "curvatureCircle"; + +/// How near (screen points) a path pulls the pointer, unless the Smart Guides' snapping tolerance +/// is larger. +const SNAP_PX: f64 = 5.0; +/// 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; +/// The longest outline (screen points) the preview draws dashed, about 7,000 dashes. +const DASHED_PX: f64 = 50_000.0; + +/// The point of a path the pointer snapped to: the path, subpath, segment and `t` on it. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Hit { + id: NodeId, + subpath: usize, + segment: usize, + t: f64, +} + +/// What the tool shows at a hit. +enum Found { + Circle(CurvatureCircle), + /// The pointer's text, and where the path is. + Refused(&'static str, Point), +} + +#[derive(Default)] +pub struct CurvatureCircleTool { + /// The point under the pointer, and whether Shift was held. + hover: Option<(Hit, bool)>, + /// The press in progress, where the pointer was pressed: what a release draws. + press: Option<(Hit, bool)>, + from: Point, + /// The circles the tool drew since the history last moved outside it. + drawn: HashSet, +} + +/// The nearest point within reach of `p` on the paths a click can pick, guides and the paths in +/// `skip` left out; of paths at the same distance, a selected one, then the one on top. +fn hit_at(cx: &ToolContext, p: Point, skip: &HashSet) -> Option { + let tol = cx.tol(SNAP_PX).max(cx.snap_tol()); + let mut best: Option<(Hit, f64)> = None; + for id in crate::draw2::candidate_paths(cx) { + if skip.contains(&id) { + continue; + } + let Some(pd) = cx.doc.node(id).filter(|n| !n.is_guide()).and_then(|n| n.path_data()) else { continue }; + // A path whose control points' box lies out of reach holds no point within reach. + if pd.control_bounds().is_none_or(|b| !b.inflate(tol, tol).contains(p)) { + continue; + } + if let Some((subpath, segment, t, _, d)) = pd.nearest(p) + && d <= tol + && best.is_none_or(|(_, b)| d < b) + { + best = Some((Hit { id, subpath, segment, t }, d)); + } + } + best.map(|(hit, _)| hit) +} + +/// The circle at `hit` as `shape.curvatureCircle` draws it, or why it draws none; `None` when the +/// path or segment is gone. +fn found(cx: &ToolContext, hit: Hit, convex: bool) -> Option { + let sp = cx.doc.node(hit.id)?.path_data()?.subpaths.get(hit.subpath)?; + if hit.segment >= sp.segment_count() { + return None; + } + let at = vectorcraft_geom::ParamCurve::eval(&sp.segment(hit.segment), hit.t); + Some(match curvature_circle_on(sp, hit.segment, hit.t, convex) { + Ok(c) if on_canvas(&c) => Found::Circle(c), + Ok(_) => Found::Refused("Circle too large", at), + Err(NoCircle::Straight) => Found::Refused("Straight segment", at), + Err(NoCircle::Cusp) => Found::Refused("Cusp", at), + Err(NoCircle::Corner) => Found::Refused("Corner", at), + }) +} + +/// Does the circle stay on the canvas? +fn on_canvas(c: &CurvatureCircle) -> bool { + let (p, r) = (c.center, c.radius); + [p.x - r, p.y - r, p.x + r, p.y + r].iter().all(|v| v.abs() <= MAX_COORD) +} + +impl Tool for CurvatureCircleTool { + fn id(&self) -> &'static str { + ID + } + + fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + if !ev.pos.is_finite() { + return vec![]; + } + match ev.kind { + PointerKind::Move => { + self.hover = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift)); + vec![] + } + PointerKind::Down => { + self.press = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift)); + self.hover = self.press; + self.from = ev.pos; + vec![] + } + // A drag is not a click: the release draws nothing. + PointerKind::Drag => { + if ev.pos.distance(self.from) >= cx.tol(DRAG_PX) { + self.press = None; + self.hover = None; + } + vec![] + } + PointerKind::Up => { + let press = self.press.take(); + self.hover = hit_at(cx, ev.pos, &self.drawn).map(|h| (h, ev.mods.shift)); + let Some((hit, convex)) = press else { return vec![] }; + if ev.pos.distance(self.from) >= cx.tol(DRAG_PX) || !matches!(found(cx, hit, convex), Some(Found::Circle(_))) { + return vec![]; + } + let p = json!({"id": hit.id.0, "subpath": hit.subpath, "segment": hit.segment, "t": hit.t, "convex": convex}); + vec![Action::Exec("shape.curvatureCircle".into(), p), Action::Notify("created".into())] + } + PointerKind::DoubleClick | PointerKind::TripleClick => vec![], + } + } + + /// Escape during a press cancels it: the release draws nothing. + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + if key == ToolKey::Escape && self.press.take().is_some() { + self.hover = None; + } + vec![] + } + + fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { + key == ToolKey::Escape && self.press.is_some() + } + + /// A dropped press (a second finger, a canceled touch) draws nothing. + fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + self.press = None; + vec![] + } + + /// The circle shown depends on the path under the pointer, which an edit, an undo or a zoom + /// (the reach is in screen points) changes. + fn wants_rehover(&self) -> bool { + true + } + + /// The command selects the circle it drew; the tool adds it to the circles the pointer passes + /// over. + fn notify(&mut self, cx: &ToolContext, what: &str) { + if what == "created" + && let [id] = cx.selection.objects[..] + { + self.drawn.insert(id); + } + } + + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + self.hover = None; + self.press = None; + self.drawn.clear(); + vec![] + } + + fn hover_ended(&mut self, _cx: &ToolContext) { + if self.press.is_none() { + self.hover = None; + } + } + + /// An edit, Undo or Redo made outside the tool, or another document, may move or remove the + /// path under the pointer, and the pointer reaches the circles the tool drew again. + fn history_moved(&mut self) { + self.hover = None; + self.press = None; + self.drawn.clear(); + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + let Some((hit, convex)) = self.hover else { return vec![] }; + let color = crate::draw2::FEEDBACK; + let mut o = vec![]; + match found(cx, hit, convex) { + Some(Found::Circle(c)) => { + let r = c.radius; + let path = shapes::ellipse(Rect::new(c.center.x - r, c.center.y - r, c.center.x + r, c.center.y + r)).to_bezpath(); + // The outline is drawn solid when it is longer than DASHED_PX on screen. + let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX); + o.push(Overlay::Path { path, color, width: 1.0, dashed }); + o.push(Overlay::Line { a: c.center, b: c.at, color, dashed: false }); + let arm = cx.tol(CROSS_PX); + o.push(Overlay::Line { a: c.center - Vec2::new(arm, 0.0), b: c.center + Vec2::new(arm, 0.0), color, dashed: false }); + o.push(Overlay::Line { a: c.center - Vec2::new(0.0, arm), b: c.center + Vec2::new(0.0, arm), color, dashed: false }); + o.push(Overlay::Anchor { p: c.at, color, filled: true, size: 6.0 }); + if cx.measurement_labels { + let star = if c.nominal { "*" } else { "" }; + o.push(Overlay::Measure { p: c.at + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("R: {}{star}", cx.len(r)) }); + } + } + Some(Found::Refused(text, at)) => o.push(Overlay::Label { p: at, text: text.into(), color }), + None => {} + } + o + } + + fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { + Cursor::Crosshair + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/tools/src/curvature_circle/tests.rs b/crates/tools/src/curvature_circle/tests.rs new file mode 100644 index 0000000000..d417af58dc --- /dev/null +++ b/crates/tools/src/curvature_circle/tests.rs @@ -0,0 +1,286 @@ +use super::*; +use crate::testutil::*; +use vectorcraft_doc::{Appearance, Document, Node, Selection}; +use vectorcraft_geom::PathData; + +fn ev(kind: PointerKind, (x, y): (f64, f64), mods: Mods) -> PointerEvent { + PointerEvent::new(kind, x, y).with_mods(mods) +} + +/// A document holding `paths`, the first one on top. +fn doc_with(paths: &[PathData]) -> Document { + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + for path in paths.iter().rev() { + let id = d.alloc_id(); + d.insert(Some(l), usize::MAX, Node::path(id, path.clone(), Appearance::default_art())).unwrap(); + } + d +} + +/// A circle of radius 100 centered at (200, 200). +fn circle() -> PathData { + shapes::ellipse(Rect::new(100.0, 100.0, 300.0, 300.0)) +} + +fn click(t: &mut CurvatureCircleTool, cx: &ToolContext, p: (f64, f64), mods: Mods) -> Vec { + let mut acts = t.pointer(cx, &ev(PointerKind::Move, p, mods)); + acts.extend(t.pointer(cx, &ev(PointerKind::Down, p, mods))); + acts.extend(t.pointer(cx, &ev(PointerKind::Up, p, mods))); + acts +} + +/// The one command `acts` runs, followed by the tool's notice that it drew: the command's params. +fn params(acts: &[Action]) -> serde_json::Value { + let [Action::Exec(c, v), Action::Notify(what)] = acts else { panic!("one command: {acts:?}") }; + assert_eq!(c, "shape.curvatureCircle"); + assert_eq!(what, "created"); + v.clone() +} + +/// 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) +} + +fn label(o: &[Overlay]) -> Option { + o.iter().find_map(|o| match o { + Overlay::Label { text, .. } => Some(text.clone()), + _ => None, + }) +} + +/// Over a circle, the tool shows the circle itself, its center, the radius to the point it touches +/// and "R: 100 pt*" (an arc's own radius); a click draws it on the point of the path nearest the +/// pointer. +#[test] +fn a_click_on_a_circle_draws_the_circle_that_matches_it() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + t.pointer(&cx, &ev(PointerKind::Move, (302.0, 200.0), Mods::default())); + let o = t.overlays(&cx); + assert!(near(preview(&o).expect("the circle is shown"), Rect::new(100.0, 100.0, 300.0, 300.0)), "{o:?}"); + let center = Point::new(200.0, 200.0); + assert!(o.iter().any(|o| matches!(o, Overlay::Line { a, b, .. } if *a == center && b.distance(Point::new(300.0, 200.0)) < 1e-9)), "{o:?}"); + assert!(o.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("R: 100") && text.ends_with('*'))), "{o:?}"); + let without_labels = ToolContext { measurement_labels: false, ..cx }; + assert!(!t.overlays(&without_labels).iter().any(|o| matches!(o, Overlay::Measure { .. }))); + let v = params(&click(&mut t, &cx, (302.0, 200.0), Mods::default())); + assert_eq!(v["convex"], json!(false)); + let id = d.layers[0].children().unwrap()[0].id; + assert_eq!(v["id"], json!(id.0)); + let sp = &d.node(id).unwrap().path_data().unwrap().subpaths[0]; + let seg = sp.segment(v["segment"].as_u64().unwrap() as usize); + let at = vectorcraft_geom::ParamCurve::eval(&seg, v["t"].as_f64().unwrap()); + assert!(at.distance(Point::new(300.0, 200.0)) < 1e-6, "{v}"); +} + +/// Shift held at the press puts the circle on the other side of the path, and the preview follows +/// Shift too. +#[test] +fn shift_puts_the_circle_on_the_other_side() { + let d = doc_with(&[circle()]); + 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 = CurvatureCircleTool::default(); + t.pointer(&cx, &ev(PointerKind::Move, (300.0, 200.0), shift)); + assert!(near(preview(&t.overlays(&cx)).expect("the circle is shown"), Rect::new(300.0, 100.0, 500.0, 300.0)), "{:?}", t.overlays(&cx)); + assert_eq!(params(&click(&mut t, &cx, (300.0, 200.0), shift))["convex"], json!(true)); +} + +/// On a straight segment the pointer shows "Straight segment", at a cusp "Cusp", at a corner +/// anchor "Corner", and where the circle would reach past the canvas "Circle too large"; a click +/// there draws nothing. +#[test] +fn straight_segments_cusps_and_huge_circles_are_refused() { + let line = PathData::from_bezpath(&vectorcraft_geom::BezPath::from_svg("M0 400 L400 400").unwrap()); + // A handle drawn back onto its anchor at (0, 0). + let cusp = PathData::from_bezpath(&vectorcraft_geom::BezPath::from_svg("M0 0 C0 0 60 40 100 0").unwrap()); + let gentle = PathData::from_bezpath(&vectorcraft_geom::BezPath::from_svg("M0 450 C100 450.0000001 200 450.0000001 300 450").unwrap()); + // A curve that meets a line at a corner anchor (150, 250). + let corner = PathData::from_bezpath(&vectorcraft_geom::BezPath::from_svg("M0 250 C50 200 100 200 150 250 L300 250").unwrap()); + let d = doc_with(&[line, cusp, gentle, corner]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + let refused = [((200.0, 401.0), "Straight segment"), ((-1.0, -1.0), "Cusp"), ((150.0, 251.0), "Corner"), ((150.0, 451.0), "Circle too large")]; + for (at, want) in refused { + t.pointer(&cx, &ev(PointerKind::Move, at, Mods::default())); + let o = t.overlays(&cx); + assert_eq!(label(&o).as_deref(), Some(want), "{o:?}"); + assert_eq!(preview(&o), None); + assert_eq!(click(&mut t, &cx, at, Mods::default()), vec![], "{want}"); + } +} + +/// Away from every path the tool shows nothing and a click draws nothing; the pointer reaches a +/// path within 5 screen points, so at 200% within 2.5 pt. +#[test] +fn the_pointer_reaches_a_path_within_5_screen_points() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, snapping_tolerance: 0.0, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + assert_eq!(click(&mut t, &cx, (200.0, 200.0), Mods::default()), vec![]); + assert!(t.overlays(&cx).is_empty()); + assert_eq!(click(&mut t, &cx, (306.0, 200.0), Mods::default()), vec![]); + assert_eq!(click(&mut t, &cx, (304.0, 200.0), Mods::default()).len(), 2); + let zoomed = ToolContext { zoom: 2.0, ..cx }; + assert_eq!(click(&mut t, &zoomed, (303.0, 200.0), Mods::default()), vec![]); + assert_eq!(click(&mut t, &zoomed, (302.0, 200.0), Mods::default()).len(), 2); + // A larger snapping tolerance reaches farther, with Smart Guides off or on. + for smart_guides in [false, true] { + let wide = ToolContext { snapping_tolerance: 10.0, smart_guides, ..cx }; + assert_eq!(click(&mut t, &wide, (309.0, 200.0), Mods::default()).len(), 2, "{smart_guides}"); + assert_eq!(click(&mut t, &wide, (311.0, 200.0), Mods::default()), vec![], "{smart_guides}"); + } +} + +/// Of two paths within reach, the nearer one is used, even when the other one is selected: a +/// selected circle 4 pt from the pointer loses to a circle under it. +#[test] +fn the_nearest_path_wins_over_a_selected_one() { + let far = shapes::ellipse(Rect::new(104.0, 100.0, 304.0, 300.0)); + let d = doc_with(&[circle(), far]); + let ids: Vec = d.layers[0].children().unwrap().iter().map(|n| n.id).collect(); + let far_id = *ids.iter().find(|id| d.node(**id).unwrap().path_data().unwrap().bounds().unwrap().x0 > 100.5).unwrap(); + let s = Selection { objects: vec![far_id], ..Selection::default() }; + let p = paint(); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + let v = params(&click(&mut t, &cx, (300.0, 200.0), Mods::default())); + assert_ne!(v["id"], json!(far_id.0), "{v}"); +} + +/// A guide is not a path the tool draws from, even when it is selected. +#[test] +fn a_selected_guide_is_left_out() { + let mut d = doc_with(&[circle()]); + let id = d.layers[0].children().unwrap()[0].id; + if let Some(vectorcraft_doc::NodeKind::Path { guide, .. }) = d.node_mut(id).map(|n| &mut n.kind) { + *guide = true; + } + let s = Selection { objects: vec![id], ..Selection::default() }; + let p = paint(); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + assert_eq!(click(&mut t, &cx, (300.0, 200.0), Mods::default()), vec![]); + assert!(t.overlays(&cx).is_empty()); +} + +/// After a click on a circle drawn with the Ellipse tool, the next hover and click pass over the +/// circle the tool drew (selected and on top of it) and use the circle under it again, until an +/// edit made outside the tool. +#[test] +fn the_next_click_passes_over_the_circle_just_drawn() { + let d = doc_with(&[circle(), circle()]); + let ids: Vec = d.layers[0].children().unwrap().iter().rev().map(|n| n.id).collect(); + let (drawn, under) = (ids[0], ids[1]); + let s = Selection { objects: vec![drawn], ..Selection::default() }; + let p = paint(); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + t.notify(&cx, "created"); + t.pointer(&cx, &ev(PointerKind::Move, (302.0, 200.0), Mods::default())); + assert_eq!(t.hover.map(|(h, _)| h.id), Some(under)); + assert_eq!(params(&click(&mut t, &cx, (302.0, 200.0), Mods::default()))["id"], json!(under.0)); + t.history_moved(); + assert_eq!(params(&click(&mut t, &cx, (302.0, 200.0), Mods::default()))["id"], json!(drawn.0)); +} + +/// A press that a second finger or a canceled touch drops draws nothing on the release, and an +/// edit made outside the tool drops what the pointer was over. +#[test] +fn a_dropped_press_and_an_outside_edit_draw_nothing() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 200.0), Mods::default())); + t.drop_press(&cx); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 200.0), Mods::default())), vec![]); + t.pointer(&cx, &ev(PointerKind::Move, (300.0, 200.0), Mods::default())); + t.history_moved(); + assert!(t.overlays(&cx).is_empty()); +} + +/// Escape during a press cancels it, and the tool takes Escape only while a press is held; the +/// tool asks to be hovered again after an edit or a zoom. +#[test] +fn escape_cancels_a_press() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + assert!(!t.claims_key(&cx, ToolKey::Escape)); + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 200.0), Mods::default())); + assert!(t.claims_key(&cx, ToolKey::Escape)); + t.key(&cx, ToolKey::Escape, Mods::default()); + assert!(t.overlays(&cx).is_empty()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 200.0), Mods::default())), vec![]); + assert!(t.wants_rehover()); +} + +/// The preview of a circle more than 50,000 screen points around is drawn solid; a smaller one is +/// dashed. +#[test] +fn a_huge_preview_is_drawn_solid() { + let big = shapes::ellipse(Rect::new(-10_000.0, -10_000.0, 10_000.0, 10_000.0)); + let d = doc_with(&[big]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + t.pointer(&cx, &ev(PointerKind::Move, (10_001.0, 0.0), 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:?}"); +} + +/// A press dragged 2 screen points or more is not a click and draws nothing; a press that moves +/// less still draws the circle. +#[test] +fn a_drag_draws_nothing() { + let d = doc_with(&[circle()]); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CurvatureCircleTool::default(); + let press = |t: &mut CurvatureCircleTool, to: (f64, f64)| { + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 200.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, to, Mods::default())); + t.pointer(&cx, &ev(PointerKind::Up, to, Mods::default())) + }; + assert_eq!(press(&mut t, (300.0, 230.0)), vec![]); + // The circle at the press is not shown once the press is a drag; at a release away from every + // path nothing is shown. + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 200.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (250.0, 200.0), Mods::default())); + assert!(t.overlays(&cx).is_empty()); + t.pointer(&cx, &ev(PointerKind::Up, (250.0, 200.0), Mods::default())); + assert!(t.overlays(&cx).is_empty()); + assert_eq!(press(&mut t, (300.0, 202.0)), vec![]); + assert_eq!(press(&mut t, (300.0, 201.0)).len(), 2); + // A release that far away with no drag before it is not a click either. + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 200.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 230.0), Mods::default())), vec![]); +} + +/// The tool is in the Ellipse tool's group, after the Circle tool. +#[test] +fn the_curvature_circle_tool_follows_the_circle_tool() { + let tool = crate::create(ID); + assert_eq!(tool.id(), ID); + let group = crate::catalog::group_of(ID).unwrap(); + let ids: Vec<&str> = crate::TOOL_GROUPS[group].iter().map(|t| t.id).collect(); + let circle = ids.iter().position(|id| *id == crate::circle::ID).unwrap(); + assert_eq!(ids.get(circle + 1), Some(&ID)); +} diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index 3e50415434..5e2e179bdf 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,36 @@ 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 linear dimension is placed: the lines of the visible, unlocked linear dimensions in + /// the document ([`dimension_lines`]), which its line can line up with while Smart Guides are + /// on. With Smart Guides on, they are read again when the document they come from has changed. + levels: Vec, + /// Which document `levels` were read from: the open document's id and revision, or, while an + /// interaction is in progress, the open document's id and the address of the document the + /// interaction began with. + levels_at: (u64, u64, usize), + /// The document's next object id at the dimension's first preview: the id its preview takes + /// (`dimension.create` gives the dimension the next id). The preview is not a level. + preview_id: u64, } /// What a linear dimension between `a` and `b` measures with the pointer at `p` while it is @@ -170,9 +193,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 +219,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 @@ -258,6 +447,9 @@ fn on_dimensions(cx: &ToolContext, p: Point) -> Option<(Point, bool)> { } } for c in n.children().into_iter().flatten().rev() { + if *budget == 0 { + return; + } lines(c, measured, p, reach, budget, best); } } @@ -272,6 +464,9 @@ fn on_dimensions(cx: &ToolContext, p: Point) -> Option<(Point, bool)> { return; } for c in n.children().into_iter().flatten().rev() { + if *budget == 0 { + return; + } visit(c, p, reach, budget, best); } } @@ -280,11 +475,75 @@ fn on_dimensions(cx: &ToolContext, p: Point) -> Option<(Point, bool)> { } let (reach, mut budget, mut best) = ([cx.tol(ANCHOR_REACH), cx.tol(8.0)], 20_000usize, Best::default()); for n in cx.doc.layers.iter().rev() { + if budget == 0 { + break; + } visit(n, p, reach, &mut budget, &mut best); } 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 `doc`, except the preview of the +/// dimension being placed: a dimension with the id `preview.0` that measures the points +/// `preview.1`. Bounded work, as in [`on_dimensions`]. +fn dimension_lines(doc: &vectorcraft_doc::Document, preview: (u64, [Point; 2])) -> Vec { + fn visit(n: &Node, preview: (u64, [Point; 2]), budget: &mut usize, out: &mut Vec) { + let is_preview = n.id.0 == preview.0 + && n.extras().dimension.as_ref().is_some_and(|d| d.a.distance(preview.1[0]) < 1e-9 && d.b.distance(preview.1[1]) < 1e-9); + if *budget == 0 || !n.visible || n.locked || is_preview { + 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() { + if *budget == 0 { + return; + } + visit(c, preview, budget, out); + } + } + let (mut budget, mut out) = (20_000usize, vec![]); + for n in doc.layers.iter().rev() { + if budget == 0 { + break; + } + visit(n, preview, &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 +562,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 +596,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 +616,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 +721,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 +749,33 @@ 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 at the first preview and, with Smart Guides on, again when the document they come + // from has changed since. They come from the document the next preview applies to: while + // the interaction is in progress, the document as it began, which each preview starts + // again from, so a dimension that a command moves or hides in between, and that the next + // preview puts back, stays a level where it was, and the previews themselves do not make + // the tool read the lines again. The preview of this dimension is not one of them. + if d.mode == DimensionMode::Linear { + if !self.began { + self.preview_id = cx.doc.peek_next_id(); + } + let (from, at) = match cx.interaction_doc { + Some(began) => (began, (cx.revision.0, 0, std::ptr::from_ref(began).addr())), + None => (cx.doc, (cx.revision.0, cx.revision.1, 0)), + }; + if !self.began || (cx.smart_guides && self.levels_at != at) { + self.levels = dimension_lines(from, (self.preview_id, [d.a, d.b])); + self.levels_at = at; + } + } + 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 +798,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 +807,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)); @@ -609,11 +930,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![] } @@ -664,6 +988,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![] @@ -727,7 +1052,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 } }); @@ -741,6 +1066,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 } } @@ -778,6 +1118,234 @@ 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); + } + } + + /// The lines of the dimensions in the document are read only for a linear dimension. They are + /// read with Smart Guides off too, so a line placed after Smart Guides are turned on lines up. + #[test] + fn dimension_lines_are_read_only_for_a_linear_dimension() { + use vectorcraft_doc::{Node, NodeKind}; + let (mut d, _) = doc_with_rect(); + let id = d.alloc_id(); + let mut drawn = Node::new(id, NodeKind::Group { children: vec![], clip: false }); + let pt = Point::new; + drawn.extras_mut().dimension = + Some(Box::new(DimensionTool::default().recipe(DimensionMode::Linear, pt(300.0, 300.0), pt(400.0, 300.0), pt(350.0, 300.0), None))); + let l = d.layers[0].id; + d.insert(Some(l), usize::MAX, drawn).unwrap(); + let (s, p) = (Selection::default(), paint()); + let ev = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y); + let c = cx(&d, &s, &p); + let off = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = DimensionTool::default(); + for (x, y) in [(400.0, 400.0), (450.0, 400.0)] { + t.pointer(&off, &ev(PointerKind::Down, x, y)); + t.pointer(&off, &ev(PointerKind::Up, x, y)); + } + assert!(matches!(t.pointer(&off, &ev(PointerKind::Move, 420.0, 450.0)).first(), Some(Action::Begin(_)))); + assert_eq!(t.levels.len(), 1); + let acts = t.pointer(&c, &ev(PointerKind::Move, 420.0, 302.0)); + let Some(Action::Preview(_, params)) = acts.last() else { panic!("{acts:?}") }; + assert_eq!(params["offset"], json!(-100.0), "on the level of the line drawn at y = 300"); + let mut t = DimensionTool::default(); + t.set_option("mode", &json!("angular")); + t.pointer(&c, &ev(PointerKind::Down, 100.0, 100.0)); + assert!(matches!(t.pointer(&c, &ev(PointerKind::Drag, 130.0, 140.0)).first(), Some(Action::Begin(_)))); + assert!(t.levels.is_empty(), "an angular dimension reads no lines"); + // A radius (dragged outwards from a circle) and a diameter (inwards) read none either. + let circle = d.alloc_id(); + let round = vectorcraft_geom::shapes::ellipse(Rect::new(400.0, 150.0, 500.0, 250.0)); + d.insert(Some(l), usize::MAX, Node::path(circle, round, vectorcraft_doc::Appearance::default_art())).unwrap(); + let c = cx(&d, &s, &p); + for (to, mode) in [(530.0, "radius"), (470.0, "diameter")] { + let mut t = DimensionTool::default(); + t.set_option("mode", &json!("radial")); + t.pointer(&c, &ev(PointerKind::Down, 500.0, 200.0)); + let acts = t.pointer(&c, &ev(PointerKind::Drag, to, 200.0)); + assert!(matches!(acts.first(), Some(Action::Begin(_))), "{mode}: {acts:?}"); + let Some(Action::Preview(_, params)) = acts.last() else { panic!("{mode}: {acts:?}") }; + assert_eq!(params["mode"], json!(mode)); + assert!(t.levels.is_empty(), "a {mode} dimension reads no lines"); + } + } + + /// A dimension hidden, locked or deleted while another is placed is no longer a level, and one + /// shown again or grouped is: the lines are read again when the document's revision moves. The + /// preview of the dimension itself, with the id the document gave next when it began, is never + /// a level. + #[test] + fn dimension_lines_are_read_again_when_the_document_changes() { + use vectorcraft_doc::{Node, NodeKind}; + let (mut d, _) = doc_with_rect(); + let pt = Point::new; + let line = |y: f64| Some(Box::new(DimensionTool::default().recipe(DimensionMode::Linear, pt(300.0, y), pt(400.0, y), pt(350.0, y), None))); + let id = d.alloc_id(); + let mut drawn = Node::new(id, NodeKind::Group { children: vec![], clip: false }); + drawn.extras_mut().dimension = line(300.0); + let l = d.layers[0].id; + d.insert(Some(l), usize::MAX, drawn).unwrap(); + let (s, p) = (Selection::default(), paint()); + let ev = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y); + let offset = |t: &mut DimensionTool, c: &ToolContext| { + let acts = t.pointer(c, &ev(PointerKind::Move, 420.0, 302.0)); + let Some(Action::Preview(_, params)) = acts.last() else { panic!("{acts:?}") }; + params["offset"].clone() + }; + let mut t = DimensionTool::default(); + let c = cx(&d, &s, &p); + for (x, y) in [(400.0, 400.0), (450.0, 400.0)] { + t.pointer(&c, &ev(PointerKind::Down, x, y)); + t.pointer(&c, &ev(PointerKind::Up, x, y)); + } + assert!(matches!(t.pointer(&c, &ev(PointerKind::Move, 420.0, 450.0)).first(), Some(Action::Begin(_)))); + assert_eq!(offset(&mut t, &c), json!(-100.0), "on the level of the line drawn at y = 300"); + // With Smart Guides off the lines are not read; turned on, they are read as they are now. + let mut hidden = d.clone(); + hidden.node_mut(id).unwrap().visible = false; + let off = ToolContext { revision: (0, 1), smart_guides: false, ..cx(&hidden, &s, &p) }; + offset(&mut t, &off); + assert_eq!(t.levels.len(), 1, "not read with Smart Guides off"); + let on = ToolContext { revision: (0, 1), ..cx(&hidden, &s, &p) }; + assert_eq!(offset(&mut t, &on), json!(-98.0), "read when Smart Guides are turned on"); + for (rev, edit) in [(1, "hidden"), (2, "locked"), (3, "deleted")] { + let mut doc = d.clone(); + match edit { + "hidden" => doc.node_mut(id).unwrap().visible = false, + "locked" => doc.node_mut(id).unwrap().locked = true, + _ => { + doc.remove(id).unwrap(); + } + } + let c = ToolContext { revision: (0, rev), ..cx(&doc, &s, &p) }; + assert_eq!(offset(&mut t, &c), json!(-98.0), "{edit}: off every level"); + } + let c = ToolContext { revision: (0, 4), ..cx(&d, &s, &p) }; + assert_eq!(offset(&mut t, &c), json!(-100.0), "shown again: on the level"); + // Grouped while it is placed, in a group with the id the preview takes: still a level. + let mut doc = d.clone(); + let moved = doc.remove(id).unwrap(); + let group = doc.alloc_id(); + doc.insert(Some(l), usize::MAX, Node::new(group, NodeKind::Group { children: vec![moved], clip: false })).unwrap(); + let c = ToolContext { revision: (0, 5), ..cx(&doc, &s, &p) }; + assert_eq!(offset(&mut t, &c), json!(-100.0), "grouped: on the level"); + // The dimension's own preview, which takes the next id and measures its points, is not a + // level. Another dimension that takes that id is. + let mut own = DimensionTool::default().recipe(DimensionMode::Linear, pt(400.0, 400.0), pt(450.0, 400.0), pt(425.0, 400.0), None); + own.place(pt(425.0, 304.0)); + assert_eq!(own.line_ends(), (pt(400.0, 304.0), pt(450.0, 304.0))); + for (rev, made, level) in [(6, Some(Box::new(own)), json!(-98.0)), (7, line(304.0), json!(-96.0))] { + let mut doc = d.clone(); + let mut preview = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![], clip: false }); + preview.extras_mut().dimension = made; + doc.node_mut(id).unwrap().visible = false; + doc.insert(Some(l), usize::MAX, preview).unwrap(); + let c = ToolContext { revision: (0, rev), ..cx(&doc, &s, &p) }; + assert_eq!(offset(&mut t, &c), level, "revision {rev}"); + } + } + + /// While the interaction is in progress, the lines are read from the document it began with, + /// which the next preview starts from, not from the document a command changed in between: a + /// dimension moved or hidden there stays a level where it was. + #[test] + fn dimension_lines_are_read_from_the_document_the_preview_applies_to() { + use vectorcraft_doc::{Node, NodeKind}; + let (mut d, _) = doc_with_rect(); + let pt = Point::new; + let line = |y: f64| Some(Box::new(DimensionTool::default().recipe(DimensionMode::Linear, pt(300.0, y), pt(400.0, y), pt(350.0, y), None))); + let id = d.alloc_id(); + let mut drawn = Node::new(id, NodeKind::Group { children: vec![], clip: false }); + drawn.extras_mut().dimension = line(300.0); + let l = d.layers[0].id; + d.insert(Some(l), usize::MAX, drawn).unwrap(); + let (s, p) = (Selection::default(), paint()); + let ev = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y); + let offset = |t: &mut DimensionTool, c: &ToolContext, y: f64| { + let acts = t.pointer(c, &ev(PointerKind::Move, 420.0, y)); + let Some(Action::Preview(_, params)) = acts.last() else { panic!("{acts:?}") }; + params["offset"].clone() + }; + let mut t = DimensionTool::default(); + let c = cx(&d, &s, &p); + for (x, y) in [(400.0, 400.0), (450.0, 400.0)] { + t.pointer(&c, &ev(PointerKind::Down, x, y)); + t.pointer(&c, &ev(PointerKind::Up, x, y)); + } + assert!(matches!(t.pointer(&c, &ev(PointerKind::Move, 420.0, 450.0)).first(), Some(Action::Begin(_)))); + for (rev, edit) in [(1, "moved"), (2, "hidden")] { + let mut doc = d.clone(); + match edit { + "moved" => doc.node_mut(id).unwrap().extras_mut().dimension = line(320.0), + _ => doc.node_mut(id).unwrap().visible = false, + } + let c = ToolContext { revision: (0, rev), interaction_doc: Some(&d), ..cx(&doc, &s, &p) }; + assert_eq!(offset(&mut t, &c, 318.0), json!(-82.0), "{edit}: not on the level at y = 320"); + assert_eq!(offset(&mut t, &c, 302.0), json!(-100.0), "{edit}: on the level at y = 300"); + } + // A revision that moves with the same document the interaction began with does not read + // the lines again; another document it began with does. + t.levels.clear(); + let c = ToolContext { revision: (0, 3), interaction_doc: Some(&d), ..cx(&d, &s, &p) }; + assert_eq!(offset(&mut t, &c, 302.0), json!(-98.0), "not read again"); + let again = d.clone(); + let c = ToolContext { revision: (0, 4), interaction_doc: Some(&again), ..cx(&d, &s, &p) }; + assert_eq!(offset(&mut t, &c, 302.0), json!(-100.0), "read again"); + } + + /// The preview of the dimension itself does not count toward the 20,000 objects read: a + /// dimension that was the last one read stays a level once the preview is in front of it. + #[test] + fn the_preview_does_not_push_the_last_dimension_read_out_of_reach() { + use std::sync::Arc; + use vectorcraft_doc::{Node, NodeKind}; + let (mut d, _) = doc_with_rect(); + let pt = Point::new; + let line = |y: f64| Some(Box::new(DimensionTool::default().recipe(DimensionMode::Linear, pt(300.0, y), pt(400.0, y), pt(350.0, y), None))); + let mut drawn = Node::new(d.alloc_id(), NodeKind::Group { children: vec![], clip: false }); + drawn.extras_mut().dimension = line(300.0); + // The layer, the group and 19,997 empty groups before the dimension: it is the 20,000th. + let mut children = vec![Arc::new(drawn)]; + children.extend((0..19_997).map(|_| Arc::new(Node::new(d.alloc_id(), NodeKind::Group { children: vec![], clip: false })))); + let l = d.layers[0].id; + let group = Node::new(d.alloc_id(), NodeKind::Group { children, clip: false }); + d.insert(Some(l), usize::MAX, group).unwrap(); + let (s, p) = (Selection::default(), paint()); + let ev = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y); + let offset = |t: &mut DimensionTool, c: &ToolContext| { + let acts = t.pointer(c, &ev(PointerKind::Move, 420.0, 302.0)); + let Some(Action::Preview(_, params)) = acts.last() else { panic!("{acts:?}") }; + params["offset"].clone() + }; + let mut t = DimensionTool::default(); + let c = cx(&d, &s, &p); + for (x, y) in [(400.0, 400.0), (450.0, 400.0)] { + t.pointer(&c, &ev(PointerKind::Down, x, y)); + t.pointer(&c, &ev(PointerKind::Up, x, y)); + } + assert!(matches!(t.pointer(&c, &ev(PointerKind::Move, 420.0, 450.0)).first(), Some(Action::Begin(_)))); + assert_eq!(offset(&mut t, &c), json!(-100.0), "the 20,000th object is read"); + let mut previewed = d.clone(); + let mut preview = Node::new(previewed.alloc_id(), NodeKind::Group { children: vec![], clip: false }); + preview.extras_mut().dimension = + Some(Box::new(DimensionTool::default().recipe(DimensionMode::Linear, pt(400.0, 400.0), pt(450.0, 400.0), pt(425.0, 304.0), None))); + previewed.insert(Some(l), usize::MAX, preview).unwrap(); + let c = ToolContext { revision: (0, 1), ..cx(&previewed, &s, &p) }; + assert_eq!(offset(&mut t, &c), json!(-100.0), "still read with the preview in front"); + } + #[test] fn a_dropped_placement_press_does_not_commit_the_dimension() { let (d, _) = doc_with_rect(); @@ -937,6 +1505,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 66cc842a53..e1c0c88dae 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -69,6 +69,18 @@ use crate::rulerguide::GuideEdit; use crate::select::{MoveSnap, hit_center, hold_point, is_area_type, is_path_type, matrix_json, release_guide_at, selection_bounds}; use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; +/// An ordinary path's handle drag keeps its owner across previews, which each start at Begin. +#[derive(Clone, Debug)] +struct HandleDrag { + at: Point, + last: Point, + handle: Point, + offset: Vec2, + space: bool, + independent: bool, + translated: bool, +} + #[derive(Clone, Debug)] enum State { Idle, @@ -107,6 +119,7 @@ enum State { si: usize, ai: usize, out: bool, + drag: Option, }, Marquee { start: Point, @@ -885,7 +898,22 @@ impl Tool for DirectSelectionTool { self.mesh.unfocus(); } if let Some((id, si, ai, out)) = hit_handle(cx, p, point) { - self.state = State::Handle { id, si, ai, out }; + let drag = cx.doc.node(id).and_then(|n| match &n.kind { + NodeKind::Path { path, .. } => { + let a = path.subpaths.get(si)?.anchors.get(ai)?; + Some(HandleDrag { + at: a.p, + last: p, + handle: if out { a.h_out } else { a.h_in }, + offset: Vec2::ZERO, + space: false, + independent: false, + translated: false, + }) + } + _ => None, + }); + self.state = State::Handle { id, si, ai, out, drag }; self.handle_snap = HandleSnap::default(); return vec![Action::Begin("Reshape".into())]; } @@ -978,7 +1006,8 @@ impl Tool for DirectSelectionTool { self.state = State::TypeArea { items, start, began: true }; out } - (PointerKind::Drag, State::Handle { id, si, ai, out }) => { + (PointerKind::Drag, State::Handle { id, si, ai, out, drag: Some(drag) }) => self.drag_handle(cx, ev, p, (id, si, ai, out), drag), + (PointerKind::Drag, State::Handle { id, si, ai, out, drag: None }) => { let (q, guides) = self.handle_snap.snap(cx, (id, si, ai), p, ev.mods.shift); self.snapped = snapped(q.to_vec2(), p.to_vec2(), ev.mods.shift, &guides); self.guides = guides; @@ -1504,6 +1533,57 @@ impl DirectSelectionTool { } vec![] } + /// Update one ordinary-path handle preview, retaining its Space translation phase. + fn drag_handle( + &mut self, + cx: &ToolContext, + ev: &PointerEvent, + p: Point, + (id, si, ai, out): (NodeId, usize, usize, bool), + mut drag: HandleDrag, + ) -> Vec { + let delta = p - drag.last; + if ev.mods.space { + drag.at += delta; + drag.handle += delta; + if delta != Vec2::ZERO { + drag.translated = true; + // Handle targets include this path's anchors, which just moved. + self.handle_snap = HandleSnap::default(); + } + self.snapped = false; + self.guides.clear(); + } else { + if drag.space { + // Resume at the accepted handle even when it was snapped away from the pointer. + drag.offset = drag.handle - drag.last; + self.handle_snap = HandleSnap::default(); + self.snapped = false; + self.guides.clear(); + } + // Releasing Space without moving must not reshape the translated handles. + if !drag.space || delta != Vec2::ZERO { + let input = p + drag.offset; + let (q, guides) = self.handle_snap.snap(cx, (id, si, ai), input, ev.mods.shift); + self.snapped = snapped(q.to_vec2(), input.to_vec2(), ev.mods.shift, &guides); + self.guides = guides; + drag.handle = q; + drag.independent = ev.mods.alt; + } + } + drag.last = p; + drag.space = ev.mods.space; + let mut params = json!({ + "id": id.0, "subpath": si, "anchor": ai, "which": if out { "out" } else { "in" }, + "x": drag.handle.x, "y": drag.handle.y, "independent": drag.independent, + }); + if drag.translated { + params["at"] = json!([drag.at.x, drag.at.y]); + } + self.state = State::Handle { id, si, ai, out, drag: Some(drag) }; + vec![Action::Preview("path.setHandle".into(), params)] + } + fn drag_move_anchors( &mut self, cx: &ToolContext, @@ -1674,7 +1754,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 }; @@ -1684,8 +1764,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)); @@ -1773,7 +1856,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![])); @@ -1785,7 +1868,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 50244eb260..4f3b795921 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -2767,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/width.rs b/crates/tools/src/distort/width.rs index 005b8e9473..b2050dbbdf 100644 --- a/crates/tools/src/distort/width.rs +++ b/crates/tools/src/distort/width.rs @@ -7,8 +7,9 @@ //! either onto another width point makes a discontinuous point (the width steps there). Shift-click //! adds width points to the selection (or takes them out), and dragging one of several selected //! points moves or widens them all. Double-clicking a stroke opens Width Point Edit (the -//! `widthPoint` dialog), editing a hit point or creating one on confirmation. Delete/Backspace -//! removes the selected width points. +//! `widthPoint` dialog), editing a hit point or creating one on confirmation; on one of several +//! selected points it edits all of them (`indices`). Delete/Backspace removes the selected width +//! points. //! //! Gestures preview `stroke.widthPoint.set {id, t, left, right, index?}` (side widths in points), //! `stroke.widthPoint.copy {id, index, t}` or, for several points, `stroke.widthProfile.set {ids, @@ -117,6 +118,9 @@ 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 width points selected before a click on one of them selected just that one, and + /// whether the button has gone down again since: a double-click on that point edits them all. + before_click: Option<((NodeId, Vec), bool)>, /// 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>, @@ -360,6 +364,9 @@ impl Tool for WidthTool { } PointerKind::TripleClick => vec![], PointerKind::DoubleClick => { + // The double-click's first click selected just the point under it: the points + // selected before it are selected again. + let before_click = self.before_click.take().and_then(|(sel, pressed)| pressed.then_some(sel)); let spot = match self.edit_spot_at(cx, p) { Ok(spot) => spot, Err(false) => return vec![], @@ -374,11 +381,32 @@ impl Tool for WidthTool { self.selected = Some((spot.owner, vec![spot.t])); return vec![Action::Dialog("widthPoint".into(), json!({"id": spot.owner.0, "t": spot.t}))]; }; - self.selected = Some((spot.owner, vec![w.t])); - vec![Action::Dialog("widthPoint".into(), json!({"id": spot.owner.0, "index": w.index, "adjustAdjoining": ev.mods.shift}))] + if let Some((owner, ts)) = before_click + && owner == spot.owner + && self.is_selected(owner, w.t) + && ts.iter().any(|t| (t - w.t).abs() <= SAME_T) + { + self.selected = Some((owner, ts)); + } + // A selected point edits every selected point; another one edits itself alone. + if !self.is_selected(spot.owner, w.t) { + self.selected = Some((spot.owner, vec![w.t])); + } + // Every selected entry goes to the dialog, which opens one point (or the two + // halves of a discontinuous point) as `index` would. + let indices = self.selected_indices(cx, spot.owner); + let mut params = json!({"id": spot.owner.0, "adjustAdjoining": ev.mods.shift}); + if indices.len() > 1 { + params["indices"] = json!(indices); + } else { + params["index"] = json!(w.index); + } + vec![Action::Dialog("widthPoint".into(), params)] } PointerKind::Down => { self.before_press = self.selected.clone(); + // Only the press right after the click counts as the double-click's second one. + self.before_click = self.before_click.take().filter(|(_, pressed)| !pressed).map(|(sel, _)| (sel, true)); let spot = match self.edit_spot_at(cx, p) { Ok(spot) => spot, Err(brushed) => { @@ -455,7 +483,14 @@ impl Tool for WidthTool { let dt = d.t - d.spot.t; self.selected = match (d.group.is_some(), d.moved, self.selected.take()) { // A click on one of several selected points selects just that one. - (true, false, _) if !ev.mods.shift => Some((d.spot.owner, vec![d.spot.t])), + (true, false, sel) if !ev.mods.shift => { + // Only a selection of several places: a discontinuous point alone also + // drags as a group, and its click must not replace the remembered one. + if let Some(sel) = sel.filter(|(_, ts)| ts.len() > 1) { + self.before_click = Some((sel, false)); + } + Some((d.spot.owner, vec![d.spot.t])) + } // Points moved together stay selected. (true, _, Some((id, ts))) if d.mode == Mode::Move => Some((id, ts.into_iter().map(|t| (t + dt).clamp(0.0, 1.0)).collect())), (true, _, sel) => sel, @@ -1037,4 +1072,74 @@ mod tests { assert!(t.pointer(&c, &ev(PointerKind::DoubleClick, 120.0, 250.0, mods)).is_empty(), "not on a stroked path"); } } + + #[test] + fn double_click_on_one_of_several_selected_points_edits_them_all() { + let (d, id) = doc_three_points(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let (none, shift) = (Mods::default(), Mods { shift: true, ..Default::default() }); + let click = |t: &mut WidthTool, x: f64, mods: Mods| { + t.pointer(&c, &ev(PointerKind::Down, x, 200.0, mods)); + t.pointer(&c, &ev(PointerKind::Up, x, 200.0, mods)); + }; + // The events a double-click sends: two clicks, then the double-click. + let double_click = |t: &mut WidthTool, x: f64, mods: Mods| { + click(t, x, mods); + click(t, x, mods); + match t.pointer(&c, &ev(PointerKind::DoubleClick, x, 200.0, mods)).as_slice() { + [Action::Dialog(kind, v)] if kind == "widthPoint" => v.clone(), + acts => panic!("expected Width Point Edit: {acts:?}"), + } + }; + for mods in [none, shift] { + let mut t = WidthTool::default(); + click(&mut t, 150.0, none); + click(&mut t, 250.0, shift); + let v = double_click(&mut t, 250.0, mods); + assert_eq!((&v["id"], &v["indices"]), (&json!(id.0), &json!([1, 3])), "{mods:?}"); + assert!(v.get("index").is_none()); + assert_eq!(v["adjustAdjoining"], json!(mods.shift)); + assert_eq!(t.selected_indices(&c, id), vec![1, 3], "the selection is kept"); + // A point outside the selection edits itself alone, and is selected alone. + let v = double_click(&mut t, 200.0, none); + assert_eq!(v["index"], json!(2)); + assert!(v.get("indices").is_none()); + assert_eq!(t.selected_indices(&c, id), vec![2]); + } + // A discontinuous point among them keeps both halves, and double-clicking it keeps the others. + let (mut d2, _) = doc_line(); + let points = vec![(0.0, 1.0, 1.0), (0.25, 1.0, 1.0), (0.5, 1.0, 1.0), (0.5, 2.0, 2.0), (0.75, 1.0, 1.0), (1.0, 1.0, 1.0)]; + d2.node_mut(id).unwrap().appearance.stroke_mut().unwrap().profile = Some(WidthProfile { points }); + let c2 = cx(&d2, &s, &p); + let mut t = WidthTool::default(); + for (x, mods) in [(150.0, none), (200.0, shift), (200.0, none), (200.0, none)] { + t.pointer(&c2, &ev(PointerKind::Down, x, 200.0, mods)); + t.pointer(&c2, &ev(PointerKind::Up, x, 200.0, mods)); + } + let acts = t.pointer(&c2, &ev(PointerKind::DoubleClick, 200.0, 200.0, none)); + let [Action::Dialog(_, v)] = acts.as_slice() else { panic!("expected Width Point Edit: {acts:?}") }; + assert_eq!(v["indices"], json!([1, 2, 3])); + // Three points at nearly one place are selected together and all go to the dialog. + let (mut d3, _) = doc_line(); + let points = vec![(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (0.5000005, 2.0, 2.0), (0.5000009, 3.0, 3.0), (1.0, 1.0, 1.0)]; + d3.node_mut(id).unwrap().appearance.stroke_mut().unwrap().profile = Some(WidthProfile { points }); + let c3 = cx(&d3, &s, &p); + let mut t = WidthTool::default(); + for _ in 0..2 { + t.pointer(&c3, &ev(PointerKind::Down, 200.0, 200.0, none)); + t.pointer(&c3, &ev(PointerKind::Up, 200.0, 200.0, none)); + } + let acts = t.pointer(&c3, &ev(PointerKind::DoubleClick, 200.0, 200.0, none)); + let [Action::Dialog(_, v)] = acts.as_slice() else { panic!("expected Width Point Edit: {acts:?}") }; + assert_eq!(v["indices"], json!([1, 2, 3])); + // A click on one of the selected points, then a double-click on it later, edits that point. + let mut t = WidthTool::default(); + click(&mut t, 150.0, none); + click(&mut t, 250.0, shift); + click(&mut t, 250.0, none); + click(&mut t, 200.0, none); + let v = double_click(&mut t, 250.0, none); + assert_eq!(v["index"], json!(3)); + } } diff --git a/crates/tools/src/draw2.rs b/crates/tools/src/draw2.rs index 9401dcd4c2..3c663006e5 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). @@ -365,7 +366,7 @@ pub(crate) fn walk_pickable<'a>(cx: &ToolContext<'a>, mut f: impl FnMut(&'a vect } /// Editable path nodes, selected ones first, then the rest top-most first ([`walk_pickable`]). -fn candidate_paths(cx: &ToolContext) -> Vec { +pub(crate) fn candidate_paths(cx: &ToolContext) -> Vec { let mut v: Vec = cx.selection.objects.iter().copied().filter(|id| cx.doc.node(*id).is_some_and(|n| n.path_data().is_some())).collect(); let mut rest = vec![]; walk_pickable(cx, |n| { @@ -374,8 +375,9 @@ fn candidate_paths(cx: &ToolContext) -> Vec { } }); rest.reverse(); + let mut seen: std::collections::HashSet = v.iter().copied().collect(); for id in rest { - if !v.contains(&id) { + if seen.insert(id) { v.push(id); } } diff --git a/crates/tools/src/draw2/anchor.rs b/crates/tools/src/draw2/anchor.rs index 3389746f2d..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 { @@ -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/gesture.rs b/crates/tools/src/draw2/gesture.rs index 75f0fde6d6..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![], diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 3ebc50cd02..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 @@ -3096,7 +3201,7 @@ fn the_eraser_tip_follows_its_variation_modes() { assert_eq!(t.check_option(k, &json!(mode.id())), Ok(()), "{k} {mode:?}"); } } - let modes = "must be one of `fixed`, `random`, `pressure`, `tilt`, `bearing`, `rotation`"; + 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())); @@ -3111,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)); @@ -3148,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] @@ -3167,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)); @@ -3193,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)); @@ -3206,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)); @@ -3242,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) }); }; @@ -3283,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)); @@ -3333,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) }); }; @@ -3424,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 5eed055eaa..d9d210096e 100644 --- a/crates/tools/src/extra.rs +++ b/crates/tools/src/extra.rs @@ -6,7 +6,9 @@ //! on macOS) draws a flare there with them at once), then a click sets the //! end point of the rings (↑/↓ add or remove rings and ~ places them anew); Space held during //! either drag moves the flare. The rest comes -//! from the tool's options (the Flare Tool Options, which last). Reshape: a click on a selected +//! from the tool's options (the Flare Tool Options, which last). With one flare selected, the tool +//! shows its center and end handles, and dragging either changes the flare's length and direction +//! (`shape.editFlare`). Reshape: a click on a selected //! path sets a focal point (adding an anchor on a segment), Shift-click adds or removes more, and //! a drag from a focal point moves them all; the engine's `path.reshape` stretches the selected //! anchors between them and the anchors that stay. @@ -83,6 +85,40 @@ pub struct FlareTool { /// Whether the flare has rays and rings (the options' Rays and Rings checkboxes). rays_on: bool, rings_on: bool, + /// A drag of the selected flare's center or end handle. + handle: Option, +} + +/// A drag of a selected flare's handle: the flare, whether it is the end handle (else the center), +/// where the handle was, where it was pressed, whether Alt (Option on macOS) was held at the press +/// and whether the drag has begun its undo step. +#[derive(Clone, Copy, Debug)] +struct HandleDrag { + id: vectorcraft_doc::NodeId, + end: bool, + from: Point, + at: Point, + alt: bool, + began: bool, +} + +/// The flare whose handles the Flare tool shows: the one selected object, when it is a flare that +/// can be edited, with its center and the rings' end point. +fn selected_flare(cx: &ToolContext) -> Option<(vectorcraft_doc::NodeId, Point, Point)> { + let [id] = cx.selection.objects.as_slice() else { return None }; + if !cx.doc.is_editable(*id) { + return None; + } + let node = cx.doc.node(*id)?; + let spec = node.extras().flare.as_deref().filter(|spec| spec.draws(node))?; + Some((*id, spec.center()?, spec.end()?)) +} + +/// `shape.editFlare`'s params for handle drag `h` with the pointer at `pointer`: the handle moves +/// as far as the pointer has. +fn handle_params(h: HandleDrag, pointer: Point) -> Value { + let p = h.from + (pointer - h.at); + if h.end { json!({ "ids": [h.id.0], "x2": p.x, "y2": p.y }) } else { json!({ "ids": [h.id.0], "cx": p.x, "cy": p.y }) } } impl Default for FlareTool { @@ -104,6 +140,7 @@ impl Default for FlareTool { values: FLARE_OPTIONS.map(|(_, default, _, _)| default), rays_on: true, rings_on: true, + handle: None, } } } @@ -251,7 +288,7 @@ impl Tool for FlareTool { "flare" } fn busy(&self) -> bool { - self.drag.is_some() || self.placed.is_some() + self.drag.is_some() || self.placed.is_some() || self.handle.is_some() } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { self.hover = ev.pos; @@ -261,8 +298,43 @@ impl Tool for FlareTool { if quote_pressed && self.rings_on && self.placed.is_some() && matches!(ev.kind, PointerKind::Drag | PointerKind::Move | PointerKind::Up) { self.ring_seed = Some(next_ring_seed(self.ring_seed, ev.pos)); } + if let Some(mut h) = self.handle { + return match ev.kind { + PointerKind::Drag if h.began => vec![Action::Preview("shape.editFlare".into(), handle_params(h, ev.pos))], + PointerKind::Drag if ev.pos.distance(h.at) < cx.tol(3.0) => vec![], + PointerKind::Drag => { + h.began = true; + self.handle = Some(h); + vec![Action::Begin("Edit Flare".into()), Action::Preview("shape.editFlare".into(), handle_params(h, ev.pos))] + } + PointerKind::Up => { + self.handle = None; + if h.began { + vec![Action::Preview("shape.editFlare".into(), handle_params(h, ev.pos)), Action::Commit] + } else if h.alt { + // A click on a handle without a drag is a click with the tool. + self.click_flare(cx, h.at) + } else { + vec![Action::Dialog("flare".into(), json!({ "x": h.at.x, "y": h.at.y }))] + } + } + _ => vec![], + }; + } match ev.kind { PointerKind::Down => { + // A press on the selected flare's center or end handle drags that handle. + if self.placed.is_none() + && let Some((id, c, e)) = selected_flare(cx) + { + let tol = cx.tol(4.0); + let (dc, de) = (ev.pos.distance(c), ev.pos.distance(e)); + if dc.min(de) <= tol { + let end = de < dc; + self.handle = Some(HandleDrag { id, end, from: if end { e } else { c }, at: ev.pos, alt: ev.mods.alt, began: false }); + return vec![]; + } + } if self.placed.is_none() { self.drag = Some((ev.pos, ev.pos)); self.rays = None; @@ -350,6 +422,11 @@ impl Tool for FlareTool { }; return vec![Action::Preview("shape.flare".into(), preview)]; } + if key == ToolKey::Escape + && let Some(h) = self.handle.take() + { + return if h.began { vec![Action::Cancel] } else { vec![] }; + } if key == ToolKey::Escape && self.busy() { self.rays = None; self.rings = None; @@ -367,16 +444,27 @@ impl Tool for FlareTool { // Switching away after the centre drag keeps the flare with the rings its options give. self.drag = None; self.held = None; + if self.handle.take().is_some_and(|h| h.began) { + return vec![Action::Commit]; + } if self.placed.take().is_some() && std::mem::take(&mut self.began) { vec![Action::Commit] } else { vec![] } } - fn overlays(&self, _cx: &ToolContext) -> Vec { + fn overlays(&self, cx: &ToolContext) -> Vec { match (self.drag, self.placed) { (Some((c, p)), _) => { let r = self.center_diameter(p.distance(c)) / 2.0; vec![Overlay::Path { path: ellipse_path(c, r, r, 0.0), color: BLUE, width: 1.0, dashed: false }] } (_, Some((c, _))) => vec![Overlay::Line { a: c, b: self.hover, color: BLUE, dashed: true }], - _ => vec![], + // The selected flare's center and end handles. + _ => match selected_flare(cx) { + Some((_, c, e)) => vec![ + Overlay::Line { a: c, b: e, color: BLUE, dashed: true }, + Overlay::Anchor { p: c, color: BLUE, filled: self.handle.is_some_and(|h| !h.end), size: 7.0 }, + Overlay::Anchor { p: e, color: BLUE, filled: self.handle.is_some_and(|h| h.end), size: 7.0 }, + ], + None => vec![], + }, } } fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { @@ -1021,6 +1109,69 @@ mod tests { assert_eq!(t.turn, 10.0); } + /// With one flare selected, the tool shows its center and end handles where the flare is now + /// drawn, and dragging either edits the flare (`shape.editFlare`) as one undo step; a press + /// away from them draws a new flare. + #[test] + fn dragging_a_selected_flares_handles_changes_its_length_and_direction() { + use crate::testutil::*; + use vectorcraft_doc::flare::{FlareSpec, part_node, parts}; + use vectorcraft_doc::{Node, Selection}; + let (mut d, _) = doc_with_rect(); + let gid = d.alloc_id(); + let v = json!({ "cx": 100.0, "cy": 100.0, "x2": 300.0, "y2": 100.0, "rays": 3, "rings": 2, "seed": 5, "diameter": 30.0, + "opacity": 50.0, "brightness": 30.0, "growth": 20.0, "fuzziness": 50.0, "longest": 300.0, "rayFuzziness": 100.0, + "rotation": 0.0, "largest": 50.0 }); + let xf = vectorcraft_geom::Affine::translate((10.0, 20.0)); + let children: Vec<_> = parts(&v).into_iter().map(|part| std::sync::Arc::new(part_node(d.alloc_id(), part, xf, false))).collect(); + let edited = children[0].id; + let mut g = Node::group(gid, children); + g.extras_mut().flare = Some(Box::new(FlareSpec { params: v, transform: xf })); + let layer = d.layers[0].id; + d.insert(Some(layer), usize::MAX, g).unwrap_or_else(|e| panic!("{e}")); + let s = Selection { objects: vec![gid], ..Default::default() }; + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = FlareTool::default(); + let ov = t.overlays(&cx); + let anchors: Vec = ov.iter().filter_map(|o| if let Overlay::Anchor { p, .. } = o { Some(*p) } else { None }).collect(); + assert_eq!(anchors, vec![Point::new(110.0, 120.0), Point::new(310.0, 120.0)]); + // The end handle, grabbed 2 points off: it moves as far as the pointer. + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 312.0, 120.0)).is_empty()); + assert!(t.busy()); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 312.0, 160.0)); + assert_eq!(a.first(), Some(&Action::Begin("Edit Flare".into()))); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 302.0, 200.0)); + assert_eq!(a, vec![Action::Preview("shape.editFlare".into(), json!({ "ids": [gid.0], "x2": 300.0, "y2": 200.0 })), Action::Commit]); + // The center handle; Escape cancels its drag. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 110.0, 121.0)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 150.0, 121.0)); + assert_eq!(a.last(), Some(&Action::Preview("shape.editFlare".into(), json!({ "ids": [gid.0], "cx": 150.0, "cy": 120.0 })))); + assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel]); + assert!(!t.busy()); + // A click on a handle without a drag is a click with the tool: it opens the dialog, and + // with Alt held it draws a flare there with the tool's options. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 110.0, 120.0)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 110.0, 120.0)); + assert_eq!(a, vec![Action::Dialog("flare".into(), json!({ "x": 110.0, "y": 120.0 }))]); + assert!(!t.busy()); + let alt = Mods { alt: true, ..Default::default() }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 310.0, 121.0).with_mods(alt)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 310.0, 121.0).with_mods(alt)); + assert_eq!(a, vec![Action::Exec("shape.flare".into(), flare_params(&t.options(), Point::new(310.0, 121.0)))]); + assert!(!t.busy()); + // Away from the handles a drag draws a new flare. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 200.0, 300.0)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 240.0, 300.0)); + assert_eq!(a.first(), Some(&Action::Begin("Flare".into()))); + // Without a flare selected, no handles show. + let none = Selection::default(); + assert!(FlareTool::default().overlays(&crate::testutil::cx(&d, &none, &p)).is_empty()); + // A flare with an edited part is no longer edited as a flare: no handles show. + d.node_mut(edited).unwrap_or_else(|| panic!("no part")).opacity = 0.25; + assert!(FlareTool::default().overlays(&crate::testutil::cx(&d, &s, &p)).is_empty()); + } + /// Space held while dragging out a flare moves it at its current size and turn, in the center /// drag and in the drag that places the rings' end point; let go, the drag goes on from there. #[test] diff --git a/crates/tools/src/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/guides/targets.rs b/crates/tools/src/guides/targets.rs index a68c6af385..6022ab68fb 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -119,6 +119,27 @@ fn parallel(a: Vec2, b: Vec2) -> bool { scale > 1e-18 && a.dot(b) > 0.0 && a.cross(b).abs() <= 1e-6 * scale } +/// `seg` as a line from its start to its end when it runs straight: a line, or a curve whose +/// control points lie on that line and that stays between its ends (a straight path with its +/// handles drawn out along it). +fn straight(seg: PathSeg) -> Option { + use vectorcraft_geom::kurbo::ParamCurveExtrema; + let (l, ctrl) = match seg { + PathSeg::Line(l) => return Some(l), + PathSeg::Quad(q) => (Line::new(q.p0, q.p2), [q.p1, q.p1]), + PathSeg::Cubic(c) => (Line::new(c.p0, c.p3), [c.p1, c.p2]), + }; + let d = l.p1 - l.p0; + let len2 = d.hypot2(); + if !len2.is_finite() || len2 <= 1e-18 || !ctrl.into_iter().all(|p| d.cross(p - l.p0).abs() <= 1e-9 * len2) { + return None; + } + // The curve's own bounds, not its control points', must stay within the ends' box. + let (b, ends) = (ParamCurveExtrema::bounding_box(&seg), Rect::from_points(l.p0, l.p1)); + let eps = 1e-9 * len2.sqrt(); + (b.x0 >= ends.x0 - eps && b.x1 <= ends.x1 + eps && b.y0 >= ends.y0 - eps && b.y1 <= ends.y1 + eps).then_some(l) +} + /// Does the curve `seg` run around `center` the whole way, as an arc of a circle about it drawn /// with curves does: nearly square to the center all along, and its distance from the center /// varying by no more than 0.03%? A circle drawn with four curves ([`vectorcraft_geom::shapes::ellipse`]) @@ -257,9 +278,10 @@ impl Targets { Self::moving(cx, exclude, Gather::Bounds) } - /// [`Self::for_move`]'s targets for a selection moved by one of its anchors (#7411): the path - /// segments of the art but `exclude` too, which that anchor lands on ([`Self::snap_onto_path`]), - /// as a dragged anchor does with Direct Selection. + /// [`Self::for_move`]'s targets for a selection moved by one of its anchors (#7411) or by a + /// point of a path's stroke or outline (#8568): the path segments of the art but `exclude` too, + /// which that point lands on ([`Self::snap_onto_path`]), as a dragged anchor does with Direct + /// Selection. pub fn for_move_by_anchor(cx: &ToolContext, exclude: &[NodeId]) -> Self { Self::moving(cx, exclude, Gather::Segments) } @@ -1036,15 +1058,57 @@ impl Targets { Some((q, self.label(q, Kind::Edge.label()).into_iter().collect())) } + /// [`Self::snap_onto_path`] for a selection held by a point `p` of a path's edge, its bounds + /// now `r` (#8568). Where paths cross, or on a curved segment, the point lands as + /// `snap_onto_path` lands it. On a straight segment, the selection then slides along that + /// segment, so the point stays on it, until its bounds line up with the other art or are spaced + /// evenly with it ([`Self::snap_rects_along`]), else until they line up with a ruler guide of + /// `rulers` ([`Self::snap_moved_along_to_rulers`]). A slide goes at most twice `tol` and not + /// past the segment's ends. Returns where the point goes and the guides. + pub(crate) fn snap_held_onto_path(&self, p: Point, r: Rect, tol: f64, rulers: Option<&Targets>) -> Option<(Point, Vec)> { + if self.segments.is_empty() { + return None; + } + if let Some(q) = self.crossing_with(p, tol, rulers.map_or(&self.rulers, |r| &r.rulers)) { + return Some((q, self.label(q, "intersect").into_iter().collect())); + } + let (seg, q) = self.nearest_segment(p, tol)?; + let on_path = |q: Point| self.label(q, Kind::Edge.label()); + let Some(l) = straight(seg) else { return Some((q, on_path(q).into_iter().collect())) }; + let len = (l.p1 - l.p0).hypot(); + if !len.is_finite() || len <= 1e-9 { + return Some((q, on_path(q).into_iter().collect())); + } + let u = (l.p1 - l.p0) / len; + let moved = r + (q - p); + // How far the point may slide each way: twice `tol`, and not past the segment's ends. + let at = (q - l.p0).dot(u); + let within = ((-at).max(-2.0 * tol), (len - at).min(2.0 * tol)); + let (s, mut ov) = Some(self.slide_rects_along(&[moved], u, tol, within)) + .filter(|(.., hit)| *hit) + .or_else(|| rulers.map(|t| t.slide_moved_along_to_rulers(q, moved, u, tol, within)).filter(|(.., hit)| *hit)) + .map_or((Vec2::ZERO, vec![]), |(s, ov, _)| (s, ov)); + let q = q + s; + // The point's label is "path", the label a ruler guide's slide puts there too. + ov.retain(|o| !matches!(o, Overlay::Label { .. })); + ov.extend(on_path(q)); + Some((q, ov)) + } + /// The nearest point within `tol` of `p` on a target segment. fn on_segment(&self, p: Point, tol: f64) -> Option { + self.nearest_segment(p, tol).map(|(_, q)| q) + } + + /// [`Self::on_segment`], with the segment the point is on. + fn nearest_segment(&self, p: Point, tol: f64) -> Option<(PathSeg, Point)> { self.segments .iter() .filter(|(b, _)| b.inflate(tol, tol).contains(p)) .map(|(_, c)| (c, c.nearest(p, 1e-6))) .filter(|(_, n)| n.distance_sq <= tol * tol) .min_by(|a, b| a.1.distance_sq.total_cmp(&b.1.distance_sq)) - .map(|(c, n)| c.eval(n.t)) + .map(|(c, n)| (*c, c.eval(n.t))) } /// Where two target paths, a path and a ruler guide, or two ruler guides cross, the crossing @@ -1152,9 +1216,16 @@ impl Targets { /// it is spaced evenly along an axis the line runs along. Returns the shift (along `dir`) and /// the guides. pub(crate) fn snap_rects_along(&self, rects: &[Rect], dir: Vec2, tol: f64) -> (Vec2, Vec) { + let (s, ov, _) = self.slide_rects_along(rects, dir, tol, (f64::NEG_INFINITY, f64::INFINITY)); + (s, ov) + } + + /// [`Self::snap_rects_along`] for a slide of `within` (the least and the most way along + /// `dir`), also saying whether anything lined up or was spaced evenly. + fn slide_rects_along(&self, rects: &[Rect], dir: Vec2, tol: f64, (lo, hi): (f64, f64)) -> (Vec2, Vec, bool) { let len = dir.hypot(); if !len.is_finite() || len <= 1e-9 { - return (Vec2::ZERO, vec![]); + return (Vec2::ZERO, vec![], false); } let u = dir / len; // The axes the line runs along: the x axis (`true`) and the y axis, and how far a step of @@ -1170,7 +1241,7 @@ impl Targets { for v in vs { for (t, from, _) in lines_near(lines, v, tol).iter().filter(|(t, ..)| (t - v).abs() <= tol) { let s = (t - v) / c; - if best.is_none_or(|b| s.abs() < b.0.abs()) { + if (lo..=hi).contains(&s) && best.is_none_or(|b| s.abs() < b.0.abs()) { best = Some((s, *t, *from, x)); } } @@ -1185,17 +1256,41 @@ impl Targets { self.line(Point::new(from.x.min(m.x0), t), Point::new(from.x.max(m.x1), t)) } }); - return (u * s, ov.into_iter().collect()); + return (u * s, ov.into_iter().collect(), true); } - let [r] = rects else { return (Vec2::ZERO, vec![]) }; + let [r] = rects else { return (Vec2::ZERO, vec![], false) }; if self.boxes.is_empty() { - return (Vec2::ZERO, vec![]); + return (Vec2::ZERO, vec![], false); } - let spaced = - axes.filter_map(|(x, c)| self.even_spacing(*r, x, tol).map(|(shift, _)| (shift / c, x))).min_by(|a, b| a.0.abs().total_cmp(&b.0.abs())); - let Some((s, x)) = spaced else { return (Vec2::ZERO, vec![]) }; + // The slide that spaces it evenly along each axis, within `lo..=hi` along the line. A slide + // along a slanted line also moves it across, so the gaps must still be equal where it ends + // up. + let spaced = axes + .filter_map(|(x, c)| { + // A level or upright slide along that axis keeps its row. + let level = (if x { u.y } else { u.x }).abs() <= 1e-9; + // At most 8 slides are checked where they end up, to bound the work per pointer move. + let checked = std::cell::Cell::new(0_usize); + let fits = |shift: f64| { + let s = shift / c; + if !(lo..=hi).contains(&s) { + return false; + } + if level { + return true; + } + if checked.get() >= 8 { + return false; + } + checked.set(checked.get() + 1); + self.even_spacing(*r + u * s, x, tol).is_some_and(|(rest, _)| rest.abs() <= 1e-6) + }; + self.even_spacing_by(*r, x, tol, Some(&fits)).map(|(shift, _)| (shift / c, x)) + }) + .min_by(|a, b| a.0.abs().total_cmp(&b.0.abs())); + let Some((s, x)) = spaced else { return (Vec2::ZERO, vec![], false) }; let gaps = self.even_spacing(*r + u * s, x, tol).map(|(_, gaps)| gaps).unwrap_or_default(); - (u * s, gaps.into_iter().flat_map(|g| self.gap_marks(g, x, tol)).collect()) + (u * s, gaps.into_iter().flat_map(|g| self.gap_marks(g, x, tol)).collect(), true) } /// Snap rectangles that move together (an artboard and its bleed): the edge or centre of any @@ -1240,6 +1335,12 @@ impl Targets { /// neighbour before or after it as two other objects of the row are apart, or as far from both /// neighbours; and the equal gaps then, as (start, end, where across) along that axis. fn even_spacing(&self, r: Rect, x: bool, tol: f64) -> Option<(f64, Vec<[f64; 3]>)> { + self.even_spacing_by(r, x, tol, None) + } + + /// [`Self::even_spacing`] for the nearest shift along that axis that `accept` takes (any shift + /// when `None`). + fn even_spacing_by(&self, r: Rect, x: bool, tol: f64, accept: Option<&dyn Fn(f64) -> bool>) -> Option<(f64, Vec<[f64; 3]>)> { let (r0, r1) = span(&r, x); let len = r1 - r0; let (c0, c1) = span(&r, !x); @@ -1276,8 +1377,36 @@ impl Targets { starts.extend(before.map(|a| (a.2 + g, Some(*g)))); starts.extend(after.map(|b| (b.1 - g - len, Some(*g)))); } - let (start, repeats) = - starts.into_iter().filter(|(t, _)| (t - r0).abs() <= tol).min_by(|a, b| (a.0 - r0).abs().total_cmp(&(b.0 - r0).abs()))?; + starts.retain(|(t, _)| (t - r0).abs() <= tol); + let nearer = |a: &(f64, Option), b: &(f64, Option)| (a.0 - r0).abs().total_cmp(&(b.0 - r0).abs()); + let (start, repeats) = match accept { + // The nearest start, the first proposed among equally near ones. + None => starts.into_iter().min_by(nearer)?, + Some(accept) => { + // Nearest first; the sort is stable, so equally near starts keep the order they + // were proposed in. Starts as near as each other are at most two shifts (one each + // way), so the shifts refused at the current distance are few, and each is asked + // about once. + starts.sort_by(nearer); + let mut refused: Vec = vec![]; + let mut at = f64::NAN; + starts.into_iter().find(|(t, _)| { + let shift = t - r0; + if shift.abs() != at { + at = shift.abs(); + refused.clear(); + } + if refused.contains(&shift) { + return false; + } + let ok = accept(shift); + if !ok { + refused.push(shift); + } + ok + })? + } + }; let at = r + if x { Vec2::new(start - r0, 0.0) } else { Vec2::new(0.0, start - r0) }; let (end, mut gaps) = (start + len, vec![]); if let Some((a, _, a1)) = before @@ -1385,9 +1514,16 @@ impl Targets { /// shortest slide winning and at most twice `tol` (a line nearly parallel to a guide would /// carry the selection far to meet it). Returns the shift along the line and the guides. pub(crate) fn snap_moved_along_to_rulers(&self, p: Point, r: Rect, dir: Vec2, tol: f64) -> (Vec2, Vec) { + let (s, ov, _) = self.slide_moved_along_to_rulers(p, r, dir, tol, (f64::NEG_INFINITY, f64::INFINITY)); + (s, ov) + } + + /// [`Self::snap_moved_along_to_rulers`] for a slide of `within` (the least and the most way + /// along `dir`), also saying whether the bounds lined up with a guide. + fn slide_moved_along_to_rulers(&self, p: Point, r: Rect, dir: Vec2, tol: f64, (lo, hi): (f64, f64)) -> (Vec2, Vec, bool) { let len = dir.hypot(); if !len.is_finite() || len <= 1e-9 { - return (Vec2::ZERO, vec![]); + return (Vec2::ZERO, vec![], false); } let u = dir / len; // The way along the line, where the guide is and where it starts, and whether it is upright. @@ -1399,16 +1535,22 @@ impl Targets { let vs = if vertical { [r.x0, r.center().x, r.x1] } else { [r.y0, r.center().y, r.y1] }; let (mid, half) = if vertical { (Point::new(0.0, r.center().y), r.height() / 2.0) } else { (Point::new(r.center().x, 0.0), r.width() / 2.0) }; - for (t, from, _) in self.rulers.iter().filter(|g| g.vertical == vertical).filter_map(|g| g.line_at(mid, tol + half)) { + for g in self.rulers.iter().filter(|g| g.vertical == vertical) { for v in vs { - let s = (t - v) / c; - if (t - v).abs() <= tol && s.abs() <= 2.0 * tol && best.is_none_or(|b| s.abs() < b.0.abs()) { + let s = (g.pos - v) / c; + if (g.pos - v).abs() > tol || s.abs() > 2.0 * tol || !(lo..=hi).contains(&s) || best.is_some_and(|b| s.abs() >= b.0.abs()) { + continue; + } + // The guide runs past the bounds: for a slide held to `within`, where the slide + // puts them; for a Shift move, where the move put them. + let at = if lo.is_finite() || hi.is_finite() { r.center() + u * s } else { mid }; + if let Some((t, from, _)) = g.line_at(at, tol + half) { best = Some((s, t, from, vertical)); } } } } - let Some((s, t, from, vertical)) = best else { return (Vec2::ZERO, vec![]) }; + let Some((s, t, from, vertical)) = best else { return (Vec2::ZERO, vec![], false) }; let moved = r + u * s; let line = if vertical { self.line(Point::new(t, from.y.min(moved.y0)), Point::new(t, from.y.max(moved.y1))) @@ -1417,7 +1559,7 @@ impl Targets { }; let mut ov: Vec = line.into_iter().collect(); ov.extend(self.label(p + u * s, "align")); - (u * s, ov) + (u * s, ov, true) } /// Snap a bounding-box resize. `a` is the scale [`crate::bbox::scale_for_drag`] gave for diff --git a/crates/tools/src/input.rs b/crates/tools/src/input.rs index 9fa2eab661..a4b4011bf1 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. @@ -197,6 +217,9 @@ pub enum ToolKey { /// A letter key a–z, lowercase (E while dragging a Selection or Group Selection marquee makes it /// select only the objects entirely inside it, and E again switches it back). Letter(char), + /// Alt (Option on macOS) pressed and let go with no other key, click or wheel turn in between + /// (the Quick Pen tool switches to its next action). + AltTap, } /// What a tool asks the engine to do. diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 43e59de7da..9483943af6 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -15,6 +15,7 @@ pub mod catalog; pub mod circle; pub mod corners; pub mod cropimage; +pub mod curvature_circle; pub mod cut; pub mod dimension; pub mod direct; @@ -35,6 +36,7 @@ pub mod pen; pub mod pie; pub mod place; pub mod printtiling; +pub mod quickpen; pub mod repeat_grid; pub mod repeat_radial; pub mod rulerguide; @@ -42,10 +44,12 @@ pub mod select; pub mod settings; pub mod shape; pub mod shaperwidget; +pub mod sidewidget; pub mod slice; pub mod symbolism; pub mod text; pub mod touchtype; +pub mod trace_split; pub mod typewidget; pub mod xform; @@ -104,6 +108,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 @@ -380,6 +388,8 @@ pub fn create(id: &str) -> Box { "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()), + curvature_circle::ID => Box::new(curvature_circle::CurvatureCircleTool::default()), + quickpen::ID => Box::new(quickpen::QuickPenTool::default()), // Not in the toolbar: `file.place.queue` loads it. "place" => Box::new(place::PlaceTool::default()), other => symbolism::create(other) @@ -625,6 +635,7 @@ pub(crate) mod testutil { snap_to_glyph: false, glyph_snap: GlyphSnap::default(), corner_widgets: true, + shape_widgets: true, fill_active: true, gradient_stop: None, appearance_item: None, @@ -672,8 +683,22 @@ pub(crate) mod testutil { plane_targets: distort::perspective::widget::PlaneTargets::ALL, precise_cursors: false, global_edit: &[], + interaction_doc: None, } } + + /// 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/mirror.rs b/crates/tools/src/mirror.rs index 5560fbc321..31253003d9 100644 --- a/crates/tools/src/mirror.rs +++ b/crates/tools/src/mirror.rs @@ -184,4 +184,29 @@ mod tests { spec.kind = RepeatKind::Mirror { angle: f64::NAN, center: Point::ZERO }; assert!(MirrorAxis::of(&doc, &selection, 1.0).is_none()); } + + #[test] + fn a_tool_switch_cancels_a_mirror_axis_drag() { + use crate::{PointerEvent, PointerKind, Tool}; + let (mut doc, id) = doc_with_rect(); + let mut source = doc.node(id).unwrap().clone(); + source.id = doc.alloc_id(); + doc.node_mut(id).unwrap().kind = NodeKind::Repeat(RepeatSpec::mirror(vec![Arc::new(source)], 90.0, 10.0)); + let mut selection = Selection::default(); + selection.set([id]); + let paint = paint(); + let c = cx(&doc, &selection, &paint); + let axis = MirrorAxis::of(&doc, &selection, c.zoom).unwrap(); + let mut t = crate::select::SelectionTool::default(); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, axis.center.x, axis.center.y)).is_empty()); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, axis.center.x + 20.0, axis.center.y)); + assert!(matches!(a.first(), Some(Action::Begin(l)) if l == "Repeat Options"), "{a:?}"); + assert_eq!(t.deactivate(&c), vec![Action::Cancel]); + assert!(!t.busy()); + // A press that has not moved the axis leaves nothing to cancel. + t.pointer(&c, &PointerEvent::new(PointerKind::Down, axis.center.x, axis.center.y)); + assert!(t.busy()); + assert!(t.deactivate(&c).is_empty()); + assert!(!t.busy()); + } } diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs index b1077d5a12..3fd145868c 100644 --- a/crates/tools/src/pen.rs +++ b/crates/tools/src/pen.rs @@ -51,6 +51,10 @@ pub struct PenTool { /// The anchor a press placed, while the drag shapes its handles. drag: Option, hover: Option, + /// The pointer at the last hover before snapping: a press picks anchors there first. + hover_raw: Option, + /// The modifiers at the last hover: with Alt a press may go to the Anchor Point tool. + hover_mods: Mods, /// The incoming handle of the anchor being dragged out, as last previewed. in_h: Point, /// The first anchor, as it was when a press on it began closing the path, and its outgoing @@ -297,6 +301,8 @@ impl Tool for PenTool { match ev.kind { PointerKind::Move => { self.hover = Some(p); + self.hover_raw = Some(ev.pos); + self.hover_mods = ev.mods; vec![] } PointerKind::Down => { @@ -337,7 +343,9 @@ impl Tool for PenTool { } } // An end of another open path: the two become one, and the path is finished. - if let Some((other, other_si, at_first)) = raw_other.or_else(|| open_end_at(cx, p, tol, Some((id, si)))) { + if let Some((other, other_si, at_first)) = + raw_other.or_else(|| if p != ev.pos { open_end_at(cx, p, tol, Some((id, si))) } else { None }) + { self.stop(); let end = if at_first { "first" } else { "last" }; let mut params = json!({"ids": [id.0, other.0], "ends": ["last", end]}); @@ -522,20 +530,30 @@ impl Tool for PenTool { // The rubber band preference hides only the preview segment; Measurement Labels decides the readout. if self.drag.is_none() && self.handle.is_none() - && let (Some((id, _, _, last, out)), Some(h)) = (self.active(cx), self.hover) + && let (Some((id, si, first, last, out)), Some(h)) = (self.active(cx), self.hover) { - if cx.pen_rubber_band { + // The segment a click at `h` adds, if any: it leaves the last anchor along its outgoing + // handle and arrives at the anchor the click ends it on, with that anchor's handle. + let raw = self.hover_raw.unwrap_or(h); + let segment = + if cx.pen_rubber_band || cx.measurement_labels { click_end(cx, (id, si, first, last), raw, h, self.hover_mods) } else { None }; + if cx.pen_rubber_band + && let Some((end, end_h)) = segment + { let mut bp = BezPath::new(); bp.move_to(last); - if out.distance(last) > 1e-9 { - bp.quad_to(out, h); + if out.distance(last) > 1e-9 || end_h.distance(end) > 1e-9 { + bp.curve_to(out, end_h, end); } else { - bp.line_to(h); + bp.line_to(end); } o.push(Overlay::Path { path: bp, color: cx.doc.layer_color(id), width: 1.0, dashed: false }); } - if cx.measurement_labels && last.distance(h) > 1e-9 { - o.push(Overlay::Measure { p: h + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: cx.segment_measure_label(last, h) }); + if cx.measurement_labels + && let Some((end, _)) = segment + && last.distance(end) > 1e-9 + { + o.push(Overlay::Measure { p: h + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: cx.segment_measure_label(last, end) }); } } o.extend_from_slice(self.snap.guides()); @@ -629,7 +647,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; @@ -639,6 +657,46 @@ impl PenTool { } } +/// Where a click ends the next segment of subpath `si` of path `id` (first anchor `first`, last +/// anchor `last`), and the incoming handle it arrives with, for a pointer at `raw` that snaps to +/// `h`. The anchors are picked in the order a press picks them: at `raw` first, then at `h`. On the +/// first anchor the path closes, with that anchor's incoming handle retracted +/// ([`PenTool::begin_close`]). On an end of another open path the two join, and the segment arrives +/// with that end's own handle on the joining side. Anywhere else the click adds a corner anchor at `h`. +/// None where the click adds no segment: on the last anchor (its outgoing handle retracts), with +/// Alt over the path (the Anchor Point tool takes the press, [`alt_converts`]), and on an end of +/// another path that lies on the last anchor (`path.join` merges the two ends into one anchor). +fn click_end(cx: &ToolContext, (id, si, first, last): (NodeId, usize, Point, Point), raw: Point, h: Point, m: Mods) -> Option<(Point, Point)> { + let tol = cx.tol(5.0).max(cx.point_tol()); + let closing_end = last_anchor(cx, id, Some(si)).filter(|(_, ai)| *ai > 0).map(|_| first); + match pick_endpoint(closing_end, last, raw, tol, Endpoint::First) { + Some(Endpoint::First) => return Some((first, first)), + Some(Endpoint::Last) => return None, + None => {} + } + if alt_converts(cx, raw, m) { + return None; + } + let raw_other = open_end_at(cx, raw, tol, Some((id, si))); + if raw_other.is_none() && h != raw { + match pick_endpoint(closing_end, last, h, tol, Endpoint::First) { + Some(Endpoint::First) => return Some((first, first)), + Some(Endpoint::Last) => return None, + None => {} + } + } + let other = raw_other.or_else(|| if h != raw { open_end_at(cx, h, tol, Some((id, si))) } else { None }); + let joined = other.and_then(|(other, osi, at_first)| { + let sp = cx.doc.node(other)?.path_data()?.subpaths.get(osi)?; + if at_first { sp.anchors.first().map(|a| (a.p, a.h_in)) } else { sp.anchors.last().map(|a| (a.p, a.h_out)) } + }); + match joined { + Some((end, _)) if end.distance(last) < 1e-6 => None, + Some(joined) => Some(joined), + None => Some((h, h)), + } +} + /// The first anchor of subpath `si` of path `id`. pub(crate) fn first_anchor(cx: &ToolContext, id: NodeId, si: usize) -> Option { cx.doc.node(id)?.path_data()?.subpaths.get(si)?.anchors.first().copied() diff --git a/crates/tools/src/pen/tests.rs b/crates/tools/src/pen/tests.rs index 710c39ae7a..7b804685b3 100644 --- a/crates/tools/src/pen/tests.rs +++ b/crates/tools/src/pen/tests.rs @@ -865,6 +865,27 @@ fn anchors_snap_to_smart_guides() { assert_eq!(a[1], Action::Preview("path.create".into(), json!({"anchors": [{"x": 100.0, "y": 100.0}]}))); } +/// The rubber band after a smooth anchor is the curve the click then adds: it leaves along the +/// anchor's outgoing handle and arrives at the new corner anchor without a handle, so the segment +/// keeps its shape when the anchor goes down (#8296). +#[test] +fn rubber_band_is_the_segment_a_click_adds() { + let (last, out) = (Point::new(60.0, 300.0), Point::new(110.0, 250.0)); + let sub = vectorcraft_geom::SubPath::new(vec![Anchor::corner(Point::new(10.0, 300.0)), Anchor::smooth(last, out)], false); + let (d, id, s) = drawing(sub); + let p = paint(); + let cx = ToolContext { zoom: 1.0, smart_guides: false, snap_to_point: false, snap_to_pixel: false, snap_to_grid: false, ..cx(&d, &s, &p) }; + let h = Point::new(237.0, 361.0); + let mut t = PenTool { drawing: true, ..PenTool::default() }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, h.x, h.y)); + let band: Vec<_> = + t.overlays(&cx).into_iter().filter_map(|o| if let Overlay::Path { path, .. } = o { Some(path.elements().to_vec()) } else { None }).collect(); + assert_eq!(band, vec![vec![vectorcraft_geom::PathEl::MoveTo(last), vectorcraft_geom::PathEl::CurveTo(out, h, h)]]); + // The click adds a corner anchor there: the segment drawn is the one previewed. + let a = click(&mut t, &cx, h.x, h.y, Mods::default()); + assert_eq!(a[1], Action::Preview("path.appendAnchor".into(), json!({"id": id.0, "x": h.x, "y": h.y, "subpath": 0}))); +} + /// With Enable Rubber Band off, the preview segment is hidden but Measurement Labels still shows /// the D / Angle / dX / dY readout at the snapped point before the next click. #[test] diff --git a/crates/tools/src/pie.rs b/crates/tools/src/pie.rs index af79c1ce46..ae9d934954 100644 --- a/crates/tools/src/pie.rs +++ b/crates/tools/src/pie.rs @@ -115,9 +115,9 @@ impl PieWidget { out } - /// The widgets the Selection tool can drag (its bounding box showing). + /// The widgets the Selection tool can drag (its bounding box and the shape widgets showing). pub fn for_tool(cx: &ToolContext) -> Vec { - if !cx.show_bbox { + if !cx.show_bbox || !cx.shape_widgets { return vec![]; } Self::of(cx.doc, cx.selection, cx.zoom) @@ -248,9 +248,14 @@ mod tests { let w = PieWidget::of(&d, &s, 1.0); assert!(near(w[0].on, Point::new(200.0, 100.0)) && near(w[0].at, Point::new(200.0, 88.0)), "{w:?}"); assert!(near(w[1].at, Point::new(312.0, 150.0)), "{w:?}"); - // No widgets with the bounding box hidden, with nothing selected, or on another shape. + // No widgets with the bounding box or the shape widgets hidden, with nothing selected, or on + // another shape. let p = paint(); + assert_eq!(PieWidget::for_tool(&cx(&d, &s, &p)).len(), 2); assert!(PieWidget::for_tool(&ToolContext { show_bbox: false, ..cx(&d, &s, &p) }).is_empty()); + let hidden = ToolContext { shape_widgets: false, ..cx(&d, &s, &p) }; + assert!(PieWidget::for_tool(&hidden).is_empty()); + assert!(!over_widget(&hidden, w[1].at) && double_click(&hidden, w[1].at).is_none()); assert!(PieWidget::of(&d, &Selection::default(), 1.0).is_empty()); let (d, id) = doc_with_rect(); let mut s = Selection::default(); diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs new file mode 100644 index 0000000000..140278719d --- /dev/null +++ b/crates/tools/src/quickpen.rs @@ -0,0 +1,616 @@ +//! The Quick Pen tool (Alt+P, Option+P on macOS) draws paths of straight lines and circular arcs +//! (`path.quickPen`). +//! +//! A click sets the start point, and each click or drag after it adds a piece from the last point +//! to where the pointer is let go, as the tool's action says: a straight line, a continuous arc +//! (it leaves its start in the direction the path arrives in, so the two join smoothly) or a +//! sharp-corner arc (it turns through the arc size, 180° by default, and meets the path before it +//! at a corner). Alt (Option) pressed and let go on its own switches to the next action. C flips +//! the last sharp-corner arc to the other side of its chord, and [ and ] make the arc size 15° +//! smaller or larger, for the last sharp-corner arc and the ones after it. A click on the first +//! point closes the path, a click on an end of an open path goes on drawing from it, and Escape +//! or Enter ends the path. The path's points show as circles, without handles, and a preview +//! shows the piece the next click adds. Points snap to Smart Guides. Each piece is one undo step. + +use std::f64::consts::{FRAC_PI_2, PI}; + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_geom::{Anchor, AnchorKind, BezPath, Point, SubPath, Vec2}; + +use crate::draw2::FEEDBACK; +use crate::guides::{DrawSnap, Leave}; +use crate::pen::{continue_from, open_end_at}; +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; + +/// The tool's id. +pub const ID: &str = "quickPen"; +/// The command that draws the path. +pub const COMMAND: &str = "path.quickPen"; +/// A sharp-corner arc's turn (degrees) until [ or ] changes it. +pub const DEFAULT_TURN: f64 = 180.0; +/// The degrees [ and ] take from or add to the arc size. +pub const TURN_STEP: f64 = 15.0; +/// The smallest and largest arc size (degrees). +pub const MIN_TURN: f64 = 1.0; +pub const MAX_TURN: f64 = 359.0; +/// Screen points the pointer moves after a press before the press drags. +const DRAG_PX: f64 = 3.0; +/// A continuous arc whose end lies within this angle (radians) of straight ahead, or of straight +/// behind, is drawn as a line: no circle runs there in the path's direction. +const STRAIGHT: f64 = 1e-6; + +/// What the next click adds. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Stroke { + #[default] + Line, + ContinuousArc, + SharpArc, +} + +impl Stroke { + pub const ALL: [Stroke; 3] = [Stroke::Line, Stroke::ContinuousArc, Stroke::SharpArc]; + + /// The name commands and the tool's `action` option use. + pub fn name(self) -> &'static str { + match self { + Stroke::Line => "line", + Stroke::ContinuousArc => "continuousArc", + Stroke::SharpArc => "sharpArc", + } + } + + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|k| k.name() == s) + } + + /// The action after this one: Line, Continuous Arc, Sharp Corner Arc, and round again. + pub fn next(self) -> Self { + match self { + Stroke::Line => Stroke::ContinuousArc, + Stroke::ContinuousArc => Stroke::SharpArc, + Stroke::SharpArc => Stroke::Line, + } + } +} + +/// One piece of a Quick Pen path: from the path's last point to `to`. `turn` (degrees) and `flip` +/// shape a sharp-corner arc, and a continuous arc with no direction to follow. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Piece { + pub to: Point, + pub stroke: Stroke, + pub turn: f64, + pub flip: bool, +} + +impl Piece { + pub fn to_json(&self) -> Value { + let mut v = json!({"x": self.to.x, "y": self.to.y, "action": self.stroke.name()}); + if self.stroke != Stroke::Line { + v["turn"] = json!(self.turn); + v["flip"] = json!(self.flip); + } + v + } +} + +/// `v` turned by `a` radians (clockwise on the page, whose y runs down). +fn rot(v: Vec2, a: f64) -> Vec2 { + let (s, c) = a.sin_cos(); + Vec2::new(v.x * c - v.y * s, v.x * s + v.y * c) +} + +fn unit(v: Vec2) -> Option { + let l = v.hypot(); + (l > 1e-12 && l.is_finite()).then(|| v / l) +} + +/// The direction an open subpath runs at its last point: along that point's incoming handle, or +/// else from the segment before it. None for a single point, or a path that comes back on itself. +pub fn arrival(sp: &SubPath) -> Option { + let n = sp.anchors.len(); + let last = sp.anchors.last()?; + if let Some(d) = unit(last.p - last.h_in) { + return Some(d); + } + let prev = sp.anchors.get(n.checked_sub(2)?)?; + unit(last.p - prev.h_out).or_else(|| unit(last.p - prev.p)) +} + +/// The signed turn (radians) of the arc `piece` adds from `a` to `b` on `sp`, or None for a +/// straight segment. Positive turns bulge to the left of the direction drawn. +fn turn_of(sp: &SubPath, piece: &Piece, a: Point, b: Point) -> Option { + let sharp = |p: &Piece| p.turn.to_radians() * if p.flip { -1.0 } else { 1.0 }; + match piece.stroke { + Stroke::Line => None, + Stroke::SharpArc => Some(sharp(piece)), + Stroke::ContinuousArc => match arrival(sp) { + None => Some(sharp(piece)), + Some(t) => { + let c = b - a; + let phi = t.cross(c).atan2(t.dot(c)); + (phi.abs() > STRAIGHT && phi.abs() < PI - STRAIGHT).then_some(2.0 * phi) + } + }, + } +} + +/// Adds `piece` at the end of the open subpath `sp`. A piece that ends where the subpath does adds +/// nothing (false). An arc is drawn as cubic segments of at most 90° each, its inner points smooth; +/// the new end is a corner without an outgoing handle. The point the piece leaves from is smooth +/// when a continuous arc goes on from a curve into it, and a corner otherwise. +pub fn append(sp: &mut SubPath, piece: &Piece) -> bool { + let Some(last) = sp.anchors.last().copied() else { return false }; + let (a, b) = (last.p, piece.to); + let c = b - a; + let l = c.hypot(); + if l <= 1e-9 || !l.is_finite() { + return false; + } + let Some(s) = turn_of(sp, piece, a, b) else { + if let Some(end) = sp.anchors.last_mut() { + end.h_out = end.p; + end.kind = AnchorKind::Corner; + } + sp.anchors.push(Anchor::corner(b)); + return true; + }; + let continuous = piece.stroke == Stroke::ContinuousArc && arrival(sp).is_some(); + let n = ((s.abs() / FRAC_PI_2) - 1e-9).ceil().max(1.0) as usize; + let step = s / n as f64; + let r = l / (2.0 * (s.abs() / 2.0).sin()); + let k = 4.0 / 3.0 * (step.abs() / 4.0).tan() * r; + let mut t = rot(c / l, -s / 2.0); + if let Some(end) = sp.anchors.last_mut() { + end.h_out = a + t * k; + end.kind = if continuous && end.h_in != end.p { AnchorKind::Smooth } else { AnchorKind::Corner }; + } + let mut p = a; + for i in 1..=n { + let chord = rot(t, step / 2.0) * (2.0 * r * (step.abs() / 2.0).sin()); + let t2 = rot(t, step); + let q = if i == n { b } else { p + chord }; + let mut an = Anchor::with_handles(q, q - t2 * k, q); + if i < n { + an.h_out = q + t2 * k; + an.kind = AnchorKind::Smooth; + } + sp.anchors.push(an); + (p, t) = (q, t2); + } + true +} + +/// Closes `sp`: a last point that lies on the first joins it (the first point takes its incoming +/// handle); otherwise a straight segment closes the path. Fewer than two points stay open. +pub fn close(sp: &mut SubPath) { + let n = sp.anchors.len(); + if n < 2 { + return; + } + if let (Some(first), Some(last)) = (sp.anchors.first().copied(), sp.anchors.last().copied()) + && n >= 3 + && first.p.distance(last.p) <= 1e-9 + { + sp.anchors.pop(); + if let Some(f) = sp.anchors.first_mut() { + f.h_in = last.h_in; + } + } + sp.closed = true; +} + +/// `base` with `pieces` added after it, closed when `closed`. +pub fn build(base: &SubPath, pieces: &[Piece], closed: bool) -> SubPath { + let mut sp = base.clone(); + for piece in pieces { + append(&mut sp, piece); + } + if closed { + close(&mut sp); + } + sp +} + +/// The path being drawn: subpath `si` of `id`, whose points were `base` before the tool drew on +/// (both none until the engine made a new path), then `pieces`. A new path starts at `start`. +#[derive(Clone, Debug, PartialEq)] +struct Drawing { + id: Option, + si: usize, + base: Option, + start: Option, + pieces: Vec, +} + +impl Drawing { + /// The subpath as the tool drew it. + fn drawn(&self) -> Option { + Some(build(self.base.as_ref()?, &self.pieces, false)) + } +} + +/// The press in progress: where it went down, whether it has dragged, and whether it began an undo +/// step (a piece it adds). +#[derive(Clone, Copy, Debug, PartialEq)] +struct Press { + at: Point, + dragged: bool, + begun: bool, +} + +pub struct QuickPenTool { + action: Stroke, + turn: f64, + drawing: Option, + press: Option, + hover: Option, + snap: DrawSnap, +} + +impl Default for QuickPenTool { + fn default() -> Self { + Self { action: Stroke::Line, turn: DEFAULT_TURN, drawing: None, press: None, hover: None, snap: DrawSnap::default() } + } +} + +/// Is `id` selected on its own, itself or the compound path it is in? +fn selected_alone(cx: &ToolContext, id: NodeId) -> bool { + let sel = cx.selection.objects.as_slice(); + sel == [id] || cx.doc.parent_of(id).is_some_and(|p| sel == [p] && cx.doc.node(p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))) +} + +fn point_tol(cx: &ToolContext) -> f64 { + cx.tol(5.0).max(cx.point_tol()) +} + +impl QuickPenTool { + /// The subpath being drawn, while it is selected, editable, open and still exactly what the tool + /// drew: an edit made outside the tool (a point moved, the path it went on from changed) ends + /// the drawing, so the next piece does not undo it. + fn active<'a>(&self, cx: &'a ToolContext) -> Option<(NodeId, &'a SubPath)> { + let dr = self.drawing.as_ref()?; + let id = dr.id?; + if !selected_alone(cx, id) || !cx.doc.is_editable(id) { + return None; + } + let sp = cx.doc.node(id)?.path_data()?.subpaths.get(dr.si)?; + (!sp.closed && dr.drawn()?.anchors == sp.anchors).then_some((id, sp)) + } + + /// `path.quickPen`'s params for the path being drawn, closed when `closed`. + fn params(&self, closed: bool) -> Value { + let Some(dr) = &self.drawing else { return json!({}) }; + let pieces: Vec = dr.pieces.iter().map(Piece::to_json).collect(); + let mut v = json!({"pieces": pieces}); + match (dr.id, dr.start) { + (Some(id), _) => { + v["id"] = json!(id.0); + v["subpath"] = json!(dr.si); + v["keep"] = json!(dr.base.as_ref().map_or(1, |b| b.anchors.len().max(1))); + } + (None, Some(s)) => v["start"] = json!([s.x, s.y]), + (None, None) => {} + } + if closed { + v["closed"] = json!(true); + } + v + } + + /// The last piece, while it is a sharp-corner arc and no press is under way. + fn last_sharp_arc(&self, cx: &ToolContext) -> Option { + if self.press.is_some() { + return None; + } + self.active(cx)?; + self.drawing.as_ref()?.pieces.last().copied().filter(|p| p.stroke == Stroke::SharpArc) + } + + fn piece_to(&self, to: Point) -> Piece { + Piece { to, stroke: self.action, turn: self.turn, flip: false } + } + + /// The segment from the path's last point the snapping leaves from. + fn leave(&self, cx: &ToolContext) -> Option<(NodeId, Leave)> { + let (id, sp) = self.active(cx)?; + sp.anchors.last().map(|a| (id, Leave::segment(cx, a.p, false).without_contact())) + } + + /// What a press draws: a piece on the path being drawn, its closing piece, or a new path (from + /// an end of an open path, the path goes on). + fn press_down(&mut self, cx: &ToolContext, p: Point) -> Vec { + if self.drawing.is_some() && self.active(cx).is_none() { + self.drawing = None; + } + let tol = point_tol(cx); + if let Some((id, sp)) = self.active(cx) { + let (first, last) = match (sp.anchors.first(), sp.anchors.last()) { + (Some(f), Some(l)) => (f.p, l.p), + _ => return vec![], + }; + if sp.anchors.len() >= 2 && p.distance(first) <= tol && p.distance(first) <= p.distance(last) { + let piece = self.piece_to(first); + if let Some(dr) = self.drawing.as_mut() { + dr.pieces.push(piece); + } + let out = vec![Action::Exec(COMMAND.into(), self.params(true))]; + self.drawing = None; + return out; + } + if p.distance(last) <= tol { + return vec![]; + } + let from = self.leave(cx).map(|l| l.1); + let q = self.snap.press(cx, p, &[id], from.as_ref()); + let piece = self.piece_to(q); + if let Some(dr) = self.drawing.as_mut() { + dr.pieces.push(piece); + } + self.press = Some(Press { at: p, dragged: false, begun: true }); + return vec![Action::Begin("Quick Pen".into()), Action::Preview(COMMAND.into(), self.params(false))]; + } + if let Some((id, si, at_first)) = open_end_at(cx, p, tol, None) + && cx.doc.is_editable(id) + && let Some(sp) = cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)) + { + // From its start, `continue_from` reverses the path first. + let mut base = sp.clone(); + if at_first { + base.reverse(); + } + self.drawing = Some(Drawing { id: Some(id), si, base: Some(base), start: None, pieces: vec![] }); + return continue_from(cx, id, si, at_first); + } + let q = self.snap.press(cx, p, &[], None); + self.drawing = Some(Drawing { id: None, si: 0, base: None, start: Some(q), pieces: vec![] }); + vec![Action::Exec(COMMAND.into(), self.params(false)), Action::Notify("created".into())] + } + + /// Ends the path being drawn; a press that added a piece is taken back. + fn end(&mut self) -> Vec { + self.drawing = None; + self.snap.clear(); + match self.press.take() { + Some(pr) if pr.begun => vec![Action::Cancel], + _ => vec![], + } + } + + /// The piece the next click adds, from the end of `sp` to `h`, as a path to preview. + fn rubber_band(&self, sp: &SubPath, h: Point) -> Option { + let n = sp.anchors.len(); + let mut tail = SubPath::new(sp.anchors.get_range(n.saturating_sub(2)..)?, false); + let from = tail.anchors.len() - 1; + if !append(&mut tail, &self.piece_to(h)) { + return None; + } + let mut added = tail.anchors.get_range(from..)?; + if let Some(a) = added.first_mut() { + a.h_in = a.p; + } + let mut bp = BezPath::new(); + SubPath::new(added, false).to_bezpath_into(&mut bp); + Some(bp) + } +} + +impl Tool for QuickPenTool { + fn id(&self) -> &'static str { + ID + } + + fn busy(&self) -> bool { + self.press.is_some() + } + + fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + let p = ev.pos; + match ev.kind { + PointerKind::Move => { + let (on, from) = self.leave(cx).unzip(); + self.hover = Some(self.snap.hover(cx, p, on.as_slice(), from.as_ref())); + vec![] + } + PointerKind::Down => { + if self.press.is_some() { + return vec![]; + } + self.press_down(cx, p) + } + PointerKind::Drag => { + let Some(mut pr) = self.press else { return vec![] }; + if !pr.dragged && p.distance(pr.at) < cx.tol(DRAG_PX) { + return vec![]; + } + pr.dragged = true; + self.press = Some(pr); + // The snapping leaves from the point before the piece being dragged. + let from = self.drawing.as_ref().and_then(|dr| { + let sp = build(dr.base.as_ref()?, dr.pieces.split_last().map_or(&[][..], |(_, rest)| rest), false); + sp.anchors.last().map(|a| Leave::segment(cx, a.p, false).without_contact()) + }); + let q = self.snap.drag(cx, p, from.as_ref()); + if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) { + last.to = q; + } + vec![Action::Preview(COMMAND.into(), self.params(false))] + } + PointerKind::Up => { + self.snap.clear(); + match self.press.take() { + Some(pr) if pr.begun => vec![Action::Commit], + _ => vec![], + } + } + PointerKind::DoubleClick | PointerKind::TripleClick => vec![], + } + } + + fn notify(&mut self, cx: &ToolContext, what: &str) { + if what == "created" + && let [id] = cx.selection.objects.as_slice() + && let Some(base) = cx.doc.node(*id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.first()) + && let Some(dr) = self.drawing.as_mut() + && dr.id.is_none() + { + (dr.id, dr.si, dr.base, dr.start) = (Some(*id), 0, Some(base.clone()), None); + } + } + + /// A path being drawn: Escape ends it. + fn ends_on_escape(&self, cx: &ToolContext) -> bool { + self.active(cx).is_some() + } + + fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool { + match key { + ToolKey::Letter('c') => self.last_sharp_arc(cx).is_some(), + ToolKey::BracketLeft | ToolKey::BracketRight | ToolKey::AltTap => true, + ToolKey::Enter => self.active(cx).is_some(), + _ => false, + } + } + + /// A dropped press does not end the path being drawn: the piece it added goes. + fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + if self.press.take().is_some_and(|pr| pr.begun) + && let Some(dr) = self.drawing.as_mut() + { + dr.pieces.pop(); + } + self.snap.clear(); + vec![] + } + + fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + match key { + ToolKey::Escape | ToolKey::Enter => self.end(), + ToolKey::Letter('c') => { + if self.last_sharp_arc(cx).is_none() { + return vec![]; + } + if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) { + last.flip = !last.flip; + } + vec![Action::Exec(COMMAND.into(), self.params(false))] + } + ToolKey::BracketLeft | ToolKey::BracketRight => { + let by = if key == ToolKey::BracketLeft { -TURN_STEP } else { TURN_STEP }; + let arc = self.last_sharp_arc(cx); + let turn = arc.map_or(self.turn, |a| a.turn) + by; + if !(MIN_TURN..=MAX_TURN).contains(&turn) { + return vec![]; + } + self.turn = turn; + if arc.is_none() { + return vec![]; + } + if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) { + last.turn = turn; + } + vec![Action::Exec(COMMAND.into(), self.params(false))] + } + ToolKey::AltTap => { + self.action = self.action.next(); + // A drag under way draws its piece with the new action. + if self.press.is_some_and(|pr| pr.begun) { + let (action, turn) = (self.action, self.turn); + if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) { + (last.stroke, last.turn, last.flip) = (action, turn, false); + } + return vec![Action::Preview(COMMAND.into(), self.params(false))]; + } + vec![] + } + _ => vec![], + } + } + + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + self.drawing = None; + self.snap.clear(); + match self.press.take() { + Some(pr) if pr.begun => vec![Action::Commit], + _ => vec![], + } + } + + fn chosen_again(&mut self, _cx: &ToolContext) -> Vec { + if self.press.is_none() { + self.drawing = None; + } + vec![] + } + + fn hover_ended(&mut self, _cx: &ToolContext) { + self.hover = None; + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + let mut o = self.snap.guides().to_vec(); + let Some((id, sp)) = self.active(cx) else { return o }; + if self.press.is_none() + && let Some(h) = self.hover + { + if cx.pen_rubber_band + && let Some(path) = self.rubber_band(sp, h) + { + o.push(Overlay::Path { path, color: cx.doc.layer_color(id), width: 1.0, dashed: false }); + } + if let Some(last) = sp.anchors.last().map(|a| a.p) + && cx.measurement_labels + && last.distance(h) > 1e-9 + { + o.push(Overlay::Measure { p: h + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: cx.segment_measure_label(last, h) }); + } + } + let n = sp.anchors.len(); + for (i, a) in sp.anchors.iter().enumerate() { + o.push(Overlay::CurvePoint { p: a.p, color: FEEDBACK, filled: i + 1 == n, size: 6.0 }); + } + o + } + + fn cursor(&self, cx: &ToolContext, p: Point, _m: Mods) -> Cursor { + let tol = point_tol(cx); + if let Some((_, sp)) = self.active(cx) { + let close = sp.anchors.len() >= 2 && sp.anchors.first().is_some_and(|f| f.p.distance(p) <= tol); + return if close { Cursor::PenClose } else { Cursor::PenDrawing }; + } + if open_end_at(cx, p, tol, None).is_some() { Cursor::PenContinue } else { Cursor::Pen } + } + + fn options(&self) -> Value { + json!({ "action": self.action.name(), "turn": self.turn }) + } + + fn set_option(&mut self, key: &str, v: &Value) { + match key { + "action" => { + if let Some(a) = v.as_str().and_then(Stroke::parse) { + self.action = a; + } + } + "turn" => { + if let Some(t) = v.as_f64().filter(|t| (MIN_TURN..=MAX_TURN).contains(t)) { + self.turn = t; + } + } + _ => {} + } + } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + match key { + "action" => crate::option_check::one_of(key, v, &Stroke::ALL.map(Stroke::name)), + "turn" => crate::option_check::number(key, v, MIN_TURN, MAX_TURN), + _ => Err(crate::option_check::unknown(key)), + } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/tools/src/quickpen/tests.rs b/crates/tools/src/quickpen/tests.rs new file mode 100644 index 0000000000..f5ab9986d1 --- /dev/null +++ b/crates/tools/src/quickpen/tests.rs @@ -0,0 +1,214 @@ +use super::*; +use crate::testutil::*; +use vectorcraft_doc::Selection; +use vectorcraft_geom::{ParamCurve, PathData}; + +fn pt(x: f64, y: f64) -> Point { + Point::new(x, y) +} + +fn start(p: Point) -> SubPath { + SubPath::new(vec![Anchor::corner(p)], false) +} + +fn piece(x: f64, y: f64, stroke: Stroke) -> Piece { + Piece { to: pt(x, y), stroke, turn: DEFAULT_TURN, flip: false } +} + +/// Every sampled point of the segments from anchor `from` on lies `r` from `center`. +fn on_circle(sp: &SubPath, from: usize, center: Point, r: f64) -> bool { + (from..sp.segment_count()).all(|i| (0..=16).all(|k| (sp.segment(i).eval(k as f64 / 16.0).distance(center) - r).abs() < r * 1e-3)) +} + +#[test] +fn a_line_piece_adds_a_corner_point_and_no_handles() { + let mut sp = start(pt(0.0, 0.0)); + assert!(append(&mut sp, &piece(100.0, 0.0, Stroke::Line))); + assert_eq!(sp.anchors.len(), 2); + assert!(sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p && a.kind == AnchorKind::Corner)); +} + +/// A sharp-corner arc turns 180° by default: a half circle on its chord, on the left of the +/// direction drawn (above a chord drawn to the right, since y runs down), in two quarter segments. +#[test] +fn a_sharp_corner_arc_is_a_half_circle_bulging_left() { + let mut sp = start(pt(0.0, 0.0)); + append(&mut sp, &piece(100.0, 0.0, Stroke::SharpArc)); + assert_eq!(sp.anchors.len(), 3); + assert!(on_circle(&sp, 0, pt(50.0, 0.0), 50.0)); + assert!(sp.anchors.get(1).unwrap().p.distance(pt(50.0, -50.0)) < 1e-9); + assert_eq!(sp.anchors.last().unwrap().p, pt(100.0, 0.0)); + // Flipped, it bulges the other way. + let mut sp = start(pt(0.0, 0.0)); + append(&mut sp, &Piece { flip: true, ..piece(100.0, 0.0, Stroke::SharpArc) }); + assert!(sp.anchors.get(1).unwrap().p.distance(pt(50.0, 50.0)) < 1e-9); +} + +/// The turn sets how much of a circle the arc is: 90° is one segment, 270° three. +#[test] +fn the_turn_sets_the_arc_and_its_segments() { + let mut sp = start(pt(0.0, 0.0)); + append(&mut sp, &Piece { turn: 90.0, ..piece(100.0, 0.0, Stroke::SharpArc) }); + assert_eq!(sp.anchors.len(), 2); + let r = 100.0 / (2.0 * (45f64).to_radians().sin()); + // Bulging up, so its center is below the chord. + assert!(on_circle(&sp, 0, pt(50.0, 50.0), r)); + let mut sp = start(pt(0.0, 0.0)); + append(&mut sp, &Piece { turn: 270.0, ..piece(100.0, 0.0, Stroke::SharpArc) }); + assert_eq!(sp.anchors.len(), 4); + assert!(sp.anchors.iter().skip(1).take(2).all(|a| a.kind == AnchorKind::Smooth)); +} + +/// A continuous arc leaves the end of the path in the direction the path arrives in: after a +/// line drawn to the right, an arc to a point below and to the right starts heading right. +#[test] +fn a_continuous_arc_goes_on_in_the_paths_direction() { + let mut sp = start(pt(0.0, 0.0)); + append(&mut sp, &piece(100.0, 0.0, Stroke::Line)); + append(&mut sp, &piece(200.0, 100.0, Stroke::ContinuousArc)); + let corner = sp.anchors.get(1).unwrap(); + let out = corner.h_out - corner.p; + assert!(out.y.abs() < 1e-9 && out.x > 0.0, "{out:?}"); + // The quarter circle centered at (100, 100). + assert!(on_circle(&sp, 1, pt(100.0, 100.0), 100.0)); + // Another continuous arc goes on smoothly from its end. + append(&mut sp, &piece(100.0, 200.0, Stroke::ContinuousArc)); + let joint = sp.anchors.get(2).unwrap(); + assert!((joint.p - joint.h_in).cross(joint.h_out - joint.p).abs() < 1e-6); + assert_eq!(joint.kind, AnchorKind::Smooth); +} + +/// With nothing to follow (the path's first piece) a continuous arc is drawn as a sharp-corner +/// arc; an end straight ahead is a line. +#[test] +fn a_continuous_arc_without_a_direction_or_straight_ahead() { + let mut a = start(pt(0.0, 0.0)); + let mut b = start(pt(0.0, 0.0)); + append(&mut a, &piece(100.0, 0.0, Stroke::ContinuousArc)); + append(&mut b, &piece(100.0, 0.0, Stroke::SharpArc)); + assert_eq!(a, b); + let mut sp = start(pt(0.0, 0.0)); + append(&mut sp, &piece(100.0, 0.0, Stroke::Line)); + append(&mut sp, &piece(300.0, 0.0, Stroke::ContinuousArc)); + assert_eq!(sp.anchors.len(), 3); + assert_eq!(sp.anchors.get(1).unwrap().h_out, pt(100.0, 0.0)); +} + +/// A line or a sharp-corner arc leaves a corner behind it, also after a continuous arc and from +/// the smooth end of a path it goes on from; a continuous arc leaves a smooth point. +#[test] +fn only_a_continuous_arc_leaves_a_smooth_point() { + let mut sp = start(pt(0.0, 0.0)); + append(&mut sp, &piece(100.0, 0.0, Stroke::Line)); + append(&mut sp, &piece(200.0, 100.0, Stroke::ContinuousArc)); + append(&mut sp, &piece(100.0, 200.0, Stroke::ContinuousArc)); + assert_eq!(sp.anchors.get(2).unwrap().kind, AnchorKind::Smooth); + let smooth_end = sp.anchors.len() - 1; + let mut a = sp.clone(); + a.anchors.last_mut().unwrap().kind = AnchorKind::Smooth; + let mut b = a.clone(); + append(&mut a, &piece(300.0, 300.0, Stroke::SharpArc)); + append(&mut b, &piece(300.0, 300.0, Stroke::Line)); + for sp in [a, b] { + assert_eq!(sp.anchors.get(smooth_end).unwrap().kind, AnchorKind::Corner); + } +} + +#[test] +fn a_piece_to_the_last_point_adds_nothing() { + let mut sp = start(pt(5.0, 5.0)); + assert!(!append(&mut sp, &piece(5.0, 5.0, Stroke::SharpArc))); + assert_eq!(sp.anchors.len(), 1); +} + +/// Closing on the first point joins the two; elsewhere a straight segment closes the path. +#[test] +fn closing_joins_a_last_point_on_the_first() { + let pieces = [piece(100.0, 0.0, Stroke::Line), piece(100.0, 100.0, Stroke::Line), piece(0.0, 0.0, Stroke::SharpArc)]; + let sp = build(&start(pt(0.0, 0.0)), &pieces, true); + assert!(sp.closed); + assert_eq!(sp.anchors.first().unwrap().p, pt(0.0, 0.0)); + assert!(sp.anchors.iter().filter(|a| a.p == pt(0.0, 0.0)).count() == 1); + assert_ne!(sp.anchors.first().unwrap().h_in, pt(0.0, 0.0), "the first point takes the arc's handle"); + let sp = build(&start(pt(0.0, 0.0)), &pieces[..2], true); + assert!(sp.closed && sp.anchors.len() == 3); +} + +#[test] +fn actions_cycle_and_name_themselves() { + assert_eq!(Stroke::Line.next(), Stroke::ContinuousArc); + assert_eq!(Stroke::ContinuousArc.next(), Stroke::SharpArc); + assert_eq!(Stroke::SharpArc.next(), Stroke::Line); + for s in Stroke::ALL { + assert_eq!(Stroke::parse(s.name()), Some(s)); + } + assert_eq!(Stroke::parse("arc"), None); +} + +#[test] +fn options_are_checked_and_set() { + let mut t = QuickPenTool::default(); + assert_eq!(t.options(), json!({"action": "line", "turn": 180.0})); + assert!(t.check_option("action", &json!("sharpArc")).is_ok()); + assert!(t.check_option("action", &json!("arc")).is_err()); + assert!(t.check_option("turn", &json!(0)).is_err()); + assert!(t.check_option("turn", &json!(360)).is_err()); + assert!(t.check_option("size", &json!(1)).is_err()); + t.set_option("action", &json!("continuousArc")); + t.set_option("turn", &json!(90)); + assert_eq!(t.options(), json!({"action": "continuousArc", "turn": 90.0})); +} + +/// Alt tapped alone switches to the next action; [ and ] change the arc size by 15° within 1° to +/// 359°, with no path being drawn. +#[test] +fn alt_tap_cycles_and_brackets_size_the_next_arc() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = QuickPenTool::default(); + assert!(t.claims_key(&cx, ToolKey::AltTap)); + for want in ["continuousArc", "sharpArc", "line"] { + assert!(t.key(&cx, ToolKey::AltTap, Mods::default()).is_empty()); + assert_eq!(t.options()["action"], want); + } + assert!(t.key(&cx, ToolKey::BracketRight, Mods::default()).is_empty()); + assert_eq!(t.options()["turn"], 195.0); + t.set_option("turn", &json!(10)); + t.key(&cx, ToolKey::BracketLeft, Mods::default()); + assert_eq!(t.options()["turn"], 10.0, "stays at or above 1°"); + // C is the Scissors' shortcut while no arc is being drawn. + assert!(!t.claims_key(&cx, ToolKey::Letter('c'))); +} + +/// The first click starts a new path and the tool picks it up once the engine made it. +#[test] +fn the_first_click_starts_a_path() { + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = QuickPenTool::default(); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 10.0)); + assert!(matches!(&a[0], Action::Exec(c, v) if c == COMMAND && v["start"] == json!([10.0, 10.0]) && v["pieces"] == json!([])), "{a:?}"); + assert_eq!(a[1], Action::Notify("created".into())); + assert_eq!(t.cursor(&cx, pt(400.0, 400.0), Mods::default()), Cursor::Pen); +} + +/// The rubber band previews exactly the piece a click adds. +#[test] +fn the_rubber_band_is_the_next_piece() { + let t = QuickPenTool { action: Stroke::SharpArc, ..Default::default() }; + let sp = build(&start(pt(0.0, 0.0)), &[piece(100.0, 0.0, Stroke::Line)], false); + let band = t.rubber_band(&sp, pt(200.0, 0.0)).unwrap(); + let mut added = sp.clone(); + append(&mut added, &t.piece_to(pt(200.0, 0.0))); + let whole = PathData::single(added); + for seg in band.segments() { + for k in 0..=8 { + let q = seg.eval(k as f64 / 8.0); + assert!(whole.nearest(q).is_some_and(|n| n.4 < 1e-6), "{q:?}"); + } + } +} diff --git a/crates/tools/src/repeat_grid.rs b/crates/tools/src/repeat_grid.rs index 07187a6a5a..eecc6ba0fe 100644 --- a/crates/tools/src/repeat_grid.rs +++ b/crates/tools/src/repeat_grid.rs @@ -392,4 +392,24 @@ mod tests { assert_eq!(cursor(&c, g.rows_at), Some(Cursor::ResizeV)); assert_eq!(cursor(&c, g.corner_at), Some(Cursor::ResizeNwSe)); } + + #[test] + fn a_tool_switch_cancels_a_grid_handle_drag() { + use crate::{PointerEvent, PointerKind, Tool}; + let (doc, selection) = grid(); + let paint = paint(); + let c = cx(&doc, &selection, &paint); + let g = GridHandles::of(&doc, &selection, crate::select::selection_box(&c), c.zoom).unwrap(); + let mut t = crate::select::SelectionTool::default(); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, g.rows_at.x, g.rows_at.y)).is_empty()); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, g.rows_at.x, g.rows_at.y + 150.0)); + assert!(preview(&a).is_some(), "{a:?}"); + assert_eq!(t.deactivate(&c), vec![Action::Cancel]); + assert!(!t.busy()); + // A press that has not changed the grid leaves nothing to cancel. + t.pointer(&c, &PointerEvent::new(PointerKind::Down, g.rows_at.x, g.rows_at.y)); + assert!(t.busy()); + assert!(t.deactivate(&c).is_empty()); + assert!(!t.busy()); + } } diff --git a/crates/tools/src/repeat_radial.rs b/crates/tools/src/repeat_radial.rs index 42a9f4395f..7304570404 100644 --- a/crates/tools/src/repeat_radial.rs +++ b/crates/tools/src/repeat_radial.rs @@ -681,4 +681,26 @@ mod tests { assert_eq!(preview(&d.drag(h.instances_at + Vec2::new(0.0, 32.0))), Some(&json!({"instances": 9}))); assert!(matches!(d.finish().as_slice(), [Action::Commit])); } + + #[test] + fn a_tool_switch_cancels_a_radial_handle_drag() { + use crate::{PointerEvent, PointerKind, Tool}; + let (doc, selection) = radial(); + let paint = paint(); + let c = cx(&doc, &selection, &paint); + let h = RadialHandles::of(&doc, &selection, crate::select::selection_box(&c), c.zoom).unwrap(); + let out = (h.radius_at - h.center) / 100.0; + let to = h.radius_at + out * 25.0; + let mut t = crate::select::SelectionTool::default(); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, h.radius_at.x, h.radius_at.y)).is_empty()); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y)); + assert_eq!(preview(&a), Some(&json!({"radius": 125.0})), "{a:?}"); + assert_eq!(t.deactivate(&c), vec![Action::Cancel]); + assert!(!t.busy()); + // A press that has not changed the repeat leaves nothing to cancel. + t.pointer(&c, &PointerEvent::new(PointerKind::Down, h.radius_at.x, h.radius_at.y)); + assert!(t.busy()); + assert!(t.deactivate(&c).is_empty()); + assert!(!t.busy()); + } } diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 700c045d3f..acfd13d3ae 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}; @@ -80,6 +81,18 @@ fn marquee_enclosed(cx: &ToolContext, inverted: bool, directional_inside: bool) inside != inverted } +/// What a press took the selection by, which decides what that point snaps to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Grip { + /// A center or the pressed point: it lands on anchors and centers, or the bounds line up. + Point, + /// One of its anchors: it also lands on paths and where they cross ([`MoveSnap::by_anchor`]). + Anchor, + /// A point of a path's stroke, outline or edge ([`hold_point`]): it also lands on paths and + /// where they cross, and along a straight path the bounds still line up ([`MoveSnap::by_edge`]). + Edge, +} + #[derive(Clone, Debug, Default)] enum State { #[default] @@ -93,9 +106,9 @@ enum State { /// The point that snaps, moving with the pointer: `start`, or where a press on a path's /// stroke or beside its edge took hold of the path ([`hold_point`]). hold: Point, - /// The press grabbed the selection by an anchor (`start`): it snaps as - /// [`MoveSnap::by_anchor`] says. - by_anchor: bool, + /// What the press took the selection by: an anchor (`start`), a point of a path's edge + /// (`hold`), or neither. + grip: Grip, began: bool, /// Shift-pressed on this selected object: released without a drag, it leaves the /// selection. @@ -134,6 +147,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. @@ -150,6 +165,8 @@ enum State { GridRepeat(crate::repeat_grid::GridDrag), /// Drag a radial repeat's instances or radius handle. RadialRepeat(crate::repeat_radial::RadialDrag), + /// Drag the divider of an Image Trace object in the Split view. + TraceSplit(crate::trace_split::SplitDrag), /// Dragging a bracket of type on a path. Bracket(BracketDrag), /// Dragging a 9-slice guide of the symbol being edited. @@ -249,6 +266,8 @@ pub(crate) struct MoveSnap { /// onto (#1534), and lines the bounds up with (#5746), within the Snapping Tolerance as drawing /// does; `points` holds them with Smart Guides off. rulers: Option, + /// Held by a point of a path's edge ([`Self::by_edge`]). + by_edge: bool, } impl MoveSnap { @@ -263,6 +282,13 @@ impl MoveSnap { Self::gather(cx, Targets::for_move_by_anchor) } + /// [`Self::by_anchor`] for a selection held by a point of a path's stroke, outline or edge + /// (#8568): that point also lands on the other art's paths and where they cross, and on a + /// straight path the bounds still line up, sliding along it ([`Targets::snap_held_onto_path`]). + pub(crate) fn by_edge(cx: &ToolContext) -> Self { + Self { by_edge: true, ..Self::gather(cx, Targets::for_move_by_anchor) } + } + fn gather(cx: &ToolContext, for_move: fn(&ToolContext, &[NodeId]) -> Targets) -> Self { let guides = cx.smart_guides && !cx.snap_to_grid; let points = |exclude: &[NodeId]| if cx.snap_to_grid { None } else { Targets::snap_to_point(cx, exclude) }; @@ -273,13 +299,14 @@ impl MoveSnap { copy_targets: guides.then(|| for_move(cx, &[])), copy_points: points(&[]), rulers: (guides && cx.snap_to_point).then(|| Targets::rulers(cx)), + by_edge: false, } } /// Snap to Grid and Snap to Pixel alone, for a move whose box is `bounds`: the grid lands an /// edge of the box on a gridline, and pixels put its top-left on whole pixels. pub(crate) fn grid_only(bounds: Option) -> Self { - Self { bounds, targets: None, points: None, copy_targets: None, copy_points: None, rulers: None } + Self { bounds, targets: None, points: None, copy_targets: None, copy_points: None, rulers: None, by_edge: false } } /// The move (`copy`: the copy) by `d` of the selection grabbed at `start`, snapped, and its @@ -314,9 +341,14 @@ impl MoveSnap { d = q - start; guides = ov; taken = [true; 2]; - } else if let Some((q, ov)) = t.snap_onto_path(start + d, cx.snap_tol(), self.rulers.as_ref()) { + } else if let Some((q, ov)) = if self.by_edge { + t.snap_held_onto_path(start + d, b + d, cx.snap_tol(), self.rulers.as_ref()) + } else { + t.snap_onto_path(start + d, cx.snap_tol(), self.rulers.as_ref()) + } { // Grabbed by an anchor ([`Self::by_anchor`]), it lands on a path near it, or where - // the path crosses another or a ruler guide, instead of lining the bounds up. + // the path crosses another or a ruler guide, instead of lining the bounds up. Held + // by its edge ([`Self::by_edge`]), along a straight path the bounds still line up. d = q - start; guides = ov; taken = [true; 2]; @@ -596,7 +628,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. @@ -641,8 +678,13 @@ const HOVER_REACH: f64 = 6.0; /// hit, when the press is on its stroke or outline or within [`HOVER_REACH`] of it, else `p` /// ([`hold_on_path`]). That point snaps, so the path itself lands on a ruler guide (#3701). pub(crate) fn hold_point(cx: &ToolContext, h: &Hit, p: Point) -> Point { + held_on_path(cx, h, p).unwrap_or(p) +} + +/// [`hold_point`]'s point of the path hit, None when the press holds no point of it. +fn held_on_path(cx: &ToolContext, h: &Hit, p: Point) -> Option { let reach = if matches!(h.kind, HitKind::Stroke | HitKind::Outline) { f64::INFINITY } else { cx.tol(HOVER_REACH) }; - cx.doc.node(h.leaf).and_then(|n| n.path_data()).and_then(|pd| hold_on_path(pd, p, reach)).unwrap_or(p) + cx.doc.node(h.leaf).and_then(|n| n.path_data()).and_then(|pd| hold_on_path(pd, p, reach)) } /// While an opacity mask or a pattern is edited, a Shaper double-click selects a Shaper Group's @@ -822,8 +864,8 @@ 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 - /// axis, a grid repeat's handles, a ruler guide) cancels it: what it changed goes back, no copy + /// 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, an Image Trace divider, 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. fn key(&mut self, cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec { @@ -859,6 +901,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 +939,20 @@ 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, a + /// polygon's side widget, a mirror axis, a grid or radial repeat's handles or an Image Trace + /// divider 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::Mirror(d) => d.cancel(), + State::GridRepeat(d) => d.cancel(), + State::RadialRepeat(d) => d.cancel(), + State::TraceSplit(d) => d.cancel(), + State::BlendWidget(_) | State::Corner(_) | State::Pie(_) => vec![], other => { self.state = other; vec![] @@ -908,7 +965,9 @@ impl Tool for SelectionTool { State::Marquee { .. } => key == ToolKey::Letter('e'), State::Corner(_) => matches!(key, ToolKey::Up | ToolKey::Down), State::BlendWidget(_) => matches!(key, ToolKey::Up | ToolKey::Down | ToolKey::Left | ToolKey::Right), - State::Loaded { .. } | State::Mirror(_) | State::GridRepeat(_) | State::RadialRepeat(_) | State::NineSlice(_) => key == ToolKey::Escape, + State::Loaded { .. } | State::Mirror(_) | State::GridRepeat(_) | State::RadialRepeat(_) | State::TraceSplit(_) | State::NineSlice(_) => { + key == ToolKey::Escape + } _ => false, } } @@ -942,6 +1001,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(), @@ -951,6 +1011,7 @@ impl Tool for SelectionTool { State::Mirror(d) => d.adjusting(), State::GridRepeat(d) => d.adjusting(), State::RadialRepeat(d) => d.adjusting(), + State::TraceSplit(d) => d.adjusting(), _ => false, } } @@ -1010,7 +1071,7 @@ impl Tool for SelectionTool { { let several = cx.selection.objects.len() > 1 || !cx.selection.guides.is_empty(); let (deselect, key) = if m.shift { (Some(id), None) } else { (None, (several && !m.alt).then_some(id)) }; - self.state = State::Moving { start: p, press: p, hold: center, by_anchor: false, began: false, deselect, key, exclude: None }; + self.state = State::Moving { start: p, press: p, hold: center, grip: Grip::Point, began: false, deselect, key, exclude: None }; return vec![]; } // 3. Objects: Cmd/Ctrl-click selects the one under the selected one (cycling). @@ -1019,7 +1080,7 @@ impl Tool for SelectionTool { && let Some(behind) = object_behind(cx, p) { self.state = - State::Moving { start: p, press: p, hold: p, by_anchor: false, began: false, deselect: None, key: None, exclude: None }; + State::Moving { start: p, press: p, hold: p, grip: Grip::Point, began: false, deselect: None, key: None, exclude: None }; return vec![Action::Exec("select.set".into(), json!({ "ids": [behind.0] }))]; } let (hit, scope) = match selected_source_hit(cx, p) { @@ -1041,9 +1102,13 @@ impl Tool for SelectionTool { out.push(Action::Exec("select.set".into(), json!({ "ids": [top.0] }))); } // Grabbed by no anchor or centre, a press on a path's stroke or beside its - // edge holds the path there, and that point of it snaps (#3701). - let hold = if grabbed.is_some() { grab } else { hold_point(cx, &h, p) }; - self.state = State::Moving { start: grab, press: p, hold, by_anchor, began: false, deselect, key, exclude }; + // edge holds the path there, and that point of it snaps (#3701). Like a + // grabbed anchor, that point also lands on the other art's paths (#8568). + let (hold, grip) = match grabbed { + Some(_) => (grab, if by_anchor { Grip::Anchor } else { Grip::Point }), + None => held_on_path(cx, &h, p).map_or((p, Grip::Point), |q| (q, Grip::Edge)), + }; + self.state = State::Moving { start: grab, press: p, hold, grip, began: false, deselect, key, exclude }; out } None => { @@ -1052,8 +1117,8 @@ impl Tool for SelectionTool { } } } - (PointerKind::Drag, State::Moving { start, press, hold, by_anchor, began, exclude, .. }) => { - self.drag_moving(cx, p, m, ev.backquote, (start, press, hold, by_anchor, began), exclude) + (PointerKind::Drag, State::Moving { start, press, hold, grip, began, exclude, .. }) => { + self.drag_moving(cx, p, m, ev.backquote, (start, press, hold, grip, began), exclude) } (PointerKind::Drag, State::Scaling { handle, bx, areas }) => { self.last_backquote = ev.backquote; @@ -1121,6 +1186,17 @@ 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(mut d)) => { + self.state = State::Idle; + let mut out = d.drag(cx, p); + out.extend(d.finish()); + out + } (PointerKind::Drag, State::BlendWidget(mut d)) => { let out = d.drag(cx, p); self.state = State::BlendWidget(d); @@ -1199,7 +1275,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 +1304,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)), @@ -1267,6 +1344,9 @@ impl Tool for SelectionTool { if let State::RadialRepeat(d) = &self.state { return d.cursor(cx); } + if let State::TraceSplit(d) = &self.state { + return d.cursor(cx); + } if matches!(self.state, State::NineSlice(_)) || (matches!(self.state, State::Idle) && crate::nineslice::over_guide(cx, p)) { return Cursor::Move; } @@ -1274,8 +1354,10 @@ impl Tool for SelectionTool { && !m.cmd && !m.ctrl && !m.alt - && let Some(cursor) = - crate::mirror::cursor(cx, p).or_else(|| crate::repeat_grid::cursor(cx, p)).or_else(|| crate::repeat_radial::cursor(cx, p)) + && let Some(cursor) = crate::mirror::cursor(cx, p) + .or_else(|| crate::repeat_grid::cursor(cx, p)) + .or_else(|| crate::repeat_radial::cursor(cx, p)) + .or_else(|| crate::trace_split::cursor(cx, p)) { return cursor; } @@ -1287,7 +1369,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 +1400,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 +1465,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)) } @@ -1630,6 +1721,21 @@ impl SelectionTool { _ => return Some(vec![]), } } + if let State::TraceSplit(mut d) = self.state.clone() { + match ev.kind { + PointerKind::Drag | PointerKind::Up => { + let mut out = d.drag(cx, ev.pos); + if ev.kind == PointerKind::Up { + out.extend(d.finish()); + self.state = State::Idle; + } else { + self.state = State::TraceSplit(d); + } + return Some(out); + } + _ => return Some(vec![]), + } + } if matches!(self.state, State::Idle) && ev.kind == PointerKind::Down && let Some(d) = crate::mirror::MirrorDrag::hit(cx, ev.pos, ev.mods) @@ -1654,6 +1760,14 @@ impl SelectionTool { self.hover = None; return Some(vec![]); } + if matches!(self.state, State::Idle) + && ev.kind == PointerKind::Down + && let Some(d) = crate::trace_split::SplitDrag::hit(cx, ev.pos, ev.mods) + { + self.state = State::TraceSplit(d); + self.hover = None; + return Some(vec![]); + } None } @@ -1684,6 +1798,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 +1841,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 +1851,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![]); @@ -1795,7 +1917,16 @@ impl SelectionTool { /// `by_anchor`: `grab` is an anchor of it. fn press_nothing(&mut self, cx: &ToolContext, p: Point, grab: Point, by_anchor: bool, m: Mods) { self.state = if !m.shift && selected_hidden_at(cx.doc, p, cx.selection_hit_options(), &cx.selection.objects).is_some() { - State::Moving { start: grab, press: p, hold: grab, by_anchor, began: false, deselect: None, key: None, exclude: None } + State::Moving { + start: grab, + press: p, + hold: grab, + grip: if by_anchor { Grip::Anchor } else { Grip::Point }, + began: false, + deselect: None, + key: None, + exclude: None, + } } else { State::Marquee { start: p, cur: p, toggle: m.shift, enclosed: false, directional_inside: false } }; @@ -1807,7 +1938,7 @@ impl SelectionTool { p: Point, m: Mods, backquote: bool, - (start, press, hold, by_anchor, began): (Point, Point, Point, bool, bool), + (start, press, hold, grip, began): (Point, Point, Point, Grip, bool), exclude: Option<(NodeId, NodeId)>, ) -> Vec { let mut out = vec![]; @@ -1815,7 +1946,11 @@ impl SelectionTool { if p.distance(press) < Self::drag_threshold(cx) { return out; } - let gather = if by_anchor { MoveSnap::by_anchor } else { MoveSnap::new }; + let gather = match grip { + Grip::Point => MoveSnap::new, + Grip::Anchor => MoveSnap::by_anchor, + Grip::Edge => MoveSnap::by_edge, + }; // A Shift-drag from a highlighted object of the Global Edit selects it and moves it // with the selection: its snap targets are gathered for the selection with it. self.moving = Some(match exclude { @@ -1836,7 +1971,7 @@ impl SelectionTool { } // Shift has already constrained `d`: any change is a snap. self.snapped = (d - unsnapped).hypot() > 1e-9; - self.state = State::Moving { start, press, hold, by_anchor, began: true, deselect: None, key: None, exclude: None }; + self.state = State::Moving { start, press, hold, grip, began: true, deselect: None, key: None, exclude: None }; self.measure = cx.measurement_labels.then(|| (p, cx.offset_label(d.x, d.y))); let mut params = json!({ "matrix": matrix_json(Affine::translate(d)), "copy": m.alt }); if backquote { diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index a8e1f8acee..82588992b7 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] @@ -187,10 +247,23 @@ fn doc_with_rect_and_lines(lines: &[(Point, Point)]) -> (vectorcraft_doc::Docume /// The rectangle of `d` grabbed at `(gx, gy)` (hovered first, so a press near an anchor grabs it) /// and dragged to `to`, with Smart Guides on or off (`smart`): the point it was grabbed at after the /// move, and the label shown. -fn grabbed_and_dragged(d: &vectorcraft_doc::Document, id: NodeId, smart: bool, (gx, gy): (f64, f64), to: (f64, f64)) -> (Point, Option) { +fn grabbed_and_dragged(d: &vectorcraft_doc::Document, id: NodeId, smart: bool, grab: (f64, f64), to: (f64, f64)) -> (Point, Option) { + grabbed_and_dragged_in(d, id, smart, false, grab, to) +} + +/// [`grabbed_and_dragged`] in Preview or, with `outline`, in Outline view. +fn grabbed_and_dragged_in( + d: &vectorcraft_doc::Document, + id: NodeId, + smart: bool, + outline: bool, + (gx, gy): (f64, f64), + to: (f64, f64), +) -> (Point, Option) { let (none, mut picked, p) = (Selection::default(), Selection::default(), paint()); picked.add(id); - let (before, after) = (ToolContext { smart_guides: smart, ..cx(d, &none, &p) }, ToolContext { smart_guides: smart, ..cx(d, &picked, &p) }); + let (before, after) = + (ToolContext { smart_guides: smart, outline, ..cx(d, &none, &p) }, ToolContext { smart_guides: smart, outline, ..cx(d, &picked, &p) }); let mut t = SelectionTool::default(); t.pointer(&before, &ev(PointerKind::Move, gx, gy)); t.pointer(&before, &ev(PointerKind::Down, gx, gy)); @@ -226,6 +299,199 @@ fn a_move_grabbed_by_an_anchor_lands_it_on_another_path() { assert!(off_line(corner) > 0.4, "the corner lands at {corner:?}"); } +/// #8568: a selection held by a point of its path's edge (pressed on the edge, or on the fill just +/// beside it) lands that point on another path ("path") with Smart Guides, in Preview and in +/// Outline view. +#[test] +fn a_move_held_by_a_paths_edge_lands_it_on_another_path() { + let (a, b) = (Point::new(300.0, 400.0), Point::new(500.0, 300.0)); + let (d, id) = doc_with_rect_and_lines(&[(a, b)]); + let off_line = |q: Point| ((b - a).cross(q - a) / (b - a).hypot()).abs(); + for outline in [false, true] { + // Hold the rectangle by its bottom edge at (150, 200), away from its corners and center, + // and drop that point half a point beside the line. + let (edge, label) = grabbed_and_dragged_in(&d, id, true, outline, (150.0, 200.0), (430.0, 335.5)); + assert!(off_line(edge) < 1e-9, "outline {outline}: the edge lands at {edge:?}, {} off the line", off_line(edge)); + assert!((edge.x - 430.0).abs() < 0.5, "outline {outline}: {edge:?}"); + assert_eq!(label.as_deref(), Some("path"), "outline {outline}"); + // With Smart Guides off, the edge stays where it was dragged. + let (edge, _) = grabbed_and_dragged_in(&d, id, false, outline, (150.0, 200.0), (430.0, 335.5)); + assert!(off_line(edge) > 0.4, "outline {outline}: the edge lands at {edge:?}"); + } + // Pressed on the fill 3 points inside the bottom edge, the press holds the edge at + // (150, 200), and that point lands on the line. + let (edge, label) = pressed_and_dragged(&d, id, (150.0, 197.0), Point::new(150.0, 200.0), (430.0, 332.5), false); + assert!(off_line(edge) < 1e-9, "the edge lands at {edge:?}, {} off the line", off_line(edge)); + assert_eq!(label.as_deref(), Some("path")); +} + +/// The rectangle of `d` pressed at `press` (not hovered first) and dragged to `to`, Alt held for a +/// copy with `alt`: where its point `at` goes, and the label shown. +fn pressed_and_dragged( + d: &vectorcraft_doc::Document, + id: NodeId, + press: (f64, f64), + at: Point, + to: (f64, f64), + alt: bool, +) -> (Point, Option) { + pressed_and_dragged_with(d, id, press, at, to, alt, true) +} + +/// [`pressed_and_dragged`] with Smart Guides › Alignment Guides on or off (`lines`). +fn pressed_and_dragged_with( + d: &vectorcraft_doc::Document, + id: NodeId, + press: (f64, f64), + at: Point, + to: (f64, f64), + alt: bool, + lines: bool, +) -> (Point, Option) { + let (none, mut picked, p) = (Selection::default(), Selection::default(), paint()); + picked.add(id); + let (before, after) = + (ToolContext { alignment_guides: lines, ..cx(d, &none, &p) }, ToolContext { alignment_guides: lines, ..cx(d, &picked, &p) }); + let mut t = SelectionTool::default(); + t.pointer(&before, &ev(PointerKind::Down, press.0, press.1)); + let a = t.pointer(&after, &ev(PointerKind::Drag, to.0, to.1).with_mods(Mods { alt, ..Mods::default() })); + let Some(Action::Preview(_, v)) = a.iter().find(|a| matches!(a, Action::Preview(..))) else { panic!("{a:?}") }; + let label = t.overlays(&after).iter().find_map(|o| match o { + Overlay::Label { text, .. } => Some(text.clone()), + _ => None, + }); + (at + Vec2::new(v["matrix"][4].as_f64().unwrap(), v["matrix"][5].as_f64().unwrap()), label) +} + +/// #8568: a selection held by its edge that lands on a straight path still lines its bounds up +/// along that path: on a level path the held point keeps the path's y, and the bounds line up on +/// x with the other art, else with a ruler guide. A press on the fill farther inside than 6 points +/// holds no edge and lines the bounds up as before, and so does an edge hold with no path in reach. +#[test] +fn a_move_held_by_an_edge_on_a_straight_path_still_lines_its_bounds_up_along_it() { + let (mut d, id) = doc_with_rect_and_lines(&[(Point::new(300.0, 300.0), Point::new(500.0, 300.0))]); + // Held by the top edge at (130, 100) and dropped at (331, 300.5): the point lands on the path, + // and the left side (at 301) lines up with the path's start at x 300. + let top = Point::new(130.0, 100.0); + let (edge, label) = pressed_and_dragged(&d, id, (130.0, 100.0), top, (331.0, 300.5), false); + assert!(edge.distance(Point::new(330.0, 300.0)) < 1e-9, "the edge lands at {edge:?}"); + assert_eq!(label.as_deref(), Some("path")); + // With Alignment Guides off, no line shows, and the bounds still line up. + let (edge, _) = pressed_and_dragged_with(&d, id, (130.0, 100.0), top, (331.0, 300.5), false, false); + assert!(edge.distance(Point::new(330.0, 300.0)) < 1e-9, "the edge lands at {edge:?}"); + // A fill press 3 points inside the edge holds it the same way. + let (edge, _) = pressed_and_dragged(&d, id, (130.0, 103.0), top, (331.0, 303.5), false); + assert!(edge.distance(Point::new(330.0, 300.0)) < 1e-9, "the edge lands at {edge:?}"); + // A fill press 10 points inside holds no edge: the bounds line up on x, and the pressed point + // does not land on the path. + let (grip, _) = pressed_and_dragged(&d, id, (130.0, 110.0), Point::new(130.0, 110.0), (331.0, 300.5), false); + assert!(grip.distance(Point::new(330.0, 300.5)) < 1e-9, "the grip lands at {grip:?}"); + // Held by the edge with no path in reach, the bounds line up on x. + let (edge, _) = pressed_and_dragged(&d, id, (130.0, 100.0), top, (331.0, 280.0), false); + assert!(edge.distance(Point::new(330.0, 280.0)) < 1e-9, "the edge lands at {edge:?}"); + // With a ruler guide at x 320 and nothing else in line, the left side (at 321) goes onto it + // while the point stays on the path. + d.add_ruler_guide(&vectorcraft_doc::Guide::new(true, 320.0)); + let (edge, label) = pressed_and_dragged(&d, id, (130.0, 100.0), top, (351.0, 300.5), false); + assert!(edge.distance(Point::new(350.0, 300.0)) < 1e-9, "the edge lands at {edge:?}"); + assert_eq!(label.as_deref(), Some("path")); +} + +/// #8568: near the end of a steep straight path, the bounds of a selection held by its edge line +/// up by the shortest slide that keeps the held point on the path, not by a shorter one that +/// would take it past the path's end. +#[test] +fn a_move_held_by_an_edge_slides_only_within_the_path() { + let (a, b) = (Point::new(300.0, 300.0), Point::new(310.0, 400.0)); + // Two upright paths far below: lining the left side up with the one at 269.95 slides the + // held point 6.5 back along the path, past its start, and with the one at 271.343 slides it + // 7.5 on. + let (d, id) = doc_with_rect_and_lines(&[ + (a, b), + (Point::new(269.95, 440.0), Point::new(269.95, 490.0)), + (Point::new(271.343, 440.0), Point::new(271.343, 490.0)), + ]); + let u = (b - a) / (b - a).hypot(); + // Dropped on the path 6 points from its start, the top edge's point at (130, 100) leaves the + // left side at 30 points before it. + let q = a + u * 6.0; + let (edge, label) = pressed_and_dragged(&d, id, (130.0, 100.0), Point::new(130.0, 100.0), (q.x, q.y), false); + let off_line = (b - a).cross(edge - a) / (b - a).hypot(); + assert!(off_line.abs() < 1e-9, "the edge lands at {edge:?}, {off_line} off the path"); + assert!((edge.x - 30.0 - 271.343).abs() < 1e-9, "the left side lands at {}", edge.x - 30.0); + assert_eq!(label.as_deref(), Some("path")); +} + +/// #8568: a straight path drawn with its handles pulled out along it counts as straight, also +/// with a handle reaching past the far end while the curve stays between its ends: a selection +/// held by its edge slides along it to line its bounds up, as along a plain line. +#[test] +fn a_move_held_by_an_edge_slides_along_a_straight_path_with_handles() { + use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath}; + let (a, b) = (Point::new(300.0, 300.0), Point::new(500.0, 300.0)); + for (out, into) in [(350.0, 450.0), (520.0, 480.0)] { + let (mut d, id) = doc_with_rect(); + let l = d.layers[0].id; + let n = d.alloc_id(); + let anchors = vec![ + Anchor { p: a, h_in: a, h_out: Point::new(out, 300.0), kind: AnchorKind::Corner }, + Anchor { p: b, h_in: Point::new(into, 300.0), h_out: b, kind: AnchorKind::Corner }, + ]; + let path = PathData::single(SubPath::new(anchors, false)); + d.insert(Some(l), 1, vectorcraft_doc::Node::path(n, path, vectorcraft_doc::Appearance::default_art())).unwrap(); + let (edge, label) = pressed_and_dragged(&d, id, (130.0, 100.0), Point::new(130.0, 100.0), (331.0, 300.5), false); + assert!(edge.distance(Point::new(330.0, 300.0)) < 1e-9, "handles at {out} and {into}: the edge lands at {edge:?}"); + assert_eq!(label.as_deref(), Some("path")); + } +} + +/// #8568: an artboard's ruler guide ends at the artboard's edge. A selection held by its edge +/// slides along a shallow path onto such a guide when the slide brings its bounds within reach of +/// the guide's end, even though they start out beyond it. +#[test] +fn a_move_held_by_an_edge_slides_onto_an_artboard_guide_it_reaches() { + let (a, b) = (Point::new(640.0, 300.0), Point::new(440.0, 310.0)); + let (mut d, id) = doc_with_rect_and_lines(&[(a, b)]); + let u = (b - a) / (b - a).hypot(); + // Held by the left edge at (100, 130) and dropped on the path where x is 507: the top is 30 + // above the point, and the middle at x 557 is beyond the guide's end at 500 by more than half + // the width and the Snapping Tolerance. A slide of 6 along the path puts the top on the guide. + let q = a + u * ((a.x - 507.0) / -u.x); + let guide = q.y - 30.0 + u.y * 6.0; + let board = d.artboards[0].id; + d.add_ruler_guide(&vectorcraft_doc::Guide { artboard: Some(board), ..vectorcraft_doc::Guide::new(false, guide) }); + let (edge, label) = pressed_and_dragged(&d, id, (100.0, 130.0), Point::new(100.0, 130.0), (q.x, q.y), false); + assert!(edge.distance(q + u * 6.0) < 1e-9, "the edge lands at {edge:?}, not {:?}", q + u * 6.0); + assert_eq!(label.as_deref(), Some("path")); +} + +/// #8568: a selection held by its edge lands that point where two other paths cross, and where a +/// path crosses a ruler guide ("intersect"), as an anchor does. +#[test] +fn a_move_held_by_an_edge_lands_it_where_paths_cross() { + let bottom = Point::new(150.0, 200.0); + let (mut d, id) = + doc_with_rect_and_lines(&[(Point::new(300.0, 400.0), Point::new(500.0, 300.0)), (Point::new(460.0, 250.0), Point::new(460.0, 420.0))]); + let (edge, label) = pressed_and_dragged(&d, id, (150.0, 200.0), bottom, (460.4, 320.5), false); + assert!(edge.distance(Point::new(460.0, 320.0)) < 1e-9, "the edge lands at {edge:?}"); + assert_eq!(label.as_deref(), Some("intersect")); + d.add_ruler_guide(&vectorcraft_doc::Guide::new(true, 440.0)); + let (edge, label) = pressed_and_dragged(&d, id, (150.0, 200.0), bottom, (440.5, 330.5), false); + assert!(edge.distance(Point::new(440.0, 330.0)) < 1e-9, "the edge lands at {edge:?}"); + assert_eq!(label.as_deref(), Some("intersect")); +} + +/// #8568: an Alt copy held by its edge snaps to the original too: dragged along the original's +/// top edge, the held point stays on that edge and the copy's right side lines up with another +/// path. +#[test] +fn a_copy_held_by_an_edge_slides_along_the_originals_edge() { + let (d, id) = doc_with_rect_and_lines(&[(Point::new(230.0, 300.0), Point::new(230.0, 400.0))]); + let (edge, label) = pressed_and_dragged(&d, id, (130.0, 100.0), Point::new(130.0, 100.0), (161.0, 100.5), true); + assert!(edge.distance(Point::new(160.0, 100.0)) < 1e-9, "the edge lands at {edge:?}"); + assert_eq!(label.as_deref(), Some("path")); +} + /// #7411: a selection grabbed by an anchor lands it where two other paths cross ("intersect"), and /// on another object's anchor near the path rather than on the path. #[test] @@ -885,6 +1151,23 @@ fn a_shift_move_lands_the_edges_on_a_ruler_guide() { assert!(moved_by(m, (231.0, 0.0)), "{m:?}"); } +/// #4312: a diagonal Shift move reaches an artboard guide only where the move puts the bounds +/// within the guide's run: the middle at x 556 is beyond the guide's end at 500 by more than half +/// the width and the Snapping Tolerance, so the top (506) does not slide onto the guide at 503. +#[test] +fn a_diagonal_shift_move_reaches_an_artboard_guide_where_the_move_puts_it() { + let (mut d, id) = doc_with_rect(); + d.artboards[0].rect = Rect::new(0.0, 0.0, 500.0, 1600.0); + let board = d.artboards[0].id; + d.add_ruler_guide(&vectorcraft_doc::Guide { artboard: Some(board), ..vectorcraft_doc::Guide::new(false, 503.0) }); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let c = cx(&d, &s, &p); + let (m, _) = shift_moved(&c, (556.0, 556.0)); + assert!(moved_by(m, (406.0, 406.0)), "{m:?}"); +} + /// With Smart Guides on, a moved selection reaches a ruler guide within the Snapping Tolerance /// (4 px), as drawing and handle drags do; with Smart Guides off, Snap to Point reaches it within /// its own distance (2 px). @@ -2829,4 +3112,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/settings.rs b/crates/tools/src/settings.rs index 97e980e3c0..e823b5c9b1 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -20,10 +20,31 @@ pub const SYMBOLISM: &[&str] = const ROWS: &[Row] = &[ (&["dimension"], None, &["mode", "style"]), + (&[crate::quickpen::ID], None, &["action", "turn"]), // Global Brush Dimensions. (LIQUIFY, Some("liquify"), &["width", "height", "angle", "intensity", "usePressure", "showBrush"]), (LIQUIFY, None, &["detail", "simplify", "simplifyOn", "rate", "complexity", "horizontal", "vertical", "affectAnchors", "affectIn", "affectOut"]), - (SYMBOLISM, Some("symbolism"), &["diameter", "intensity", "density"]), + // Symbolism Tools Options: the general options, then the Symbol Sprayer's and the Symbol Sizer's. + ( + SYMBOLISM, + Some("symbolism"), + &[ + "diameter", + "intensity", + "density", + "usePressure", + "method", + "showBrush", + "sprayScrunch", + "spraySize", + "spraySpin", + "sprayScreen", + "sprayStain", + "sprayStyle", + "proportional", + "affectsDensity", + ], + ), (&["mirrorCut"], None, &["axis", "keep"]), (&["puppetWarp"], None, &["showMesh", "expand"]), (&["arc"], None, &["closed", "lengthX", "lengthY", "reference", "baseAlong", "slope", "fillArc"]), @@ -79,6 +100,7 @@ const ROWS: &[Row] = &[ (&[crate::addons::extend_path::ID], None, &["mode"]), (&[crate::addons::corner_tool::ID], None, &["radius", "kind"]), (&[crate::addons::shared_edge::ID], None, &["diameter", "tolerance", "together"]), + (&[crate::addons::tangent_circle::ID], None, &["radius"]), (&[crate::addons::smart_pen::ID], None, &["next"]), // The kind first: a new kind resets the values after it. (&[crate::addons::parametric_shape::ID], None, &["kind", "count", "a", "b", "radius", "width", "height", "rotation"]), diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index d4c8d4f36c..7376efd5b0 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 @@ -110,8 +113,7 @@ pub struct ShapeTool { began: bool, pub sides: u32, pub points: u32, - /// The anchors an ellipse made by a click has (the Ellipse dialog opens on it); 4 is a live - /// ellipse. + /// The anchors an ellipse has (the Ellipse dialog opens on it); 4 is a live ellipse. pub anchors: u32, pub corner_radius: f64, /// Star inner radius as a fraction of the outer radius. @@ -177,6 +179,7 @@ fn circle_through_points(points: &[Point]) -> (String, Value) { struct DragOptions { sides: u32, points: u32, + anchors: u32, corner_radius: f64, star_ratio: f64, } @@ -283,29 +286,33 @@ impl ShapeTool { } fn drag_options(&self) -> DragOptions { - DragOptions { sides: self.sides, points: self.points, corner_radius: self.corner_radius, star_ratio: self.star_ratio } + DragOptions { sides: self.sides, points: self.points, anchors: self.anchors, corner_radius: self.corner_radius, star_ratio: self.star_ratio } } /// Put back the options a canceled drag changed. fn restore_drag_options(&mut self, o: DragOptions) { self.sides = o.sides; self.points = o.points; + self.anchors = o.anchors; self.corner_radius = o.corner_radius; 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 +488,16 @@ 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(mut d)) => { + let mut out = d.drag(cx, ev.pos); + out.extend(d.finish()); + out + } None => vec![], }, _ => vec![], @@ -595,6 +608,8 @@ impl ShapeTool { let mut v = box_params(start, p, m, base); if self.id == "roundedRectangle" { v["radius"] = json!(self.corner_radius); + } else if self.id == "ellipse" && self.anchors != 4 { + v["anchors"] = json!(self.anchors); } (cmd.into(), v) } @@ -823,6 +838,12 @@ impl Tool for ShapeTool { _ => vec![], } } + /// Switching tools during a drag of a corner, pie or side widget cancels it, as Escape does: + /// the shape goes back. + fn deactivate(&mut self, cx: &ToolContext) -> Vec { + if self.widget.is_some() { self.key(cx, ToolKey::Escape, Mods::default()) } else { vec![] } + } + /// ↑/↓ change a polygon's sides, a star's points or the rounded rectangle's radius while it is /// drawn; Escape turns a widget or selection drag back. fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { @@ -838,6 +859,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![], @@ -872,6 +894,14 @@ impl Tool for ShapeTool { self.points = self.points.saturating_sub(1).max(3); true } + ("ellipse", ToolKey::Up) => { + self.anchors = self.anchors.saturating_add(1).min(1000); + true + } + ("ellipse", ToolKey::Down) => { + self.anchors = self.anchors.saturating_sub(1).max(2); + true + } ("roundedRectangle", ToolKey::Up) => { self.corner_radius = (self.corner_radius + 1.0).min(MAX_CORNER_RADIUS); true @@ -883,7 +913,9 @@ impl Tool for ShapeTool { _ => false, }; if changed { - let (c, v) = self.command_at(s, self.last, self.mods, cx.constrain_angle); + // A count-only key keeps the corner a tangent-snapped circle already showed. + let p = self.tangent_corner.map_or(self.last, |d| s + d); + let (c, v) = self.command_at(s, p, self.mods, cx.constrain_angle); vec![self.preview(c, v)] } else if key == ToolKey::Escape { self.start = None; @@ -920,6 +952,7 @@ impl Tool for ShapeTool { match &self.widget { Some(WidgetDrag::Corner(c)) => c.adjusting(), Some(WidgetDrag::Pie(d)) => d.adjusting(), + Some(WidgetDrag::Sides(d)) => d.adjusting(), None => match &self.selection { Some(SelectionDrag::Move { began, .. }) => *began, Some(SelectionDrag::Rotate { .. } | SelectionDrag::Scale { .. }) => true, @@ -956,6 +989,7 @@ impl Tool for ShapeTool { match &self.widget { Some(WidgetDrag::Corner(c)) => return c.overlays(cx), Some(WidgetDrag::Pie(d)) => return d.overlays(cx), + Some(WidgetDrag::Sides(d)) => return d.overlays(cx), None => {} } // A line on a common tangent shows that snap's guides, and its length and angle. @@ -1017,7 +1051,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 @@ -1082,6 +1116,7 @@ impl Tool for ShapeTool { match key { "sides" => b.sides = self.sides, "points" => b.points = self.points, + "anchors" => b.anchors = self.anchors, "cornerRadius" => b.corner_radius = self.corner_radius, "starRatio" => b.star_ratio = self.star_ratio, _ => {} diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index ec911f4cfb..59ae1d8e83 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -1309,6 +1309,211 @@ 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:?}"); +} + +/// With a shape tool, the side widget's release is read where it happens, with or without a drag +/// event there first, and switching tools during the drag puts the count back, as Escape does. +#[test] +fn a_shape_tools_side_widget_drag_ends_at_the_release_and_cancels_on_a_tool_switch() { + 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 at = |kind: PointerKind, px: f64| PointerEvent::new(kind, w.at.x, w.at.y + px); + let sides = |n: u32| Action::Preview("object.setLiveShape".into(), json!({ "id": id.0, "sides": n })); + let mut t = ShapeTool::new("polygon"); + t.pointer(&c, &at(PointerKind::Down, 0.0)); + assert_eq!(t.pointer(&c, &at(PointerKind::Drag, 12.0)), vec![Action::Begin("Live Shape".into()), sides(6)]); + assert_eq!(t.pointer(&c, &at(PointerKind::Up, 0.0)), vec![sides(5), Action::Cancel]); + assert!(!t.busy()); + t.pointer(&c, &at(PointerKind::Down, 0.0)); + t.pointer(&c, &at(PointerKind::Drag, 12.0)); + assert_eq!(t.pointer(&c, &at(PointerKind::Up, 24.0)), vec![sides(7), Action::Commit]); + t.pointer(&c, &at(PointerKind::Down, 0.0)); + t.pointer(&c, &at(PointerKind::Drag, 12.0)); + assert_eq!(t.deactivate(&c), vec![Action::Cancel]); + assert!(!t.busy() && !t.transforming()); + // A press that changed nothing sends nothing. + t.pointer(&c, &at(PointerKind::Down, 0.0)); + assert!(t.deactivate(&c).is_empty()); + assert!(!t.busy()); +} + +/// With Show Shape Widgets off, the shape tools neither show nor take a selected live rectangle's +/// corner widget, a live ellipse's pie widget or a live polygon's side widget: the pointer there is +/// the tool's own, a drag from there draws a new shape and a double-click asks for nothing. With it +/// on, the same drag adjusts the widget. +#[test] +fn hidden_shape_widgets_do_not_answer_a_shape_tool() { + 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 p = paint(); + 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 side = crate::sidewidget::SideWidget::for_tool(&cx(&polygon.0, &polygon.1, &p)).expect("a side widget").0.at; + // The corner widget 10 px inside the box's top-left corner, the pie widgets 12 px right of the + // ellipse, and the side widget. + let (far, m) = (Point::new(480.0, 480.0), Mods::default()); + for ((d, s), at) in [(&rect, Point::new(110.0, 110.0)), (&ellipse, Point::new(312.0, 150.0)), (&polygon, side)] { + let shown = cx(d, s, &p); + let hidden = ToolContext { shape_widgets: false, ..cx(d, s, &p) }; + let drag = |t: &mut ShapeTool, c: &ToolContext| { + t.pointer(c, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + let a = t.pointer(c, &PointerEvent::new(PointerKind::Drag, at.x + 20.0, at.y + 25.0)); + t.pointer(c, &PointerEvent::new(PointerKind::Up, at.x + 20.0, at.y + 25.0)); + a + }; + for id in ["rectangle", "roundedRectangle", "ellipse", "polygon", "star"] { + let mut t = ShapeTool::new(id); + assert_ne!(t.cursor(&shown, at, m), t.cursor(&shown, far, m), "{id} at {at:?}"); + assert_eq!(t.cursor(&hidden, at, m), t.cursor(&hidden, far, m), "{id} at {at:?}"); + let a = drag(&mut t, &shown); + assert!(matches!(a.last(), Some(Action::Preview(cmd, _)) if cmd == "object.setLiveShape"), "{id} at {at:?}: {a:?}"); + let a = drag(&mut t, &hidden); + assert!(matches!(a.last(), Some(Action::Preview(cmd, _)) if cmd.starts_with("shape.")), "{id} at {at:?}: {a:?}"); + assert!(t.pointer(&hidden, &PointerEvent::new(PointerKind::DoubleClick, at.x, at.y)).is_empty(), "{id} at {at:?}"); + assert!(!t.busy(), "{id}"); + } + } +} + +/// Switching away from a shape tool or the Selection tool during a drag of a corner, pie or side +/// widget cancels it, as Escape does: the shape goes back. After a press that has not moved there +/// is nothing to put back. +#[test] +fn a_tool_switch_cancels_a_widget_drag() { + use vectorcraft_doc::{Appearance, LiveShape, Node, NodeKind}; + let live = |shape: LiveShape| { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let (l, id) = (d.layers[0].id, d.alloc_id()); + let mut n = Node::path(id, shape.to_path(), Appearance::default_art()); + if let NodeKind::Path { live: slot, .. } = &mut n.kind { + *slot = Some(Box::new(shape)); + } + d.insert(Some(l), 0, n).unwrap(); + let mut s = Selection::default(); + s.add(id); + (d, s) + }; + let xf = Affine::translate((100.0, 100.0)); + let rect = live(LiveShape::Rectangle { w: 100.0, h: 100.0, radii: [0.0; 4], kinds: Default::default(), radii_relative: false, xf }); + let ellipse = live(LiveShape::Ellipse { w: 200.0, h: 100.0, pie: (0.0, 360.0), xf }); + let polygon = live(LiveShape::Polygon { + radius: 80.0, + sides: 5, + xf: Affine::translate((250.0, 250.0)), + radii: vec![], + kinds: vec![], + radii_relative: false, + }); + let p = paint(); + let side = crate::sidewidget::SideWidget::for_tool(&cx(&polygon.0, &polygon.1, &p)).expect("a side widget").0.at; + // The corner widget at (110, 110), the pie widget 12 px right of (300, 150), the side widget. + let drags = [ + (&rect, Point::new(110.0, 110.0), Point::new(130.0, 130.0)), + (&ellipse, Point::new(312.0, 150.0), Point::new(200.0, 20.0)), + (&polygon, side, side + Vec2::new(0.0, 25.0)), + ]; + for ((d, s), at, to) in drags { + let c = cx(d, s, &p); + let tools: [Box; 6] = [ + Box::new(crate::select::SelectionTool::default()), + Box::new(ShapeTool::new("rectangle")), + Box::new(ShapeTool::new("roundedRectangle")), + Box::new(ShapeTool::new("ellipse")), + Box::new(ShapeTool::new("polygon")), + Box::new(ShapeTool::new("star")), + ]; + for mut t in tools { + let id = t.id(); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)).is_empty(), "{id} at {at:?}"); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y)); + assert!(matches!(a.first(), Some(Action::Begin(_))), "{id} at {at:?}: {a:?}"); + assert_eq!(t.deactivate(&c), vec![Action::Cancel], "{id} at {at:?}"); + assert!(!t.busy() && !t.transforming(), "{id} at {at:?}"); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, to.x, to.y)).is_empty(), "{id} at {at:?}"); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + assert!(t.busy(), "{id} at {at:?}"); + assert!(t.deactivate(&c).is_empty(), "{id} at {at:?}"); + assert!(!t.busy(), "{id} at {at:?}"); + } + } +} + /// A double-click on a corner widget of a selected live shape, with a shape tool that shows the /// widgets, asks for the Transform panel and nothing else: neither click draws, edits or begins an /// undo step, and the tool stays idle. Line Segment, a plain path, a pie widget, a hidden or diff --git a/crates/tools/src/sidewidget.rs b/crates/tools/src/sidewidget.rs new file mode 100644 index 0000000000..f026a41c35 --- /dev/null +++ b/crates/tools/src/sidewidget.rs @@ -0,0 +1,499 @@ +//! 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 and the shape widgets showing). + pub fn for_tool(cx: &ToolContext) -> Option<(Self, OrientedBox)> { + // One object or none: a larger selection's box is not measured. + if !cx.shape_widgets || 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 or the shape widgets 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 hidden = ToolContext { shape_widgets: false, ..cx(&d, &s, &p) }; + assert!(SideWidget::for_tool(&hidden).is_none() && !over_widget(&hidden, w.at)); + assert!(SideDrag::hit(&hidden, &PointerEvent::new(PointerKind::Down, w.at.x, w.at.y)).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()); + } + + /// Switching tools during a drag puts the count back, as Escape does; a press that changed + /// nothing sends nothing. + #[test] + fn switching_tools_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)); + assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, w.at + vectorcraft_geom::Vec2::new(0.0, 30.0)))), [7]); + assert_eq!(t.deactivate(&c), vec![Action::Cancel]); + assert!(!t.busy() && !t.transforming()); + t.pointer(&c, &ev(PointerKind::Down, w.at)); + assert!(t.pointer(&c, &ev(PointerKind::Drag, w.at + vectorcraft_geom::Vec2::new(0.0, 6.0))).is_empty()); + assert!(t.deactivate(&c).is_empty()); + assert!(!t.busy() && !t.transforming()); + } + + /// The release is read where it happens, with or without a drag event there first: back at the + /// start the polygon keeps its count with no undo step, and further down it takes the new count. + #[test] + fn the_release_position_sets_the_sides() { + let (d, id, 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 at = |px: f64| w.at + vectorcraft_geom::Vec2::new(0.0, px); + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at)); + assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, at(12.0)))), [6]); + assert_eq!( + t.pointer(&c, &ev(PointerKind::Up, w.at)), + vec![Action::Preview("object.setLiveShape".into(), json!({ "id": id.0, "sides": 5 })), Action::Cancel] + ); + assert!(!t.busy() && !t.transforming()); + t.pointer(&c, &ev(PointerKind::Down, w.at)); + assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, at(12.0)))), [6]); + assert_eq!( + t.pointer(&c, &ev(PointerKind::Up, at(24.0))), + vec![Action::Preview("object.setLiveShape".into(), json!({ "id": id.0, "sides": 7 })), Action::Commit] + ); + } + + /// A double-click on the widget with the Selection tool does nothing to the artwork under it. + #[test] + fn a_double_click_on_the_widget_leaves_the_artwork_under_it_alone() { + let (mut d, _, s) = polygon_doc(5, Affine::translate((300.0, 300.0))); + let p = paint(); + let (w, _) = SideWidget::for_tool(&cx(&d, &s, &p)).unwrap(); + let l = d.layers[0].id; + let under = d.alloc_id(); + let at = d.layers[0].children().map_or(0, |c| c.len()); + let r = vectorcraft_geom::Rect::new(w.at.x - 20.0, w.at.y - 20.0, w.at.x + 20.0, w.at.y + 20.0); + d.insert(Some(l), at, Node::path(under, vectorcraft_geom::shapes::rectangle(r), Appearance::default_art())).unwrap(); + let c = cx(&d, &s, &p); + assert!(over_widget(&c, w.at)); + let mut t = SelectionTool::default(); + assert!(t.pointer(&c, &ev(PointerKind::DoubleClick, w.at)).is_empty()); + // Beside the widget, the double-click reaches the artwork. + assert!(!t.pointer(&c, &ev(PointerKind::DoubleClick, w.at + vectorcraft_geom::Vec2::new(0.0, 15.0))).is_empty()); + } +} diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index b4dd9e631b..a4fc04e0cc 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -23,9 +23,26 @@ pub fn create(id: &str) -> Option> { }) } +/// The values of Method in the Symbolism Tools Options. +pub const METHODS: [&str; 3] = ["userDefined", "average", "random"]; + +/// The values of each Symbol Sprayer option in the Symbolism Tools Options. +pub const SPRAY_MODES: [&str; 2] = ["average", "userDefined"]; + +/// The Symbol Sprayer options: (tool option, key in `symbol.spray`'s `attributes`). +pub const SPRAY_ATTRIBUTES: [(&str, &str); 6] = [ + ("sprayScrunch", "scrunch"), + ("spraySize", "size"), + ("spraySpin", "spin"), + ("sprayScreen", "screen"), + ("sprayStain", "stain"), + ("sprayStyle", "style"), +]; + pub struct SymbolismTool { id: &'static str, - points: Vec, + /// The drag's points, each with its pen pressure (0..1). + points: Vec<(Point, f64)>, /// How many points the last preview had ([`previews_at`] thins previews of a long drag). previewed: usize, active: bool, @@ -41,6 +58,40 @@ pub struct SymbolismTool { pub symbol: Option, /// Graphic style for the Styler (None = the document's first non-default style). pub style: Option, + /// Use Pressure Pen: each point's pen pressure is the intensity there. + pub use_pressure: bool, + /// Method of the Scruncher, Sizer, Spinner, Stainer, Screener and Styler: one of [`METHODS`]. + pub method: &'static str, + /// Show Brush Size and Intensity: the brush outline follows the pointer. + pub show_brush: bool, + /// The Symbol Sprayer options, in the order of [`SPRAY_ATTRIBUTES`]: each one of [`SPRAY_MODES`]. + pub spray: [&'static str; 6], + /// Symbol Sizer: Proportional Resizing. + pub proportional: bool, + /// Symbol Sizer: Resizing Affects Density. + pub affects_density: bool, +} + +/// Checks the Symbolism Tools Options in `values` before `tool.setOption` sets any, when `tool` is +/// a symbolism tool, with the tool's own checks ([`Tool::check_option`]): a number out of its +/// range, `method` that is not one of [`METHODS`], a Symbol Sprayer option that is not one of +/// [`SPRAY_MODES`], and `usePressure`, `showBrush`, `proportional` or `affectsDensity` that is not +/// true or false are errors. Ok for every other tool, and for a key the tool does not report +/// (`tool.setOption` refuses that one as an unknown option). Saved settings go to the tool's +/// `set_option` instead, which skips a value it cannot read. +pub fn check_options(tool: &str, values: &serde_json::Map) -> Result<(), String> { + if !tool.starts_with("symbol") || create(tool).is_none() { + return Ok(()); + } + let tool = SymbolismTool::new(tool); + let known = tool.options(); + values.iter().filter(|(key, _)| known.get(key.as_str()).is_some()).try_for_each(|(key, v)| tool.check_option(key, v)) +} + +/// `v` as one of `allowed`, when it is one. +fn one_of(v: &Value, allowed: &[&'static str]) -> Option<&'static str> { + let s = v.as_str()?; + allowed.iter().copied().find(|a| *a == s) } impl SymbolismTool { @@ -67,6 +118,12 @@ impl SymbolismTool { density: 5.0, symbol: None, style: None, + use_pressure: false, + method: "userDefined", + show_brush: true, + spray: ["average"; 6], + proportional: true, + affects_density: false, } } @@ -86,14 +143,29 @@ impl SymbolismTool { /// The command + params for the gesture so far. pub fn command(&self, cx: &ToolContext) -> (String, Value) { let radius = self.diameter / 2.0; - let pts = points_json(&self.points); if self.id == "symbolSprayer" { - let mut v = json!({"points": pts, "radius": radius, "density": self.density, "alt": self.alt}); + let pts = points_json(&self.points.iter().map(|(p, _)| *p).collect::>()); + let attributes: serde_json::Map = + SPRAY_ATTRIBUTES.iter().zip(self.spray).map(|((_, key), mode)| (key.to_string(), json!(mode))).collect(); + let mut v = json!({"points": pts, "radius": radius, "density": self.density, "alt": self.alt, "attributes": attributes}); if let Some(s) = &self.symbol { v["name"] = json!(s); } + // Stain: User Defined stains the new instances with the fill color in its own model. + if self.spray[4] == "userDefined" + && let Some(c) = cx.paint.fill.color() + { + v["color"] = serde_json::to_value(c).unwrap_or(Value::Null); + v["keepModel"] = json!(true); + } + // A style the document no longer has (a deleted one) is left out: the default style applies. + if let Some(s) = self.style.as_ref().filter(|s| cx.doc.graphic_styles.iter().any(|g| g.name == **s)) { + v["style"] = json!(s); + } return ("symbol.spray".into(), v); } + let pressure = self.use_pressure; + let pts = Value::Array(self.points.iter().map(|(p, f)| if pressure { json!([p.x, p.y, f]) } else { json!([p.x, p.y]) }).collect()); let tool = match self.id { "symbolShifter" => "shift", "symbolScruncher" => "scrunch", @@ -113,6 +185,17 @@ impl SymbolismTool { if let Some(s) = &self.style { v["style"] = json!(s); } + if pressure { + v["usePressure"] = json!(true); + } + // The Symbol Shifter has no Method. + if tool != "shift" { + v["method"] = json!(self.method); + } + if tool == "size" { + v["proportional"] = json!(self.proportional); + v["affectsDensity"] = json!(self.affects_density); + } ("symbol.adjust".into(), v) } } @@ -140,9 +223,10 @@ impl Tool for SymbolismTool { fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { let p = ev.pos; self.hover = Some(p); + let sample = (p, f64::from(ev.pressure).clamp(0.0, 1.0)); match ev.kind { PointerKind::Down => { - self.points = vec![p]; + self.points = vec![sample]; self.previewed = 1; self.active = true; self.alt = ev.mods.alt; @@ -152,11 +236,15 @@ impl Tool for SymbolismTool { PointerKind::Drag if self.active => { // Sprayer: thin the samples to a fraction of the brush; others: every few pixels. let step = if self.id == "symbolSprayer" { (self.diameter * 0.15).max(cx.tol(3.0)) } else { cx.tol(3.0) }; + // With Use Pressure Pen a change of pressure of at least 0.05 is kept where the pen + // stays (the Sprayer does not use the pressure). + let pressed = self.use_pressure && self.id != "symbolSprayer"; + let thinned = self.points.last().is_some_and(|(l, f)| l.distance(p) < step && !(pressed && (sample.1 - f).abs() >= 0.05)); // Each preview carries every point so far: a long drag stops growing and previews less often. - if self.points.len() >= MAX_STROKE_SAMPLES || self.points.last().is_some_and(|l| l.distance(p) < step) { + if self.points.len() >= MAX_STROKE_SAMPLES || thinned { return vec![]; } - self.points.push(p); + self.points.push(sample); if !previews_at(self.points.len()) { return vec![]; } @@ -193,9 +281,16 @@ impl Tool for SymbolismTool { vec![] } fn overlays(&self, _cx: &ToolContext) -> Vec { - let Some(p) = self.hover else { return vec![] }; - let circle = kurbo::Circle::new(p, self.diameter / 2.0).to_path(0.1); - vec![Overlay::Path { path: circle, color: FEEDBACK, width: 1.0, dashed: false }] + let Some(p) = self.hover.filter(|_| self.show_brush) else { return vec![] }; + let ring = |radius: f64, dashed| Overlay::Path { path: kurbo::Circle::new(p, radius).to_path(0.1), color: FEEDBACK, width: 1.0, dashed }; + let mut v = vec![ring(self.diameter / 2.0, false)]; + // The intensity: a dashed ring that fills the brush at 10. A pen's pressure sets it instead + // with Use Pressure Pen, so no ring is drawn then. The Symbol Sprayer uses neither, so it + // draws no ring. + if self.id != "symbolSprayer" && !self.use_pressure && self.intensity < 10.0 { + v.push(ring(self.diameter / 2.0 * self.intensity / 10.0, true)); + } + v } fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { match self.id { @@ -210,7 +305,22 @@ impl Tool for SymbolismTool { } } fn options(&self) -> Value { - json!({"diameter": self.diameter, "intensity": self.intensity, "density": self.density, "symbol": self.symbol, "style": self.style}) + let mut v = json!({ + "diameter": self.diameter, + "intensity": self.intensity, + "density": self.density, + "symbol": self.symbol, + "style": self.style, + "usePressure": self.use_pressure, + "method": self.method, + "showBrush": self.show_brush, + "proportional": self.proportional, + "affectsDensity": self.affects_density, + }); + for ((key, _), mode) in SPRAY_ATTRIBUTES.iter().zip(self.spray) { + v[*key] = json!(mode); + } + v } fn set_option(&mut self, key: &str, v: &Value) { match key { @@ -219,15 +329,28 @@ impl Tool for SymbolismTool { "density" => self.density = v.as_f64().unwrap_or(self.density).clamp(1.0, 10.0), "symbol" => self.symbol = v.as_str().map(str::to_string), "style" => self.style = v.as_str().map(str::to_string), - _ => {} + "usePressure" => self.use_pressure = v.as_bool().unwrap_or(self.use_pressure), + "method" => self.method = one_of(v, &METHODS).unwrap_or(self.method), + "showBrush" => self.show_brush = v.as_bool().unwrap_or(self.show_brush), + "proportional" => self.proportional = v.as_bool().unwrap_or(self.proportional), + "affectsDensity" => self.affects_density = v.as_bool().unwrap_or(self.affects_density), + _ => { + if let Some(i) = SPRAY_ATTRIBUTES.iter().position(|(k, _)| *k == key) { + self.spray[i] = one_of(v, &SPRAY_MODES).unwrap_or(self.spray[i]); + } + } } } fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { use crate::option_check as c; + let must_be = |names: &[&str]| format!("`{key}` must be one of {}", names.join(", ")); 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), + "usePressure" | "showBrush" | "proportional" | "affectsDensity" => c::boolean(key, v), + "method" => one_of(v, &METHODS).map(drop).ok_or_else(|| must_be(&METHODS)), + k if SPRAY_ATTRIBUTES.iter().any(|(a, _)| *a == k) => one_of(v, &SPRAY_MODES).map(drop).ok_or_else(|| must_be(&SPRAY_MODES)), _ => Err(c::unknown(key)), } } @@ -391,6 +514,159 @@ mod tests { assert!(matches!(&a[1], Action::Preview(_, v) if v["color"] == fill && v["keepModel"] == true), "{a:?}"); } + /// The Symbolism Tools Options the tools keep, with what each is before it is set. + #[test] + fn the_options_dialog_fields_are_tool_options() { + let mut t = SymbolismTool::new("symbolSizer"); + let o = t.options(); + assert_eq!((o["usePressure"].clone(), o["method"].clone(), o["showBrush"].clone()), (json!(false), json!("userDefined"), json!(true))); + assert_eq!((o["proportional"].clone(), o["affectsDensity"].clone()), (json!(true), json!(false))); + for (key, _) in SPRAY_ATTRIBUTES { + assert_eq!(o[key], "average", "{key}"); + } + for (key, v) in [ + ("usePressure", json!(true)), + ("method", json!("random")), + ("showBrush", json!(false)), + ("proportional", json!(false)), + ("affectsDensity", json!(true)), + ("sprayStain", json!("userDefined")), + ] { + t.set_option(key, &v); + assert_eq!(t.options()[key], v, "{key}"); + } + // A value that is none of an option's choices leaves it as it was. + for (key, v) in [("method", json!("smooth")), ("method", json!(2)), ("sprayStain", json!("random")), ("usePressure", json!("yes"))] { + let before = t.options(); + t.set_option(key, &v); + assert_eq!(t.options(), before, "{key}: {v}"); + } + } + + /// The adjusting tools send the Method (the Shifter has none), the Sizer its two options, and + /// with Use Pressure Pen each point's pen pressure. + #[test] + fn adjust_tools_send_the_method_the_sizer_options_and_the_pen_pressure() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let press = |t: &mut SymbolismTool| { + let down = PointerEvent { pressure: 0.25, ..PointerEvent::new(PointerKind::Down, 5.0, 5.0) }; + match t.pointer(&cx, &down).swap_remove(1) { + Action::Preview(_, v) => v, + other => panic!("{other:?}"), + } + }; + let mut sizer = SymbolismTool::new("symbolSizer"); + let v = press(&mut sizer); + assert_eq!((v["method"].clone(), v["proportional"].clone(), v["affectsDensity"].clone()), (json!("userDefined"), json!(true), json!(false))); + assert_eq!((v["points"].clone(), v.get("usePressure")), (json!([[5.0, 5.0]]), None)); + sizer.set_option("usePressure", &json!(true)); + sizer.set_option("method", &json!("average")); + sizer.set_option("affectsDensity", &json!(true)); + let v = press(&mut sizer); + assert_eq!((v["points"].clone(), v["usePressure"].clone()), (json!([[5.0, 5.0, 0.25]]), json!(true))); + assert_eq!((v["method"].clone(), v["affectsDensity"].clone()), (json!("average"), json!(true))); + let mut shifter = SymbolismTool::new("symbolShifter"); + shifter.set_option("method", &json!("random")); + let v = press(&mut shifter); + assert!(v.get("method").is_none() && v.get("proportional").is_none(), "{v}"); + let mut spinner = SymbolismTool::new("symbolSpinner"); + spinner.set_option("method", &json!("random")); + let v = press(&mut spinner); + assert!(v["method"] == "random" && v.get("proportional").is_none(), "{v}"); + } + + /// With Use Pressure Pen a drag sample where the pen stays is kept when the pressure changes; + /// without it, or with the same pressure, the drag keeps thinning the samples by distance. + #[test] + fn a_pressure_change_where_the_pen_stays_is_kept() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let stroke = |use_pressure: bool, pressures: [f32; 3]| { + let mut t = SymbolismTool::new("symbolSizer"); + t.set_option("usePressure", &json!(use_pressure)); + let at = |kind, pressure| PointerEvent { pressure, ..PointerEvent::new(kind, 5.0, 5.0) }; + let events = + [(PointerKind::Down, pressures[0]), (PointerKind::Drag, pressures[1]), (PointerKind::Drag, pressures[2]), (PointerKind::Up, 0.0)]; + // The points of the last preview, the one the drag commits. + let mut last = Value::Null; + for (kind, pressure) in events { + for a in t.pointer(&cx, &at(kind, pressure)) { + if let Action::Preview(_, v) = a { + last = v["points"].clone(); + } + } + } + last + }; + assert_eq!(stroke(true, [0.0, 1.0, 1.0]), json!([[5.0, 5.0, 0.0], [5.0, 5.0, 1.0]])); + assert_eq!(stroke(true, [0.5, 0.52, 0.5]), json!([[5.0, 5.0, 0.5]])); + assert_eq!(stroke(false, [0.0, 1.0, 1.0]), json!([[5.0, 5.0]])); + } + + /// The Sprayer sends its six options as `attributes`, and the fill color only while Stain is + /// User Defined. + #[test] + fn the_sprayer_sends_its_attributes() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = SymbolismTool::new("symbolSprayer"); + t.set_option("usePressure", &json!(true)); + let spray = |t: &mut SymbolismTool| match t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 5.0, 5.0)).swap_remove(1) { + Action::Preview(c, v) if c == "symbol.spray" => v, + other => panic!("{other:?}"), + }; + let v = spray(&mut t); + let average = + json!({"scrunch": "average", "size": "average", "spin": "average", "screen": "average", "stain": "average", "style": "average"}); + assert_eq!((v["attributes"].clone(), v.get("color"), v["points"].clone()), (average, None, json!([[5.0, 5.0]]))); + t.set_option("sprayStain", &json!("userDefined")); + t.set_option("spraySpin", &json!("userDefined")); + let v = spray(&mut t); + assert_eq!( + (v["attributes"]["stain"].clone(), v["attributes"]["spin"].clone(), v["attributes"]["size"].clone()), + (json!("userDefined"), json!("userDefined"), json!("average")) + ); + assert_eq!((v["color"].clone(), v["keepModel"].clone()), (serde_json::to_value(p.fill.color().unwrap()).unwrap(), json!(true))); + } + + /// Show Brush Size and Intensity: the brush's outline with a dashed ring for the intensity + /// inside it; no ring with Use Pressure Pen, at intensity 10 or for the Symbol Sprayer, and + /// nothing with it off. + #[test] + fn show_brush_size_and_intensity_draws_the_brush() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = SymbolismTool::new("symbolScruncher"); + assert!(t.overlays(&cx).is_empty(), "no pointer yet"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 50.0, 50.0)); + let rings = |t: &SymbolismTool| { + t.overlays(&cx) + .into_iter() + .map(|o| match o { + Overlay::Path { path, dashed, .. } => (path.bounding_box().width().round(), dashed), + other => panic!("{other:?}"), + }) + .collect::>() + }; + assert_eq!(rings(&t), [(80.0, false), (40.0, true)]); + t.set_option("intensity", &json!(10)); + assert_eq!(rings(&t), [(80.0, false)]); + t.set_option("intensity", &json!(2)); + t.set_option("usePressure", &json!(true)); + assert_eq!(rings(&t), [(80.0, false)]); + t.set_option("showBrush", &json!(false)); + assert!(t.overlays(&cx).is_empty()); + // The Symbol Sprayer uses neither Intensity nor pen pressure: the outline only. + let mut t = SymbolismTool::new("symbolSprayer"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 50.0, 50.0)); + assert_eq!(rings(&t), [(80.0, false)]); + } + #[test] fn brackets_change_diameter_and_intensity() { let (d, _) = doc_with_rect(); diff --git a/crates/tools/src/text.rs b/crates/tools/src/text.rs index fb7e38bd0f..8348cb15bd 100644 --- a/crates/tools/src/text.rs +++ b/crates/tools/src/text.rs @@ -43,10 +43,13 @@ use vectorcraft_text::{FontDb, TextLayout, edit}; use crate::guides::DrawSnap; use crate::{Action, Cursor, ImeSurrounding, Mods, Overlay, PointerEvent, PointerKind, SurroundingUnit, Tool, ToolContext, ToolKey}; +mod missing; mod plain; mod ports; mod tool; +pub use missing::MISSING_FONT_EDIT; +use missing::PendingEdit; #[cfg(test)] use plain::char_range_to_bytes; use plain::common_affixes; @@ -228,6 +231,8 @@ pub struct TypeTool { stepped: bool, /// The state at the start of each `command.batch` still running, innermost last. batches: Vec, + /// The edit of type set in fonts that aren't available whose question is open ([`missing`]). + pending_edit: Option, cache: Mutex>, /// The other frames' layouts the last overlays drew ([`FrameLayouts`]): each overlays call /// keeps only the frames it draws. @@ -815,18 +820,69 @@ 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, and so does a click anywhere + /// inside area type's frame. 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> { - let h = hit_test(cx.doc, p, vectorcraft_doc::hit::HitOptions { type_path_only: false, ..cx.hit_options() })?; + self.pending_edit = None; + let opt = vectorcraft_doc::hit::HitOptions { type_path_only: false, area_type_interior: true, ..cx.hit_options() }; + let h = hit_test(cx.doc, p, opt)?; let Some(NodeKind::Text(t)) = cx.doc.node(h.leaf).map(|n| &n.kind) else { return None }; let lay = self.layout(t); let byte = vectorcraft_text::hit_byte(&lay, t.xf.inverse() * p); + let same_story = self.editing.is_some_and(|e| cx.doc.story_of(e).contains(&h.leaf)); + if !same_story { + let fonts = missing::unavailable_fonts(cx.doc, h.leaf); + if !fonts.0.is_empty() { + let token = next_edit_session(); + self.pending_edit = Some(PendingEdit { token, revision: cx.revision, id: h.leaf, byte, accepted: false }); + self.clicks = (None, 0); + return Some(vec![Action::Dialog(MISSING_FONT_EDIT.into(), missing::question(token, h.leaf, &fonts))]); + } + } + Some(self.begin_edit(cx, h.leaf, byte, p)) + } + + /// End the previous edit and edit type `id` with the caret at `byte` (clicked at `p`), selecting + /// it → the actions. + fn begin_edit(&mut self, cx: &ToolContext, id: NodeId, byte: usize, p: Point) -> Vec { let mut out = self.finish(cx); - self.start_editing(h.leaf, byte); + self.start_editing(id, byte); self.remember(cx); self.clicks = (Some(p), 1); - out.push(Action::Exec("select.set".into(), json!({"ids": [h.leaf.0]}))); - Some(out) + out.push(Action::Exec("select.set".into(), json!({"ids": [id.0]}))); + out + } + + /// The answer to the [`MISSING_FONT_EDIT`] question whose token is `token`: OK (`ok`) lets the + /// next [`Tool::poll`] start the edit, Cancel forgets it. An answer to another question is + /// ignored. + fn answer_edit(&mut self, token: u64, ok: bool) { + let Some(e) = self.pending_edit.as_mut().filter(|e| e.token == token) else { return }; + if ok { + e.accepted = true; + } else { + self.pending_edit = None; + } + } + + /// Start the edit OK accepted: the caret goes where the type was clicked. Nothing starts when + /// the document changed since the question, or the type is gone. + fn resume_edit(&mut self, cx: &ToolContext) -> Vec { + let Some(e) = self.pending_edit.take_if(|e| e.accepted) else { return vec![] }; + if e.revision != cx.revision { + return vec![]; + } + let Some(t) = Self::text(cx, e.id) else { return vec![] }; + let text = t.plain_text(); + let mut byte = e.byte.min(text.len()); + while !text.is_char_boundary(byte) { + byte -= 1; + } + let out = self.begin_edit(cx, e.id, byte, Point::ZERO); + self.clicks = (None, 0); + out } /// The button released after a press at `start` (new type goes at `at`). While type is being diff --git a/crates/tools/src/text/missing.rs b/crates/tools/src/text/missing.rs new file mode 100644 index 0000000000..7d14d635b4 --- /dev/null +++ b/crates/tools/src/text/missing.rs @@ -0,0 +1,83 @@ +//! Type set in fonts that aren't available as named asks before it is edited: a click or a +//! double-click that would start editing it opens a question ([`MISSING_FONT_EDIT`]) instead, and +//! editing starts at the clicked place only after OK (the tool option `missingFontEdit`). The +//! fonts are those `text.missingFonts` reads, for the story of the type clicked only. + +use std::collections::BTreeSet; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, NodeId, NodeKind, TextRun}; +use vectorcraft_text::{FontDb, FontMatch}; + +/// The dialog kind of the question, with the fields `token`, `id`, `missing` and `style` (lists of +/// "family style" names) and `more` (how many more fonts the lists leave out). +pub const MISSING_FONT_EDIT: &str = "missingFontEdit"; + +/// The most fonts the question names. +const LISTED: usize = 8; + +/// The longest family or style name checked (bytes), as `text.missingFonts` reads them. +const MAX_NAME: usize = 256; + +/// An edit of type set in fonts that aren't available, waiting for the answer to its question. +#[derive(Clone, Debug, PartialEq)] +pub(super) struct PendingEdit { + /// The question's token, which its answer names. + pub token: u64, + /// The document (its uid) and its revision when the question was asked: an answer to a + /// document since changed starts no editing. + pub revision: (u64, u64), + /// The type clicked, and the caret's byte offset there. + pub id: NodeId, + pub byte: usize, + /// OK was chosen: the next [`crate::Tool::poll`] starts editing. + pub accepted: bool, +} + +/// The fonts (family, style) run `r` is drawn in: its own, or, set in a composite font, those of +/// the parts its characters fall in. An inline graphic and an empty run draw no glyphs. +fn run_fonts(db: &FontDb, r: &TextRun) -> Vec<(String, String)> { + if r.inline.is_some() || r.text.is_empty() { + return vec![]; + } + db.composite_fonts_for(&r.style.font_family, &r.text).unwrap_or_else(|| vec![(r.style.font_family.clone(), r.style.font_style.clone())]) +} + +/// The fonts that the story of type object `id` ([`Document::story_of`]: every frame threaded with +/// it) is drawn in and that aren't available as named, each once, in the order first used, with how +/// they resolve ([`FontMatch::Missing`] or [`FontMatch::Style`]); at most [`LISTED`], with how many +/// more there are. CSS generic families and names longer than 256 bytes are left out, as +/// `text.missingFonts` leaves them out. +pub(super) fn unavailable_fonts(doc: &Document, id: NodeId) -> (Vec<(String, String, FontMatch)>, usize) { + let db = FontDb::global(); + let mut seen = BTreeSet::new(); + let mut listed = Vec::new(); + let mut more = 0; + for frame in doc.story_of(id) { + let Some(NodeKind::Text(t)) = doc.node(frame).map(|n| &n.kind) else { continue }; + for (family, style) in t.runs.iter().flat_map(|r| run_fonts(db, r)) { + if family.trim().is_empty() || vectorcraft_text::is_generic_family(&family) || family.len() > MAX_NAME || style.len() > MAX_NAME { + continue; + } + if !seen.insert((family.clone(), style.clone())) { + continue; + } + let found = db.resolve(&family, &style).map_or(FontMatch::Missing, |(_, m)| m); + if found == FontMatch::Exact { + continue; + } + if listed.len() < LISTED { + listed.push((family, style, found)); + } else { + more += 1; + } + } + } + (listed, more) +} + +/// The question's fields for `fonts` ([`unavailable_fonts`]) and the edit `token` of type `id`. +pub(super) fn question(token: u64, id: NodeId, (fonts, more): &(Vec<(String, String, FontMatch)>, usize)) -> Value { + let names = |m: FontMatch| fonts.iter().filter(|f| f.2 == m).map(|(family, style, _)| format!("{family} {style}")).collect::>(); + json!({"token": token, "id": id.0, "missing": names(FontMatch::Missing), "style": names(FontMatch::Style), "more": more}) +} diff --git a/crates/tools/src/text/tests.rs b/crates/tools/src/text/tests.rs index 89a24cc3bf..7ee90ee1c8 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") { @@ -1400,6 +1401,26 @@ fn creates(acts: &[Action]) -> bool { acts.iter().any(|a| matches!(a, Action::Exec(cmd, _) if cmd == "text.create" || cmd == "text.createInPath")) } +/// A click in the empty part of an area type frame, below its one line, edits that type: the +/// selection tools pass such clicks through to the art behind (#7274), the Type tool does not. +#[test] +fn a_click_in_an_area_frame_below_its_text_edits_it() { + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + let mut t = TextObject::point(Point::new(100.0, 100.0), "Hi", CharStyle { size: 20.0, ..Default::default() }); + t.kind = TextKind::Area { frame: vectorcraft_geom::PathData::from_bezpath(&Rect::new(0.0, 0.0, 200.0, 200.0).to_path(0.1)) }; + t.cached_bounds = Some(Rect::new(0.0, 0.0, 30.0, 24.0)); + d.insert(Some(l), 0, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap(); + let (sel, p) = (Selection::default(), paint()); + let c = cx(&d, &sel, &p); + assert!(vectorcraft_doc::hit::hit_test(&d, Point::new(250.0, 250.0), c.selection_hit_options()).is_none(), "selection tools: passes through"); + let mut tool = TypeTool::new("type"); + let acts = click(&mut tool, &c, 250.0, 250.0); + assert!(!creates(&acts), "{acts:?}"); + assert_eq!(tool.editing, Some(id)); +} + /// While type is being edited, a click on blank canvas ends the editing and makes no new type; /// the Type tool stays, and the next click makes point type (#2871, #2854). The same holds when /// the editing began with a double-click from a selection tool. @@ -1542,6 +1563,7 @@ fn selected_type_shows_its_ports_in_each_state() { /// Preferences › Hyphenation › Exceptions change, the selected type is laid out again. #[test] fn the_out_port_follows_the_hyphenation_exceptions() { + let _inputs = crate::testutil::changing_layout_inputs(); struct Clear; impl Drop for Clear { fn drop(&mut self) { @@ -1690,6 +1712,7 @@ const OVERFLOWS: &str = "This text is far too long to fit in a frame of one hund /// overlays as a tool that lays every frame out afresh. #[test] fn type_overlays_keep_the_selected_frames_layouts() { + let _inputs = crate::testutil::steady_layout_inputs(); let (d, ids) = area_frames(&["One", "Two words", "Three words here", OVERFLOWS]); let (mut sel, p) = (Selection::default(), paint()); sel.set(ids.iter().copied()); @@ -1721,6 +1744,7 @@ fn type_overlays_keep_the_selected_frames_layouts() { /// out again on the next frame. #[test] fn type_overlays_keep_a_selected_storys_layouts() { + let _inputs = crate::testutil::steady_layout_inputs(); let (mut d, ids) = area_frames(&["Story one ", "story two ", "story three ", "story four"]); d.text_threads.push(ids.clone()); let (mut sel, p) = (Selection::default(), paint()); @@ -1749,6 +1773,7 @@ fn type_overlays_keep_a_selected_storys_layouts() { /// longer drawn is dropped, and choosing another tool drops them all. #[test] fn type_overlays_lay_out_again_only_the_frames_that_changed() { + let _inputs = crate::testutil::steady_layout_inputs(); let (mut d, ids) = area_frames(&["One", "Two", "Three", OVERFLOWS]); let (mut sel, p) = (Selection::default(), paint()); sel.set(ids.iter().copied()); @@ -1786,6 +1811,7 @@ fn type_overlays_lay_out_again_only_the_frames_that_changed() { /// each call, and draws what laying every frame out afresh draws. #[test] fn type_overlays_keep_at_most_frame_layouts_max() { + let _inputs = crate::testutil::steady_layout_inputs(); let texts = vec!["a "; FRAME_LAYOUTS_MAX + 3]; let (mut d, ids) = area_frames(&texts); d.text_threads.push(ids.clone()); @@ -1806,6 +1832,7 @@ fn type_overlays_keep_at_most_frame_layouts_max() { #[test] fn frame_layouts_follow_fonts_and_hyphenation_exceptions() { + let _inputs = crate::testutil::changing_layout_inputs(); // Other tests can load system fonts; this assertion needs its own process-wide database. #[cfg(not(target_arch = "wasm32"))] if std::env::var("VECTORCRAFT_FONT_CACHE_TEST_CHILD").as_deref() != Ok("1") { @@ -1848,6 +1875,7 @@ fn frame_layouts_follow_fonts_and_hyphenation_exceptions() { #[test] #[ignore = "timing, run by hand"] fn type_overlays_timing() { + let _inputs = crate::testutil::steady_layout_inputs(); use std::time::Instant; let words = "The quick brown fox jumps over the lazy dog while seven wizards box. ".repeat(6); let texts: Vec = (0..200).map(|i| format!("{i} {words}")).collect(); @@ -2163,3 +2191,173 @@ 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)); +} + +/// `tool.setOption` checks each option first: the answer to the question is a whole-number token +/// and a true or false `ok`, so a client can give it through that command. +#[test] +fn the_answer_to_the_missing_font_question_passes_the_option_check() { + let tool = TypeTool::new("type"); + assert_eq!(tool.check_option("missingFontEdit", &json!({"token": 7, "ok": true})), Ok(())); + assert_eq!(tool.check_option("missingFontEdit", &json!({"token": 7, "ok": false})), Ok(())); + for bad in [json!({"token": "7", "ok": true}), json!({"token": 7, "ok": 1}), json!({"ok": true}), json!({"token": -1, "ok": true}), json!(null)] { + assert_eq!( + tool.check_option("missingFontEdit", &bad), + Err("`missingFontEdit` must be {token, ok} with a whole number and true or false".to_string()), + "{bad}" + ); + } +} + +/// Cancel starts no edit, and the edit in progress on other type goes on; an answer that names +/// another question, or one given to a document changed since, starts nothing either. +#[test] +fn cancel_or_a_stale_answer_starts_no_edit_in_missing_fonts() { + let (mut d, first, mut tool) = editing("First"); + tool.caret = 2; + let other = add_styled_text(&mut d, 300.0, &[("Second", NO_SUCH_FAMILY, "Bold")]); + let (sel, p) = (Selection::default(), paint()); + let c = cx(&d, &sel, &p); + let at = caret_at(&c, other, 2); + let (token, _) = asked(&click(&mut tool, &c, at.x, at.y)); + assert_eq!((tool.editing, tool.caret), (Some(first), 2), "the edit in progress goes on while the question is open"); + tool.set_option("missingFontEdit", &json!({"token": token + 1, "ok": true})); + assert!(!tool.waiting(), "another question's answer"); + tool.set_option("missingFontEdit", &json!({"token": token, "ok": false})); + assert!(tool.poll(&c, false).is_empty()); + assert_eq!((tool.editing, tool.caret), (Some(first), 2)); + // OK after the document changed: nothing starts. + let (token, _) = asked(&click(&mut tool, &c, at.x, at.y)); + tool.set_option("missingFontEdit", &json!({"token": token, "ok": true})); + let changed = ToolContext { revision: (0, 1), ..cx(&d, &sel, &p) }; + assert!(tool.poll(&changed, false).is_empty()); + assert_eq!(tool.editing, Some(first)); + assert!(!tool.waiting()); +} + +/// Every new edit of such type asks again, after an earlier OK too, and a style the family lacks +/// asks as a missing family does; type in available fonts is edited at once. +#[test] +fn each_new_edit_of_type_in_unavailable_fonts_asks() { + let mut d = Document::new(500.0, 500.0); + let styled = add_styled_text(&mut d, 100.0, &[("Wide", "Source Sans 3", "Ultra Condensed Oblique 7258")]); + let plain = add_styled_text(&mut d, 300.0, &[("Plain", "Source Sans 3", "Regular")]); + let mut tool = TypeTool::new("type"); + let (sel, p) = (Selection::default(), paint()); + let c = cx(&d, &sel, &p); + let at = caret_at(&c, styled, 1); + let (token, q) = asked(&click(&mut tool, &c, at.x, at.y)); + assert_eq!((&q["missing"], &q["style"]), (&json!([]), &json!(["Source Sans 3 Ultra Condensed Oblique 7258"]))); + tool.set_option("missingFontEdit", &json!({"token": token, "ok": true})); + tool.poll(&c, false); + assert_eq!(tool.editing, Some(styled)); + // Other type in an available font is edited at once. + let to = caret_at(&c, plain, 2); + let acts = click(&mut tool, &c, to.x, to.y); + assert!(acts.contains(&Action::Exec("select.set".into(), json!({"ids": [plain.0]}))), "{acts:?}"); + assert_eq!(tool.editing, Some(plain)); + // Back to the first type: a new edit, so the question comes again. + asked(&click(&mut tool, &c, at.x, at.y)); + assert_eq!(tool.editing, Some(plain)); +} + +/// The whole story counts: type with one run in a missing font asks even when the click lands in a +/// run in an available font, and the question names each font once. +#[test] +fn a_story_with_one_run_in_a_missing_font_asks() { + let mut d = Document::new(500.0, 500.0); + let id = add_styled_text( + &mut d, + 100.0, + &[("Here ", "Source Sans 3", "Regular"), ("gone ", NO_SUCH_FAMILY, "Regular"), ("again", NO_SUCH_FAMILY, "Regular")], + ); + let mut tool = TypeTool::new("type"); + let (sel, p) = (Selection::default(), paint()); + let c = cx(&d, &sel, &p); + let at = caret_at(&c, id, 1); + let (_, q) = asked(&click(&mut tool, &c, at.x, at.y)); + assert_eq!(q["missing"], json!([format!("{NO_SUCH_FAMILY} Regular")])); + assert_eq!(tool.editing, None); +} + +/// Type set in a CSS generic family is edited without a question, and a press dropped while the +/// question is open leaves the edit in progress as it was. +#[test] +fn generic_families_and_a_dropped_press_ask_nothing_more() { + let mut d = Document::new(500.0, 500.0); + let generic = add_styled_text(&mut d, 100.0, &[("Generic", "sans-serif", "Regular")]); + let missing = add_styled_text(&mut d, 300.0, &[("Missing", NO_SUCH_FAMILY, "Regular")]); + let mut tool = TypeTool::new("type"); + let (sel, p) = (Selection::default(), paint()); + let c = cx(&d, &sel, &p); + let at = caret_at(&c, generic, 1); + let acts = click(&mut tool, &c, at.x, at.y); + assert!(acts.contains(&Action::Exec("select.set".into(), json!({"ids": [generic.0]}))), "{acts:?}"); + let to = caret_at(&c, missing, 1); + asked(&tool.pointer(&c, &PointerEvent::new(PointerKind::Down, to.x, to.y))); + assert!(tool.drop_press(&c).is_empty()); + assert_eq!(tool.editing, Some(generic)); +} diff --git a/crates/tools/src/text/tool.rs b/crates/tools/src/text/tool.rs index 2945777610..290014de98 100644 --- a/crates/tools/src/text/tool.rs +++ b/crates/tools/src/text/tool.rs @@ -73,8 +73,12 @@ impl Tool for TypeTool { } self.clicks = (None, 0); // A press on other type edits it from there, so a drag selects its text at once, - // as it does in the type being edited. + // as it does in the type being edited. While the question about its fonts is open, + // the press does nothing more, and the edit in progress goes on. if let Some(out) = self.edit_at(cx, ev.pos) { + if self.pending_edit.is_some() { + return out; + } self.selecting = true; self.before_press = Some(before); return out; @@ -472,9 +476,17 @@ impl Tool for TypeTool { } fn deactivate(&mut self, cx: &ToolContext) -> Vec { self.prev_tool = None; + self.pending_edit = None; self.frames.get_mut().unwrap_or_else(|e| e.into_inner()).clear(); self.finish(cx) } + /// OK on the question about type in missing fonts started an edit the next poll begins. + fn waiting(&self) -> bool { + self.pending_edit.as_ref().is_some_and(|e| e.accepted) + } + fn poll(&mut self, cx: &ToolContext, _wait: bool) -> Vec { + self.resume_edit(cx) + } /// Editing ends when a command takes the text out of the selection (Deselect, another object /// picked in the Layers panel) or removes it. After an Undo that takes back a list typed /// characters started, the caret goes on after the characters, and after its Redo the caret @@ -538,9 +550,15 @@ impl Tool for TypeTool { } } /// `select {start, end}` / `selectAll` / `copy` (with `runs` of the selection) / - /// `commitTyping` (the caller commits the engine interaction). + /// `commitTyping` (the caller commits the engine interaction) / `missingFontEdit {token, ok}` + /// (the answer to the question about type in missing fonts; never a saved setting). fn set_option(&mut self, key: &str, v: &Value) { match key { + "missingFontEdit" => { + if let (Some(token), Some(ok)) = (v.get("token").and_then(Value::as_u64), v.get("ok").and_then(Value::as_bool)) { + self.answer_edit(token, ok); + } + } // Transient selection transferred between Type and Eyedropper; never a saved setting. "textSelection" => { if let (Some(id), Some(a), Some(b)) = ( @@ -611,7 +629,8 @@ impl Tool for TypeTool { } } /// The calls [`Self::set_option`] takes: `commitTyping`, `endTyping`, `selectAll` and - /// `stopEditing` take any value, the others the shapes they read. + /// `stopEditing` take any value, the others the shapes they read (`missingFontEdit` a whole-number + /// `token` and a true or false `ok`). 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 { @@ -620,11 +639,13 @@ impl Tool for TypeTool { "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, + "missingFontEdit" => v.get("token").and_then(Value::as_u64).is_some() && v.get("ok").and_then(Value::as_bool).is_some(), _ => return Err(crate::option_check::unknown(key)), }; let shape = match key { "textSelection" => "{editing, anchor, caret} with whole numbers", "select" => "{start, end} with whole numbers", + "missingFontEdit" => "{token, ok} with a whole number and true or false", _ => "a list of text runs", }; if ok { Ok(()) } else { Err(format!("`{key}` must be {shape}")) } 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/trace_split.rs b/crates/tools/src/trace_split.rs new file mode 100644 index 0000000000..f5949be2a4 --- /dev/null +++ b/crates/tools/src/trace_split.rs @@ -0,0 +1,284 @@ +//! The divider of an Image Trace object in the Split view: the source image shows on its left +//! (in the image's own pixels) and the tracing result on its right. Drawing and hit testing share +//! the document-space geometry here; a drag previews `imageTrace.setView` and commits it as one +//! undo step. +use serde_json::json; +use vectorcraft_doc::{Document, NodeId, NodeKind, Selection, TraceView}; +use vectorcraft_geom::{Affine, Point}; + +use crate::{Action, Cursor, Mods, ToolContext}; + +/// How near (screen points) the pointer must come to the divider to take it. +pub const HIT_PX: f64 = 5.0; + +/// The divider's half length past each end of its grip, in screen points. +pub const GRIP_HALF: f32 = 10.0; + +/// The Split view's divider of one selected Image Trace object, in document space. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct TraceDivider { + /// The Image Trace object. + pub id: NodeId, + /// The fraction of the source image's width, from its left edge, that shows the image. + pub split: f64, + /// Where the divider meets the image's top and bottom edges. + pub ends: [Point; 2], + /// The source image's pixel-to-document transform. + xf: Affine, + width: f64, +} + +impl TraceDivider { + /// The divider of the one Image Trace object selected whole, when it shows the Split view. + pub fn of(doc: &Document, selection: &Selection, zoom: f64) -> Option { + let [id] = selection.objects.as_slice() else { return None }; + if !selection.anchors.is_empty() || !selection.segments.is_empty() || !doc.is_editable(*id) || !zoom.is_finite() || zoom <= 0.0 { + return None; + } + let n = doc.node(*id)?; + if n.extras().trace.is_none() || n.trace_view() != TraceView::Split { + return None; + } + let NodeKind::Group { children, clip: false } = &n.kind else { return None }; + let NodeKind::Image(im) = &children.first()?.kind else { return None }; + let (width, height) = (f64::from(im.width), f64::from(im.height)); + let det = im.xf.determinant(); + if width <= 0.0 || height <= 0.0 || !det.is_finite() || det.abs() < 1e-12 || !im.xf.as_coeffs().iter().all(|c| c.is_finite()) { + return None; + } + let split = n.trace_split(); + let at = width * split; + let ends = [im.xf * Point::new(at, 0.0), im.xf * Point::new(at, height)]; + ends.iter().all(|p| finite(*p)).then_some(Self { id: *id, split, ends, xf: im.xf, width }) + } + + /// The divider position for document point `p`: the fraction of the image's width left of + /// it, from 0 to 1, rounded to a ten-thousandth. + pub fn split_at(&self, p: Point) -> Option { + let local = self.xf.inverse() * p; + let f = (local.x / self.width).clamp(0.0, 1.0); + f.is_finite().then(|| (f * 10_000.0).round() / 10_000.0) + } + + /// How far the image's left-to-right direction is turned (counter-clockwise degrees on the + /// page), for the resize cursor. + fn angle(&self) -> f64 { + let across = self.xf * Point::new(1.0, 0.0) - self.xf * Point::ZERO; + (-across.y).atan2(across.x).to_degrees() + } + + /// The divider under document point `p`. Nothing with the bounding box hidden or in Outline + /// mode, where the canvas draws neither the divider nor the split. + fn hit(cx: &ToolContext, p: Point) -> Option { + if !cx.show_bbox || cx.outline || !finite(p) { + return None; + } + let d = Self::of(cx.doc, cx.selection, cx.zoom)?; + let [a, b] = d.ends; + let v = b - a; + let length = v.hypot(); + if !length.is_finite() || length <= 0.0 { + return None; + } + let unit = v / length; + let along = (p - a).dot(unit).clamp(0.0, length); + // A bounding-box handle or a shown center point under the pointer keeps its own drag. + ((a + unit * along).distance(p) <= cx.tol(HIT_PX) + && !crate::select::bbox_handle_at(cx, p) + && crate::select::hit_center(cx, p, cx.point_tol()).is_none()) + .then_some(d) + } +} + +fn finite(p: Point) -> bool { + p.x.is_finite() && p.y.is_finite() +} + +fn resize_cursor(d: &TraceDivider, cx: &ToolContext) -> Cursor { + crate::select::handle_cursor(crate::bbox::Handle::Right, d.angle() - cx.view_angle()) +} + +/// The resize cursor over the divider at `p`, turned with the image and the view. +pub fn cursor(cx: &ToolContext, p: Point) -> Option { + TraceDivider::hit(cx, p).map(|d| resize_cursor(&d, cx)) +} + +/// A drag of the divider: it previews `imageTrace.setView` while the pointer moves and commits +/// it as one undo step. +#[derive(Clone, Debug)] +pub struct SplitDrag { + divider: TraceDivider, + start: Point, + began: bool, +} + +impl SplitDrag { + pub fn hit(cx: &ToolContext, p: Point, mods: Mods) -> Option { + if mods.cmd || mods.ctrl || mods.alt { + return None; + } + let divider = TraceDivider::hit(cx, p)?; + Some(Self { divider, start: p, began: false }) + } + + pub fn adjusting(&self) -> bool { + self.began + } + + pub fn cursor(&self, cx: &ToolContext) -> Cursor { + resize_cursor(&self.divider, cx) + } + + pub fn drag(&mut self, cx: &ToolContext, p: Point) -> Vec { + if !finite(p) || (!self.began && p.distance(self.start) < cx.tol(3.0)) { + return vec![]; + } + let Some(split) = self.divider.split_at(p) else { return vec![] }; + let mut out = vec![]; + if !self.began { + self.began = true; + out.push(Action::Begin("Image Trace View".into())); + } + out.push(Action::Preview("imageTrace.setView".into(), json!({"id": self.divider.id.0, "view": TraceView::Split.id(), "split": split}))); + out + } + + pub fn finish(self) -> Vec { + if self.began { vec![Action::Commit] } else { vec![] } + } + + pub fn cancel(self) -> Vec { + if self.began { vec![Action::Cancel] } else { vec![] } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::{cx, paint}; + use std::sync::Arc; + use vectorcraft_doc::{ImageObject, Node}; + + /// A document with an Image Trace object over a 100 × 50 image placed by `xf`, in `view`. + fn traced(xf: Affine, view: &str, split: f64) -> (Document, NodeId) { + let mut doc = Document::new(400.0, 400.0); + let im = ImageObject { key: "k".into(), width: 100, height: 50, xf, link: None, placement: Default::default(), pixels: None }; + let mut source = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im))); + source.visible = false; + let mut g = Node::group(doc.alloc_id(), vec![Arc::new(source)]); + g.extras_mut().trace = Some(Box::new(json!({"view": view, "split": split}))); + let id = g.id; + let layer = doc.layers[0].id; + doc.insert(Some(layer), 0, g).unwrap(); + (doc, id) + } + + #[test] + fn the_divider_shows_only_for_one_selected_split_view_and_follows_the_image() { + let paint = paint(); + let mut selection = Selection::default(); + let (doc, id) = traced(Affine::translate((10.0, 20.0)), "split", 0.25); + assert!(TraceDivider::of(&doc, &selection, 1.0).is_none(), "nothing selected"); + selection.set([id]); + let d = TraceDivider::of(&doc, &selection, 1.0).unwrap(); + assert_eq!((d.split, d.ends), (0.25, [Point::new(35.0, 20.0), Point::new(35.0, 70.0)])); + for zoom in [0.0, -1.0, f64::NAN] { + assert!(TraceDivider::of(&doc, &selection, zoom).is_none()); + } + let (other, id) = traced(Affine::IDENTITY, "sourceImage", 0.25); + selection.set([id]); + assert!(TraceDivider::of(&other, &selection, 1.0).is_none(), "another view"); + // A turned and scaled image: the divider runs along the image's own height. + let xf = Affine::translate((200.0, 100.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2) * Affine::scale(2.0); + let (doc, id) = traced(xf, "split", 0.5); + selection.set([id]); + let d = TraceDivider::of(&doc, &selection, 1.0).unwrap(); + assert!(d.ends[0].distance(Point::new(200.0, 200.0)) < 1e-9 && d.ends[1].distance(Point::new(100.0, 200.0)) < 1e-9, "{:?}", d.ends); + assert_eq!(d.split_at(Point::new(150.0, 150.0)), Some(0.25)); + assert_eq!(d.split_at(Point::new(150.0, 900.0)), Some(1.0), "clamped"); + let c = cx(&doc, &selection, &paint); + assert_eq!(cursor(&c, Point::new(150.0, 200.0)), Some(Cursor::ResizeV)); + assert_eq!(cursor(&c, Point::new(150.0, 210.0)), None, "past the hit distance"); + let mut c = cx(&doc, &selection, &paint); + c.show_bbox = false; + assert_eq!(cursor(&c, Point::new(150.0, 200.0)), None, "bounding box hidden"); + assert!(SplitDrag::hit(&c, Point::new(150.0, 200.0), Mods::default()).is_none(), "bounding box hidden"); + let mut c = cx(&doc, &selection, &paint); + c.outline = true; + assert!(SplitDrag::hit(&c, Point::new(150.0, 200.0), Mods::default()).is_none(), "Outline mode"); + } + + #[test] + fn dragging_the_divider_previews_the_view_and_commits_once() { + let paint = paint(); + let mut selection = Selection::default(); + let (doc, id) = traced(Affine::translate((10.0, 20.0)), "split", 0.5); + selection.set([id]); + for zoom in [0.5, 1.0, 4.0] { + let mut c = cx(&doc, &selection, &paint); + c.zoom = zoom; + let on = Point::new(60.0 + 4.0 / zoom, 40.0); + assert_eq!(cursor(&c, on), Some(Cursor::ResizeH), "zoom {zoom}"); + assert!(SplitDrag::hit(&c, Point::new(60.0 + 6.0 / zoom, 40.0), Mods::default()).is_none(), "zoom {zoom}"); + assert!(SplitDrag::hit(&c, on, Mods { alt: true, ..Default::default() }).is_none()); + let mut drag = SplitDrag::hit(&c, on, Mods::default()).unwrap(); + assert!(drag.drag(&c, on + vectorcraft_geom::Vec2::new(1.0 / zoom, 0.0)).is_empty(), "under the drag threshold"); + assert!(drag.drag(&c, Point::new(f64::NAN, 0.0)).is_empty()); + let out = drag.drag(&c, Point::new(85.0, 300.0)); + assert!( + matches!(&out[..], [Action::Begin(_), Action::Preview(id, p)] + if id == "imageTrace.setView" && p["split"] == json!(0.75) && p["view"] == "split"), + "{out:?}" + ); + let out = drag.drag(&c, Point::new(-50.0, 30.0)); + assert!(matches!(&out[..], [Action::Preview(_, p)] if p["split"] == json!(0.0)), "{out:?}"); + assert!(drag.adjusting()); + assert!(matches!(drag.clone().finish()[..], [Action::Commit])); + assert!(matches!(drag.cancel()[..], [Action::Cancel])); + } + } + + /// With Show Center on, a press on the center point where the divider crosses it moves the + /// object; the rest of the divider still takes a press. + #[test] + fn the_center_point_keeps_its_drag_on_the_divider() { + use vectorcraft_doc::{Appearance, LiveShape}; + let paint = paint(); + let mut selection = Selection::default(); + let (mut doc, id) = traced(Affine::translate((10.0, 20.0)), "split", 0.5); + let xf = Affine::translate((10.0, 20.0)); + let shape = LiveShape::Rectangle { w: 100.0, h: 50.0, radii: [0.0; 4], kinds: Default::default(), radii_relative: false, xf }; + let path = Node::path(doc.alloc_id(), shape.to_path(), Appearance::default_art()); + doc.insert(Some(id), 1, path).unwrap(); + doc.node_mut(id).unwrap().edit_attrs(|a| a.show_center = Some(true)); + selection.set([id]); + let c = cx(&doc, &selection, &paint); + assert_eq!(crate::select::hit_center(&c, Point::new(60.0, 45.0), c.point_tol()).map(|(i, _)| i), Some(id)); + assert_eq!(cursor(&c, Point::new(60.0, 45.0)), None, "the center point"); + assert!(SplitDrag::hit(&c, Point::new(60.0, 45.0), Mods::default()).is_none(), "the center point"); + assert_eq!(cursor(&c, Point::new(60.0, 33.0)), Some(Cursor::ResizeH)); + } + + /// Switching away from the Selection tool during a divider drag cancels it, as Escape does: + /// the view goes back. After a press that has not moved there is nothing to put back. + #[test] + fn a_tool_switch_cancels_a_divider_drag() { + use crate::{PointerEvent, PointerKind, Tool}; + let paint = paint(); + let mut selection = Selection::default(); + let (doc, id) = traced(Affine::translate((10.0, 20.0)), "split", 0.5); + selection.set([id]); + let c = cx(&doc, &selection, &paint); + let mut t = crate::select::SelectionTool::default(); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 60.0, 40.0)).is_empty()); + let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 85.0, 40.0)); + assert!(matches!(a.first(), Some(Action::Begin(_))), "{a:?}"); + assert_eq!(t.deactivate(&c), vec![Action::Cancel]); + assert!(!t.busy() && !t.transforming()); + assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 85.0, 40.0)).is_empty()); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 60.0, 40.0)); + assert!(t.busy()); + assert!(t.deactivate(&c).is_empty()); + assert!(!t.busy()); + } +} diff --git a/crates/tools/src/xform.rs b/crates/tools/src/xform.rs index 74cf0b761d..880b6c76b3 100644 --- a/crates/tools/src/xform.rs +++ b/crates/tools/src/xform.rs @@ -18,7 +18,7 @@ use vectorcraft_geom::{BezPath, Point, Rect, Shape}; use crate::{Overlay, Tool}; -pub use artboard::ArtboardTool; +pub use artboard::{ArtboardTool, EDGE_BUTTON_TIP, EDGE_BUTTON_TIP_LOCKED}; pub use eyedropper::EyedropperTool; pub use free::{DistortMode, FreeTransformTool}; pub use gradient::GradientTool; diff --git a/crates/tools/src/xform/artboard.rs b/crates/tools/src/xform/artboard.rs index e8cac59c88..fae20e6d4e 100644 --- a/crates/tools/src/xform/artboard.rs +++ b/crates/tools/src/xform/artboard.rs @@ -28,7 +28,8 @@ //! no other artboard). Clicking one adds an empty artboard there (`artboard.new {beside, side}`); //! Alt-clicking duplicates the artboard with its art there (`artboard.duplicate {index, side}`), //! except on a locked artboard, where an Alt-click does nothing. Each is one undo step, and the new -//! artboard becomes the active one. +//! artboard becomes the active one. Resting the pointer on a button shows a tooltip that says what a +//! click does there and, on an unlocked artboard, what an Alt-click does. use serde_json::{Value, json}; use vectorcraft_doc::ArtboardSide; @@ -298,6 +299,10 @@ fn bleed_offset(cx: &ToolContext, rect: Rect, handle: Handle) -> Vec2 { const EDGE_BUTTON_OFFSET: f64 = 18.0; /// The add button's radius in screen pixels: a press this near its center takes it. const EDGE_BUTTON_RADIUS: f64 = 7.0; +/// The add button's tooltip ([`Overlay::HoverText`]), an English UI string the UI translates. +pub const EDGE_BUTTON_TIP: &str = "Click to add an artboard on this side; Alt-click to duplicate this artboard with its art"; +/// The add button's tooltip on a locked artboard, where an Alt-click does nothing. +pub const EDGE_BUTTON_TIP_LOCKED: &str = "Click to add an artboard on this side"; impl ArtboardTool { /// The add buttons on the active artboard's edges, each with its side and center: shown while @@ -657,9 +662,11 @@ impl Tool for ArtboardTool { if self.drag.is_some() { o.extend(self.guides.iter().cloned()); } - // The add buttons: a ring with a plus in it. + // The add buttons: a ring with a plus in it, and a tooltip over the area a press takes. let (radius, arm) = (cx.tol(EDGE_BUTTON_RADIUS), cx.tol(3.5)); + let tip = if ab.locked { EDGE_BUTTON_TIP_LOCKED } else { EDGE_BUTTON_TIP }; for (_, at) in self.edge_buttons(cx) { + o.push(Overlay::HoverText { center: at, radius, text: tip }); let ring: Vec = (0..24).map(|k| at + Vec2::from_angle(f64::from(k) * std::f64::consts::TAU / 24.0) * radius).collect(); let mut path = polygon(&ring, true); for arm in [Vec2::new(arm, 0.0), Vec2::new(0.0, arm)] { diff --git a/crates/tools/src/xform/artboard/tests.rs b/crates/tools/src/xform/artboard/tests.rs index 98410703f6..20c3128176 100644 --- a/crates/tools/src/xform/artboard/tests.rs +++ b/crates/tools/src/xform/artboard/tests.rs @@ -611,6 +611,44 @@ fn add_buttons_hide_with_several_artboards_selected_or_during_a_drag() { assert!(button_sides(&t, &c).is_empty(), "none while an artboard is dragged"); } +/// The tooltips the add buttons carry: each one's center, radius and text. +fn button_tips(t: &ArtboardTool, c: &ToolContext) -> Vec<(Point, f64, &'static str)> { + t.overlays(c) + .into_iter() + .filter_map(|o| if let Overlay::HoverText { center, radius, text } = o { Some((center, radius, text)) } else { None }) + .collect() +} + +#[test] +fn each_add_button_has_a_tooltip_over_the_area_a_press_takes() { + let mut d = two_boards(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let t = ArtboardTool::default(); + let radius = c.tol(EDGE_BUTTON_RADIUS); + let want: Vec<_> = t.edge_buttons(&c).into_iter().map(|(_, at)| (at, radius, EDGE_BUTTON_TIP)).collect(); + assert_eq!(want.len(), 3, "no button and no tooltip on the side without room"); + assert_eq!(button_tips(&t, &c), want); + // The tooltip's disc is the one a press takes. + for (at, r, _) in &want { + assert!(t.edge_button_at(&c, *at + Vec2::new(r * 0.99, 0.0)).is_some()); + assert!(t.edge_button_at(&c, *at + Vec2::new(r * 1.01, 0.0)).is_none()); + } + // None with several artboards selected or during a drag. + let several = ArtboardTool { active: 1, others: vec![0], ..Default::default() }; + assert!(button_tips(&several, &c).is_empty()); + let mut dragging = ArtboardTool::default(); + dragging.pointer(&c, &ev(PointerKind::Down, 700.0, 100.0)); + dragging.pointer(&c, &ev(PointerKind::Drag, 720.0, 100.0)); + assert!(button_tips(&dragging, &c).is_empty(), "none while an artboard is dragged"); + // A locked artboard's buttons tell only what a click does: an Alt-click does nothing there. + d.artboards[0].locked = true; + let c = cx(&d, &s, &p); + let tips = button_tips(&t, &c); + assert_eq!(tips.len(), 3); + assert!(tips.iter().all(|(_, _, text)| *text == EDGE_BUTTON_TIP_LOCKED), "{tips:?}"); +} + #[test] fn an_add_button_adds_an_empty_artboard_and_alt_duplicates_on_that_side() { let d = two_boards(); diff --git a/crates/tools/src/xform/transform.rs b/crates/tools/src/xform/transform.rs index 339984e9a1..d0ff487af8 100644 --- a/crates/tools/src/xform/transform.rs +++ b/crates/tools/src/xform/transform.rs @@ -11,9 +11,14 @@ //! onto another object's anchor scales exactly onto it. Scale stretches along the bounding box's //! own width and height, turned with rotated objects until Reset Bounding Box; Reflect's default //! axis is the box's vertical one, and Shift constrains a drawn axis to 45° steps from the box. +//! With the Reflect tool, a click also sets the first point of an axis, and a second click +//! reflects the selection across the line through both points (Alt on it reflects a copy); a +//! drag from there draws the axis from that first point. + +use std::collections::{BTreeMap, BTreeSet}; use serde_json::{Value, json}; -use vectorcraft_doc::{NodeId, OrientedBox}; +use vectorcraft_doc::{AnchorRef, NodeId, OrientedBox}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use super::target_overlays; @@ -82,6 +87,9 @@ struct Drag { pointer: Point, shift: bool, last: Affine, + /// The document revision at the press: a press whose document or selection changes before it + /// becomes a drag is dropped, so its reference point is never applied to other objects. + revision: (u64, u64), } impl Drag { @@ -92,10 +100,24 @@ impl Drag { } } +/// The first point of a Reflect axis set by a click, waiting for the second point, with the +/// selection and the document revision it was set for. +#[derive(Clone, Debug)] +struct Axis { + first: Point, + objects: Vec, + anchors: BTreeMap>, + revision: (u64, u64), +} + pub struct TransformTool { kind: TransformKind, /// Custom reference point and the selection it was set for. origin: Option<(Point, Vec)>, + /// Reflect: the axis whose second point the next click sets. + axis: Option, + /// The snapped pointer while hovering with an axis waiting, where its dashed line ends. + axis_to: Option, drag: Option, measure: Option<(Point, String)>, /// What the Info panel shows for the drag in progress. @@ -128,7 +150,23 @@ pub fn reflect_matrix(o: Point, theta: f64) -> Affine { impl TransformTool { pub fn new(kind: TransformKind) -> Self { - Self { kind, origin: None, drag: None, measure: None, readout: None, hover: vec![], snap: None } + Self { kind, origin: None, axis: None, axis_to: None, drag: None, measure: None, readout: None, hover: vec![], snap: None } + } + + /// The first point of the Reflect axis waiting for its second point, when it was set for the + /// current selection (objects and anchors) and nothing in the document or the selection has + /// changed since, so a selection changed and then changed back does not bring it back. + fn axis_first(&self, cx: &ToolContext) -> Option { + self.axis + .as_ref() + .filter(|a| !a.objects.is_empty() && a.revision == cx.revision && a.objects == cx.selection.objects && a.anchors == cx.selection.anchors) + .map(|a| a.first) + } + + /// Drops the Reflect axis waiting for its second point. + fn drop_axis(&mut self) { + self.axis = None; + self.axis_to = None; } /// The effective reference point: the custom one if it belongs to the current selection, @@ -297,8 +335,10 @@ impl Tool for TransformTool { self.hover.clear(); let (pick, _) = snap_pick(cx, p); // Alt: decided on release. A click sets the point and opens the dialog; a drag - // transforms a copy about the reference point as it was. - let origin = self.reference_point(cx).unwrap_or(bounds.center()); + // transforms a copy about the reference point as it was. With a Reflect axis waiting + // for its second point, a drag draws the axis from its first point. + self.axis_to = None; + let origin = self.axis_first(cx).or_else(|| self.reference_point(cx)).unwrap_or(bounds.center()); let anchors = vectorcraft_effects::preview::anchor_bounds_with(cx.selection, cx.doc, cx.bounds_measure()).is_some(); let angle = selection_box(cx).map_or(0.0, |b| b.angle); self.drag = Some(Drag { @@ -313,6 +353,7 @@ impl Tool for TransformTool { pointer: p, shift: false, last: Affine::IDENTITY, + revision: cx.revision, }); vec![] } @@ -323,6 +364,12 @@ impl Tool for TransformTool { if p.distance(d.start) < cx.tol(3.0) { return out; } + // The document or the selection changed since the press: its reference point + // (or Reflect axis) belongs to the selection as it was, so the press is dropped. + if d.revision != cx.revision { + self.end_drag(); + return out; + } d.began = true; // The selection moves, so only the other objects are targets. The Scale tool's // drag scales; the others move the art about the reference point. @@ -352,15 +399,49 @@ impl Tool for TransformTool { } else { d.last }; + // A drag draws a Reflect axis to its end, so it uses up an axis waiting for + // its second point. + self.drop_axis(); vec![preview(m, ev.mods.alt, ev.backquote), Action::Commit] + } else if d.revision != cx.revision { + // The document or the selection changed since the press, as for a drag: the + // release sets no reference point or Reflect axis. + vec![] + } else if let (TransformKind::Reflect, Some(first)) = (self.kind, self.axis_first(cx)) { + // The second point of a Reflect axis: the selection (with Alt at the release, as + // for a drag, a copy) reflects across the line through both points, as one undo + // step. A click on the first point does not define a line, so the axis keeps + // waiting. + if d.pick.distance(first) < cx.tol(3.0) { + return vec![]; + } + self.drop_axis(); + let copy = ev.mods.alt; + let (m, _, _) = self.solve(d.angle_for(copy, ev.backquote), first, first, d.pick, false, d.bounds); + vec![Action::Begin(self.kind.label().into()), preview(m, copy, ev.backquote), Action::Commit] } else { - // A click sets the reference point; with Alt, it opens the dialog too. + // A click sets the reference point; with Alt, it opens the dialog too. With the + // Reflect tool, a plain click also sets the first point of an axis. self.origin = Some((d.pick, cx.selection.objects.clone())); - if d.alt { vec![self.dialog(d.pick)] } else { vec![] } + self.drop_axis(); + if d.alt { + vec![self.dialog(d.pick)] + } else { + if self.kind == TransformKind::Reflect { + self.axis = Some(Axis { + first: d.pick, + objects: cx.selection.objects.clone(), + anchors: cx.selection.anchors.clone(), + revision: cx.revision, + }); + } + vec![] + } } } PointerKind::DoubleClick => { self.end_drag(); + self.drop_axis(); match self.reference_point(cx) { Some(o) => vec![self.dialog(o)], None => vec![], @@ -369,7 +450,9 @@ impl Tool for TransformTool { PointerKind::TripleClick => vec![], PointerKind::Move => { if self.drag.is_none() { - self.hover = if cx.selection.is_empty() { vec![] } else { snap_pick(cx, p).1 }; + let (pick, hover) = if cx.selection.is_empty() { (p, vec![]) } else { snap_pick(cx, p) }; + self.hover = hover; + self.axis_to = self.axis_first(cx).map(|_| pick); } vec![] } @@ -378,15 +461,40 @@ impl Tool for TransformTool { fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { match key { + // Escape cancels a drag, and drops the Reflect axis the drag was drawing from too. ToolKey::Escape if self.busy() => { self.end_drag(); + self.drop_axis(); vec![Action::Cancel] } - ToolKey::Enter => self.reference_point(cx).map(|o| vec![self.dialog(o)]).unwrap_or_default(), + // Escape drops a Reflect axis waiting for its second point, and a press not yet + // released with it, so the release sets no point; the reference point stays. + ToolKey::Escape if self.axis.is_some() => { + self.end_drag(); + self.drop_axis(); + vec![] + } + // Enter opens the dialog. A press not yet a drag ends with it, so its release sets no + // reference point or Reflect axis behind the dialog. + ToolKey::Enter => { + if !self.busy() { + self.end_drag(); + } + self.drop_axis(); + self.reference_point(cx).map(|o| vec![self.dialog(o)]).unwrap_or_default() + } _ => vec![], } } + /// A dropped press ends whether or not it became a drag, so the release the engine sends after + /// it sets no reference point or Reflect axis; a Reflect axis waiting for its second point is + /// dropped too, as with Escape. + fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + self.drop_axis(); + if self.end_drag().is_some_and(|d| d.began) { vec![Action::Cancel] } else { vec![] } + } + fn overlays(&self, cx: &ToolContext) -> Vec { let mut o = vec![]; let reference = match self.drag { @@ -403,6 +511,13 @@ impl Tool for TransformTool { { o.push(Overlay::Line { a: d.origin, b: *p, color: super::CYAN, dashed: true }); } + // A Reflect axis waiting for its second point: a dashed line from its first point to the + // pointer. + if self.drag.is_none() + && let (Some(a), Some(b)) = (self.axis_first(cx), self.axis_to) + { + o.push(Overlay::Line { a, b, color: super::CYAN, dashed: true }); + } if let (Some((p, t)), true) = (&self.measure, cx.transform_tools_guides) { o.push(Overlay::Measure { p: *p + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: t.clone() }); } @@ -429,9 +544,20 @@ impl Tool for TransformTool { fn set_option(&mut self, key: &str, value: &Value) { if key == "origin" { self.origin = value.as_array().and_then(|a| Some((Point::new(a.first()?.as_f64()?, a.get(1)?.as_f64()?), vec![]))); + self.drop_axis(); } } + fn ends_on_escape(&self, cx: &ToolContext) -> bool { + self.axis_first(cx).is_some() + } + + /// An edit, Undo or Redo made outside the tool, or another document, drops a Reflect axis + /// waiting for its second point. + fn history_moved(&mut self) { + self.drop_axis(); + } + /// `origin` is `[x, y]`, or null to clear it. fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { if key != "origin" { @@ -442,6 +568,7 @@ impl Tool for TransformTool { } fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + self.drop_axis(); if self.end_drag().is_some_and(|d| d.began) { vec![Action::Cancel] } else { vec![] } } } @@ -674,6 +801,353 @@ mod tests { assert!((matrix(&a[1]) * Point::new(200.0, 200.0)).distance(Point::new(302.0, 262.0)) < 1e-9); } + /// Sends a click (a press and a release, with `mods`) at `(x, y)` and returns the release's actions. + fn click(t: &mut TransformTool, cx: &ToolContext, x: f64, y: f64, mods: Mods) -> Vec { + assert!(t.pointer(cx, &ev(PointerKind::Down, x, y).with_mods(mods)).is_empty()); + t.pointer(cx, &ev(PointerKind::Up, x, y).with_mods(mods)) + } + + /// Returns the matrix of a two-click reflection: a Begin, one `object.transform` preview with + /// `copy`, and a Commit. + fn reflected(a: &[Action], copy: bool) -> Affine { + assert!( + matches!(a, [Action::Begin(l), Action::Preview(c, v), Action::Commit] if l == "Reflect" && c == "object.transform" && v["copy"] == copy), + "{a:?}" + ); + matrix(&a[1]) + } + + /// The Reflect tool: a click sets the first point of an axis, and a second click reflects the + /// selection across the line through both points, as one interaction. The next click starts a + /// new axis. + #[test] + fn a_second_reflect_click_reflects_across_the_line_through_both_points() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let mut c = cx(&d, &s, &p); + (c.smart_guides, c.snap_to_point) = (false, false); + let none = Mods::default(); + let mut t = TransformTool::new(TransformKind::Reflect); + assert!(click(&mut t, &c, 100.0, 100.0, none).is_empty()); + assert_eq!(t.reference_point(&c), Some(Point::new(100.0, 100.0))); + assert!(t.ends_on_escape(&c)); + // Hovering draws the axis from the first point to the pointer. + t.pointer(&c, &ev(PointerKind::Move, 200.0, 260.0)); + let line = Overlay::Line { a: Point::new(100.0, 100.0), b: Point::new(200.0, 260.0), color: super::super::CYAN, dashed: true }; + assert!(t.overlays(&c).contains(&line), "{:?}", t.overlays(&c)); + let m = reflected(&click(&mut t, &c, 200.0, 200.0, none), false); + for fixed in [Point::new(100.0, 100.0), Point::new(200.0, 200.0), Point::new(300.0, 300.0)] { + assert!((m * fixed).distance(fixed) < 1e-9, "{m:?}"); + } + assert!((m * Point::new(200.0, 100.0)).distance(Point::new(100.0, 200.0)) < 1e-9, "{m:?}"); + // The axis is used up; the first point stays the reference point. + assert!(!t.ends_on_escape(&c)); + assert!(!t.overlays(&c).contains(&line)); + assert_eq!(t.reference_point(&c), Some(Point::new(100.0, 100.0))); + // The next click starts a new axis, and the one after it reflects across a vertical line. + assert!(click(&mut t, &c, 120.0, 50.0, none).is_empty()); + let m = reflected(&click(&mut t, &c, 120.0, 250.0, none), false); + assert!((m * Point::new(150.0, 130.0)).distance(Point::new(90.0, 130.0)) < 1e-9, "{m:?}"); + // Shift on a plain second click does not constrain the line. + assert!(click(&mut t, &c, 100.0, 100.0, none).is_empty()); + let shift = Mods { shift: true, ..Default::default() }; + let m = reflected(&click(&mut t, &c, 210.0, 190.0, shift), false); + assert!((m * Point::new(210.0, 190.0)).distance(Point::new(210.0, 190.0)) < 1e-9, "{m:?}"); + } + + /// Alt on the second click reflects a copy and opens no dialog; Alt on a first click still opens + /// the dialog and starts no axis. + #[test] + fn alt_on_the_second_reflect_click_reflects_a_copy() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let mut c = cx(&d, &s, &p); + (c.smart_guides, c.snap_to_point) = (false, false); + let mut t = TransformTool::new(TransformKind::Reflect); + assert!(click(&mut t, &c, 250.0, 100.0, Mods::default()).is_empty()); + let m = reflected(&click(&mut t, &c, 250.0, 200.0, alt()), true); + assert!((m * Point::new(150.0, 150.0)).distance(Point::new(350.0, 150.0)) < 1e-9, "{m:?}"); + // As for a drag, Alt at the release decides: held only at the press, the original reflects; + // pressed during the click, a copy does. + for (press, release) in [(alt(), Mods::default()), (Mods::default(), alt())] { + assert!(click(&mut t, &c, 250.0, 100.0, Mods::default()).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Down, 250.0, 200.0).with_mods(press)).is_empty()); + reflected(&t.pointer(&c, &ev(PointerKind::Up, 250.0, 200.0).with_mods(release)), release.alt); + } + // Alt on a first click: the dialog, and the click after it is a first click again. + assert_eq!( + click(&mut t, &c, 120.0, 130.0, alt()), + vec![Action::Dialog("reflect".into(), json!({"axis": "vertical", "origin": [120.0, 130.0]}))] + ); + assert!(!t.ends_on_escape(&c)); + assert!(click(&mut t, &c, 130.0, 160.0, Mods::default()).is_empty()); + assert!(t.ends_on_escape(&c)); + } + + /// A second click on the first point does not define a line: nothing happens and the axis keeps + /// waiting. Escape, Enter, a double-click, a changed selection, an edit made outside the tool, + /// a new reference point and switching tools drop the axis, so the next click starts a new one. + #[test] + fn a_reflect_axis_waits_through_a_click_on_its_first_point_and_drops_on_escape_or_a_new_selection() { + let (mut d, id) = doc_with_rect(); + let l = d.layers[0].id; + let other = d.alloc_id(); + d.insert( + Some(l), + 1, + vectorcraft_doc::Node::path( + other, + vectorcraft_geom::shapes::rectangle(Rect::new(300.0, 300.0, 340.0, 340.0)), + vectorcraft_doc::Appearance::default_art(), + ), + ) + .unwrap(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let mut c = cx(&d, &s, &p); + (c.smart_guides, c.snap_to_point) = (false, false); + let none = Mods::default(); + let mut t = TransformTool::new(TransformKind::Reflect); + click(&mut t, &c, 100.0, 100.0, none); + assert!(click(&mut t, &c, 100.0, 100.0, none).is_empty()); + assert!(click(&mut t, &c, 101.0, 102.0, none).is_empty()); + assert!(t.ends_on_escape(&c)); + reflected(&click(&mut t, &c, 100.0, 200.0, none), false); + + // Each way of dropping the axis, then a click that only starts a new one. + type DropAxis = fn(&mut TransformTool, &ToolContext); + let drops: [(&str, DropAxis); 6] = [ + ("escape", |t, c| assert!(t.key(c, ToolKey::Escape, Mods::default()).is_empty())), + ("enter", |t, c| assert!(matches!(t.key(c, ToolKey::Enter, Mods::default()).as_slice(), [Action::Dialog(..)]))), + ("double-click", |t, c| assert!(matches!(t.pointer(c, &ev(PointerKind::DoubleClick, 100.0, 100.0)).as_slice(), [Action::Dialog(..)]))), + ("history", |t, _| t.history_moved()), + ("origin", |t, _| t.set_option("origin", &json!([10.0, 10.0]))), + ("deactivate", |t, c| assert!(t.deactivate(c).is_empty())), + ]; + for (name, drop) in drops { + click(&mut t, &c, 100.0, 100.0, none); + assert!(t.ends_on_escape(&c), "{name}"); + drop(&mut t, &c); + assert!(!t.ends_on_escape(&c), "{name}"); + assert!(click(&mut t, &c, 100.0, 200.0, none).is_empty(), "{name}"); + assert!(t.ends_on_escape(&c), "{name}"); + t.key(&c, ToolKey::Escape, Mods::default()); + } + + // A double-click elsewhere arrives as two clicks and then the double-click: its first click + // sets the second point and reflects, its second click starts a new axis, and the + // double-click drops that axis and opens the dialog there. + click(&mut t, &c, 100.0, 100.0, none); + reflected(&click(&mut t, &c, 100.0, 200.0, none), false); + assert!(click(&mut t, &c, 100.0, 200.0, none).is_empty()); + let a = t.pointer(&c, &ev(PointerKind::DoubleClick, 100.0, 200.0)); + assert_eq!(a, vec![Action::Dialog("reflect".into(), json!({"axis": "vertical", "origin": [100.0, 200.0]}))]); + assert!(!t.ends_on_escape(&c)); + + // The selection changed and changed back (or the document edited) moves the revision: the + // axis set before it does not come back. + click(&mut t, &c, 100.0, 100.0, none); + let mut moved = cx(&d, &s, &p); + (moved.smart_guides, moved.snap_to_point) = (false, false); + moved.revision = (c.revision.0, c.revision.1 + 1); + assert!(!t.ends_on_escape(&moved)); + assert!(click(&mut t, &moved, 100.0, 200.0, none).is_empty()); + reflected(&click(&mut t, &moved, 200.0, 200.0, none), false); + + // Another object selected, then nothing selected: the axis set for the first selection + // does not reflect them. + click(&mut t, &c, 100.0, 100.0, none); + let mut s2 = Selection::default(); + s2.add(other); + let mut c2 = cx(&d, &s2, &p); + (c2.smart_guides, c2.snap_to_point) = (false, false); + assert!(!t.ends_on_escape(&c2)); + assert!(click(&mut t, &c2, 100.0, 200.0, none).is_empty()); + let empty = Selection::default(); + let c3 = cx(&d, &empty, &p); + assert!(t.pointer(&c3, &ev(PointerKind::Down, 100.0, 300.0)).is_empty()); + assert!(t.pointer(&c3, &ev(PointerKind::Up, 100.0, 300.0)).is_empty()); + // Anchors selected with Direct Selection make a different selection too. + let mut s4 = s.clone(); + s4.anchors.insert(id, [(0, 0), (0, 1)].into()); + let mut c4 = cx(&d, &s4, &p); + (c4.smart_guides, c4.snap_to_point) = (false, false); + click(&mut t, &c, 100.0, 100.0, none); + assert!(!t.ends_on_escape(&c4)); + assert!(click(&mut t, &c4, 100.0, 200.0, none).is_empty()); + // With those anchors selected, the second click reflects them, across the line y = 200. + let m = reflected(&click(&mut t, &c4, 200.0, 200.0, none), false); + assert!((m * Point::new(150.0, 150.0)).distance(Point::new(150.0, 250.0)) < 1e-9, "{m:?}"); + + // The other transform tools only move the reference point on a second click. + for kind in [TransformKind::Rotate, TransformKind::Scale, TransformKind::Shear] { + let mut t = TransformTool::new(kind); + assert!(click(&mut t, &c, 100.0, 100.0, none).is_empty(), "{kind:?}"); + assert!(click(&mut t, &c, 100.0, 200.0, none).is_empty(), "{kind:?}"); + assert!(!t.ends_on_escape(&c), "{kind:?}"); + assert_eq!(t.reference_point(&c), Some(Point::new(100.0, 200.0)), "{kind:?}"); + } + } + + /// Escape pressed between the press and the release of the second click drops the axis and the + /// press with it: the release starts no new axis and moves no reference point, so the click + /// after it starts an axis and reflects nothing. Escape during a drag from the first point + /// cancels the drag and drops the axis too. + #[test] + fn escape_during_the_second_reflect_click_cancels_that_click() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let mut c = cx(&d, &s, &p); + (c.smart_guides, c.snap_to_point) = (false, false); + let none = Mods::default(); + let mut t = TransformTool::new(TransformKind::Reflect); + assert!(click(&mut t, &c, 100.0, 100.0, none).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Down, 200.0, 200.0)).is_empty()); + assert!(t.key(&c, ToolKey::Escape, none).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Up, 200.0, 200.0)).is_empty()); + assert!(!t.ends_on_escape(&c)); + assert_eq!(t.reference_point(&c), Some(Point::new(100.0, 100.0))); + assert!(click(&mut t, &c, 150.0, 300.0, none).is_empty()); + assert!(t.ends_on_escape(&c)); + // A drag from the first point, then Escape. + assert!(t.pointer(&c, &ev(PointerKind::Down, 300.0, 300.0)).is_empty()); + assert_eq!(t.pointer(&c, &ev(PointerKind::Drag, 100.0, 250.0))[0], Action::Begin("Reflect".into())); + assert_eq!(t.key(&c, ToolKey::Escape, none), vec![Action::Cancel]); + assert!(!t.ends_on_escape(&c)); + assert!(t.pointer(&c, &ev(PointerKind::Up, 100.0, 250.0)).is_empty()); + assert!(click(&mut t, &c, 200.0, 200.0, none).is_empty()); + } + + /// Enter between the press and the release of the second click opens the dialog at the first + /// point and ends the press: the release sets no point and starts no axis. A press the engine + /// drops ends the same way, with or without an axis waiting, and a dropped drag is canceled. A + /// press whose document or selection changes before it becomes a drag is dropped. + #[test] + fn enter_or_a_dropped_press_during_a_reflect_click_ends_that_press() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let mut c = cx(&d, &s, &p); + (c.smart_guides, c.snap_to_point) = (false, false); + let none = Mods::default(); + let first = Point::new(100.0, 100.0); + let mut t = TransformTool::new(TransformKind::Reflect); + assert!(click(&mut t, &c, 100.0, 100.0, none).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Down, 200.0, 200.0)).is_empty()); + assert_eq!(t.key(&c, ToolKey::Enter, none), vec![Action::Dialog("reflect".into(), json!({"axis": "vertical", "origin": [100.0, 100.0]}))]); + assert!(t.pointer(&c, &ev(PointerKind::Up, 200.0, 200.0)).is_empty()); + assert!(!t.ends_on_escape(&c)); + assert_eq!(t.reference_point(&c), Some(first)); + + // A dropped first press: its release sets no point and starts no axis. + assert!(t.pointer(&c, &ev(PointerKind::Down, 200.0, 200.0)).is_empty()); + assert!(t.drop_press(&c).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Up, 200.0, 200.0)).is_empty()); + assert!(!t.ends_on_escape(&c)); + assert_eq!(t.reference_point(&c), Some(first)); + // A dropped second press drops the axis too, so the next click is a first click. + assert!(click(&mut t, &c, 100.0, 100.0, none).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Down, 200.0, 200.0)).is_empty()); + assert!(t.drop_press(&c).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Up, 200.0, 200.0)).is_empty()); + assert!(!t.ends_on_escape(&c)); + assert!(click(&mut t, &c, 150.0, 300.0, none).is_empty()); + // A dropped drag is canceled, and its release commits nothing. + assert!(t.pointer(&c, &ev(PointerKind::Down, 300.0, 300.0)).is_empty()); + assert_eq!(t.pointer(&c, &ev(PointerKind::Drag, 100.0, 250.0))[0], Action::Begin("Reflect".into())); + assert_eq!(t.drop_press(&c), vec![Action::Cancel]); + assert!(t.pointer(&c, &ev(PointerKind::Up, 100.0, 250.0)).is_empty()); + assert!(!t.ends_on_escape(&c)); + + // The selection changes between the press and the first drag event: the press is dropped, + // and neither the drag nor its release transforms anything. + assert!(click(&mut t, &c, 100.0, 100.0, none).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Down, 200.0, 200.0)).is_empty()); + let mut moved = cx(&d, &s, &p); + (moved.smart_guides, moved.snap_to_point) = (false, false); + moved.revision = (c.revision.0, c.revision.1 + 1); + assert!(t.pointer(&moved, &ev(PointerKind::Drag, 100.0, 250.0)).is_empty()); + assert!(!t.busy()); + assert!(t.pointer(&moved, &ev(PointerKind::Up, 100.0, 250.0)).is_empty()); + } + + /// A press whose document or selection changes before a release that is not a drag sets no + /// reference point and starts no Reflect axis, so the next click is a first click. + #[test] + fn a_reflect_press_released_after_the_document_changed_sets_nothing() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let mut c = cx(&d, &s, &p); + (c.smart_guides, c.snap_to_point) = (false, false); + let none = Mods::default(); + let mut moved = cx(&d, &s, &p); + (moved.smart_guides, moved.snap_to_point) = (false, false); + moved.revision = (c.revision.0, c.revision.1 + 1); + let mut t = TransformTool::new(TransformKind::Reflect); + assert!(t.pointer(&c, &ev(PointerKind::Down, 200.0, 200.0)).is_empty()); + assert!(t.pointer(&moved, &ev(PointerKind::Up, 200.0, 200.0)).is_empty()); + assert!(!t.ends_on_escape(&moved)); + assert_ne!(t.reference_point(&moved), Some(Point::new(200.0, 200.0))); + assert!(click(&mut t, &moved, 150.0, 300.0, none).is_empty()); + // The other transform tools set no reference point either. + let mut t = TransformTool::new(TransformKind::Rotate); + assert!(t.pointer(&c, &ev(PointerKind::Down, 200.0, 200.0)).is_empty()); + assert!(t.pointer(&moved, &ev(PointerKind::Up, 200.0, 200.0)).is_empty()); + assert_ne!(t.reference_point(&moved), Some(Point::new(200.0, 200.0))); + } + + /// After a click sets the first point, a drag draws the axis from it (Shift in 45° steps from a + /// turned box), and its release uses the axis up. With the selection turned, two clicks still + /// reflect across the line through the clicked points on the page. + #[test] + fn a_drag_after_a_reflect_click_draws_the_axis_from_the_first_point() { + let (mut d, id) = doc_with_rect(); + let c0 = Point::new(150.0, 150.0); + d.node_mut(id).unwrap().transform(about(c0, Affine::rotate(-30f64.to_radians())), false); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let mut c = cx(&d, &s, &p); + (c.smart_guides, c.snap_to_point) = (false, false); + let none = Mods::default(); + let mut t = TransformTool::new(TransformKind::Reflect); + click(&mut t, &c, 100.0, 100.0, none); + t.pointer(&c, &ev(PointerKind::Down, 300.0, 300.0)); + let a = t.pointer(&c, &ev(PointerKind::Drag, 100.0, 250.0)); + assert_eq!(a[0], Action::Begin("Reflect".into())); + let m = matrix(&a[1]); + assert!((m * Point::new(100.0, 180.0)).distance(Point::new(100.0, 180.0)) < 1e-9, "{m:?}"); + assert!((m * Point::new(150.0, 150.0)).distance(Point::new(50.0, 150.0)) < 1e-9, "{m:?}"); + // Shift: a pointer a few degrees off the box's vertical axis steps onto it. + let frame = OrientedBox { angle: 30.0, rect: Rect::ZERO }; + let along = |x: f64, y: f64| Point::new(100.0, 100.0) + (frame.to_doc() * Point::new(x, y)).to_vec2(); + let to = along(3.0, 50.0); + let a = t.pointer(&c, &ev(PointerKind::Drag, to.x, to.y).with_mods(Mods { shift: true, ..Default::default() })); + assert!((matrix(&a[0]) * along(0.0, 50.0)).distance(along(0.0, 50.0)) < 1e-9, "{a:?}"); + let up = t.pointer(&c, &ev(PointerKind::Up, to.x, to.y)); + assert_eq!(up.last(), Some(&Action::Commit)); + assert!(!t.ends_on_escape(&c)); + assert!(click(&mut t, &c, 100.0, 300.0, none).is_empty()); + // Two clicks with the box turned: the line through the clicked points on the page. + let m = reflected(&click(&mut t, &c, 300.0, 300.0, none), false); + assert!((m * Point::new(200.0, 250.0)).distance(Point::new(200.0, 350.0)) < 1e-9, "{m:?}"); + // A drag with no axis waiting still draws it from the reference point. + let mut t = TransformTool::new(TransformKind::Reflect); + t.pointer(&c, &ev(PointerKind::Down, 150.0, 50.0)); + let a = t.pointer(&c, &ev(PointerKind::Drag, 150.0, 20.0)); + assert!((matrix(&a[1]) * Point::new(100.0, 120.0)).distance(Point::new(200.0, 120.0)) < 1e-9); + } + #[test] fn reflect_vertical_axis_mirrors_x() { let t = TransformTool::new(TransformKind::Reflect); diff --git a/crates/ui-egui/src/addons/packaging/preview.rs b/crates/ui-egui/src/addons/packaging/preview.rs index 97a8ebd988..cb6e9daca2 100644 --- a/crates/ui-egui/src/addons/packaging/preview.rs +++ b/crates/ui-egui/src/addons/packaging/preview.rs @@ -275,7 +275,7 @@ impl Cache { let opts = vectorcraft_render::RenderOptions { skip_templates: true, image_mips: true, - hidden: vectorcraft_engine::cmd::print_hidden(doc, key.fold_lines), + hidden: vectorcraft_engine::cmd::print_hidden(doc, key.fold_lines).into_iter().collect(), ..Default::default() }; if let Some(w) = &self.worker { diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 8a1666b260..3e7b864c05 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -1,6 +1,6 @@ //! 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, Smooth Bridge ([`bridge`]), 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, Tangent Circle… ([`tangent_circle`]), Add Bounding Rectangle… and Add Bounding 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 @@ -17,6 +17,7 @@ pub mod tangent_circle; use egui::Ui; use serde_json::{Map, Value, json}; use vectorcraft_geom::Point; +use vectorcraft_tools::addons::tangent_circle as tangent_circle_tool; use vectorcraft_tools::addons::{anchor_eraser, extend_path, measure_inspect, parametric_shape, slide_anchor, trim}; use crate::VectorcraftApp; @@ -36,6 +37,10 @@ pub const KIND: &str = "pathToolOptions"; pub const COMMON_TANGENTS: &str = "addon.pathtools.commonTangents"; /// The kinds of tangent Common Tangents' `tangents` picks, and their labels. pub const TANGENT_KINDS: &[(&str, &str)] = &[("All", "all"), ("External", "external"), ("Internal", "internal")]; +/// Add Bounding Rectangle's and Add Bounding Circle's commands, whose menu items open the command +/// dialog (Offset, One per Object) with a Preview. +pub const BOUNDING_RECTANGLE: &str = "addon.pathtools.boundingRectangle"; +pub const BOUNDING_CIRCLE: &str = "addon.pathtools.boundingCircle"; /// The close modes, as `addon.pathtools.close` names them, and their labels. const CLOSE_MODES: [(&str, &str); 3] = [("handles", "Keep Handles"), ("straight", "Straight"), ("smooth", "Smooth")]; const LABEL_W: f32 = 64.0; @@ -66,6 +71,7 @@ pub fn menu() -> Vec { Item::Cmd("Set Corners…", set_corners::COMMAND, Value::Null), tool("Slide Anchor Along Path", slide_anchor::ID), Item::Cmd("Shared Edge Merge Tool", shared_edge::COMMAND, json!({})), + tool("Tangent Circle Tool", tangent_circle_tool::ID), tool("Trim at Crossings Tool", trim::ID), Item::Sep, Item::Cmd("Anchor Inspector", "window.panel", json!({ "panel": ID })), @@ -79,6 +85,8 @@ pub fn menu() -> Vec { 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 })), + Item::Cmd("Add Bounding Rectangle…", BOUNDING_RECTANGLE, json!({ "offset": 0, "each": false })), + Item::Cmd("Add Bounding Circle…", BOUNDING_CIRCLE, json!({ "offset": 0, "each": false })), ] } @@ -199,7 +207,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { /// Tools whose options the dialog edits. pub fn has_options(tool: &str) -> bool { - [anchor_eraser::ID, extend_path::ID].contains(&tool) + [anchor_eraser::ID, extend_path::ID, tangent_circle_tool::ID].contains(&tool) } /// Open the options of add-on tool `tool` with its current values. @@ -229,6 +237,16 @@ fn body(_app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { }); return false; } + if d.str("__tool") == tangent_circle_tool::ID { + let (lo, hi) = tangent_circle_tool::RADIUS_RANGE; + let r = d.f64("radius", tangent_circle_tool::RADIUS); + widgets::label_row(ui, tl!("Radius:"), LABEL_W, |ui| { + if let Some(x) = widgets::range_field(ui, "tangent-circle-radius", r, lo..=hi, " pt", 2, 96.0) { + d.fields.insert("radius".into(), json!(x)); + } + }); + return false; + } let rows = [ ("size", "Size:", anchor_eraser::SIZE_RANGE, "px", anchor_eraser::SIZE), ("tolerance", "Tolerance:", anchor_eraser::TOLERANCE_RANGE, "", anchor_eraser::TOLERANCE), diff --git a/crates/ui-egui/src/addons/pathtools/bridge.rs b/crates/ui-egui/src/addons/pathtools/bridge.rs index 4b9926d616..5d6a18d282 100644 --- a/crates/ui-egui/src/addons/pathtools/bridge.rs +++ b/crates/ui-egui/src/addons/pathtools/bridge.rs @@ -1,6 +1,7 @@ //! Smooth Bridge in the interface: its dialog (the arcs' radius as a percentage of the smaller -//! circle's radius, Keep Originals), which previews on the canvas and runs `addon.pathtools.bridge` -//! on OK. +//! circle's radius, or with Constant Gap that radius plus a gap; the reach, unavailable with two +//! circles selected; Keep Originals), which previews on the canvas and runs +//! `addon.pathtools.bridge` on OK. use egui::Ui; use serde_json::{Value, json}; @@ -16,27 +17,61 @@ pub const KIND: &str = "smoothBridge"; /// The radius the command takes (%), and its default. const RADII: std::ops::RangeInclusive = 1.0..=1000.0; const RADIUS: f64 = 100.0; +/// The gap the command takes (pt), and the dialog's first one. +const GAPS: std::ops::RangeInclusive = 0.0..=1000.0; +const GAP: f64 = 4.0; +/// The reach the command takes (pt), and its default. +const REACHES: std::ops::RangeInclusive = 0.0..=10000.0; +const REACH: f64 = 10.0; const LABEL_W: f32 = 60.0; const FIELD_W: f32 = 90.0; /// The dialog's fields to start with: the command's defaults. pub(crate) fn fields() -> Value { - json!({ "radius": RADIUS, "keepOriginals": false }) + json!({ "radius": RADIUS, "constantGap": false, "gap": GAP, "reach": REACH, "keepOriginals": false }) } pub(crate) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Smooth Bridge").to_string(), body, confirm, preview: true, min_width: 280.0, ..DialogSpec::FORM }; -/// The command's parameters from the dialog's fields. +/// The command's parameters from the dialog's fields: the radius, or with Constant Gap the gap. fn params(d: &Dialog) -> Value { - json!({ "radius": d.f64("radius", RADIUS), "keepOriginals": d.bool("keepOriginals") }) + let (reach, keep) = (d.f64("reach", REACH), d.bool("keepOriginals")); + if d.bool("constantGap") { + json!({ "gap": d.f64("gap", GAP), "reach": reach, "keepOriginals": keep }) + } else { + json!({ "radius": d.f64("radius", RADIUS), "reach": reach, "keepOriginals": keep }) + } } fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { - widgets::label_row(ui, tl!("Radius:"), LABEL_W, |ui| { - if let Some(v) = widgets::range_field(ui, ("dlg-num", "radius"), d.f64("radius", RADIUS), RADII, "%", 0, FIELD_W) { - d.fields.insert("radius".into(), json!(v)); + let unit = app.session.general_unit(); + form::check(ui, d, "constantGap", tl!("Constant Gap")); + if d.bool("constantGap") { + widgets::label_row(ui, tl!("Gap:"), LABEL_W, |ui| { + form::length_within(ui, d, "gap", unit, FIELD_W, Some(GAPS)); + }); + } else { + widgets::label_row(ui, tl!("Radius:"), LABEL_W, |ui| { + if let Some(v) = widgets::range_field(ui, ("dlg-num", "radius"), d.f64("radius", RADIUS), RADII, "%", 0, FIELD_W) { + d.fields.insert("radius".into(), json!(v)); + } + }); + } + // The reach applies to three or more circles; two are bridged at any distance. Counted once, + // before a preview replaces the selection with its result. + let many = match d.fields.get("many").and_then(Value::as_bool) { + Some(many) => many, + None => { + let many = app.session.doc().map(|doc| doc.selection.objects.len() > 2).unwrap_or(true); + d.fields.insert("many".into(), json!(many)); + many } + }; + ui.add_enabled_ui(many, |ui| { + widgets::label_row(ui, tl!("Reach:"), LABEL_W, |ui| { + form::length_within(ui, d, "reach", unit, FIELD_W, Some(REACHES)); + }); }); form::check(ui, d, "keepOriginals", tl!("Keep Originals")); form::preview(app, ui, d, "Smooth Bridge", COMMAND, params(d)); @@ -72,9 +107,11 @@ mod tests { menus::invoke(&mut app, &cmd, p); assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(super::KIND)); let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); - for s in ["Smooth Bridge", "Radius:", "Keep Originals", "Preview"] { + for s in ["Smooth Bridge", "Constant Gap", "Radius:", "Reach:", "Keep Originals", "Preview"] { assert!(shown.contains(s), "{s} in {shown}"); } + assert!(!shown.contains("Gap:"), "{shown}"); + assert!(!app.ui.dialog.as_ref().unwrap().bool("many"), "Reach unavailable for two circles"); let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().unwrap().len(); app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(true)); painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); @@ -89,4 +126,30 @@ mod tests { assert_eq!(app.session.doc().unwrap().history.undo.len(), n + 1); assert_eq!(count(&app), 3, "the circles and the outline above them"); } + + #[test] + fn constant_gap_shows_the_gap_and_bridges_many_circles_within_reach() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + // Three circles 4 apart in a row and one far off. + let ids: Vec = [100.0, 124.0, 148.0, 300.0].iter().map(|&x| circle(&mut app, x, 10.0)).collect(); + app.run("select.set", json!({ "ids": ids })).unwrap(); + menus::invoke(&mut app, super::COMMAND, serde_json::Value::Null); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("constantGap".into(), json!(true)); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert!(shown.contains("Gap:") && !shown.contains("Radius:"), "{shown}"); + // A preview leaves two objects selected (one shape and the far circle); Reach stays + // available for the four circles the command still bridges. + app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(app.session.doc().unwrap().selection.objects.len(), 2, "previewed"); + assert!(app.ui.dialog.as_ref().unwrap().bool("many"), "Reach available for four circles"); + let p = super::params(app.ui.dialog.as_ref().unwrap()); + assert_eq!(p, json!({"gap": 4.0, "reach": 10.0, "keepOriginals": false}), "the gap, not the radius"); + crate::dialogs::confirm(&mut app).unwrap(); + let top: Vec = app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); + assert_eq!(top, [ids[2], ids[3]], "one shape in the topmost joined circle's place, and the far circle"); + } } diff --git a/crates/ui-egui/src/addons/pathtools/tests.rs b/crates/ui-egui/src/addons/pathtools/tests.rs index 3f7006e536..2c49c661fe 100644 --- a/crates/ui-egui/src/addons/pathtools/tests.rs +++ b/crates/ui-egui/src/addons/pathtools/tests.rs @@ -22,6 +22,7 @@ fn the_plugins_submenu_selects_the_tools_and_opens_the_anchor_inspector() { ("Measure & Inspect Tool", "measureInspect"), ("Parametric Shape Tool", "parametricShape"), ("Slide Anchor Along Path", "slideAnchor"), + ("Tangent Circle Tool", "tangentCircle"), ("Trim at Crossings Tool", "trimAtCrossings"), ] { let e = under(label).expect(label); @@ -98,6 +99,14 @@ fn double_clicking_the_brush_opens_its_options_and_ok_sets_them() { app.ui.dialog.as_mut().unwrap().fields.insert("mode".into(), json!("arc")); crate::dialogs::confirm(&mut app).unwrap(); assert_eq!(app.session.tool_options_of("extendPath")["mode"], json!("arc")); + // The Tangent Circle tool's radius for Shift. + app.run("tool.options", json!({"tool": "tangentCircle"})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("radius", 0.0), 36.0); + let text = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert!(text.contains("Tangent Circle Tool Options") && text.contains("Radius:"), "{text}"); + app.ui.dialog.as_mut().unwrap().fields.insert("radius".into(), json!(12.5)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.session.tool_options_of("tangentCircle")["radius"], json!(12.5)); assert!(app.run("tool.options", json!({"tool": "measureInspect"})).is_err()); } @@ -329,3 +338,195 @@ 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(); + // The end points of every two-anchor path in the document, rounded and sorted. + let lines = |app: &VectorcraftApp| { + let mut ends = Vec::new(); + app.session.doc().unwrap().doc.walk(|node| { + if let Some(path) = node.path_data() { + for sub in &path.subpaths { + if sub.anchors.len() == 2 { + let mut pair: Vec<(i64, i64)> = + sub.anchors.iter().map(|a| ((a.p.x * 1e6).round() as i64, (a.p.y * 1e6).round() as i64)).collect(); + pair.sort(); + ends.push(pair); + } + } + } + }); + ends.sort(); + ends + }; + let (start, n, nodes) = (app.session.doc().unwrap().doc.clone(), 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); + }; + + // Each choice previews the same two lines, and OK with that choice keeps them as one step; + // undo puts the document back as it was. + let mut first: Option>> = None; + for (_, kind) in super::TANGENT_KINDS { + open(&mut app); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "preview".into(), json!(true)); + crate::dialogs::set_field(d, "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"); + let previewed = lines(&app); + assert_eq!(previewed.len(), 2, "{kind}"); + let first = first.get_or_insert_with(|| previewed.clone()); + assert_eq!(&previewed, first, "{kind}: the same lines as the first choice"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((steps(&app), count(&app)), (n + 1, nodes + 2), "{kind}: one undo step"); + assert_eq!(&lines(&app), first, "{kind}: OK keeps the previewed lines"); + app.run("edit.undo", json!({})).unwrap(); + app.run("select.set", json!({"ids": [oval, dot]})).unwrap(); + assert_eq!((steps(&app), count(&app)), (n, nodes), "{kind}: undone"); + assert_eq!(app.session.doc().unwrap().doc, start, "{kind}: undo restores the document"); + } + let first = first.unwrap(); + + // Switching the choice while the preview is on keeps the same two lines on the canvas. + open(&mut app); + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for (_, kind) in super::TANGENT_KINDS.iter().rev() { + 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}: switched in place"); + assert_eq!(lines(&app), first, "{kind}: the same lines after the switch"); + } + crate::dialogs::cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, start, "Cancel takes the preview away"); + assert_eq!(steps(&app), n, "and adds no 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); +} + +/// Object › Plug-ins › Path Precision Tools › Add Bounding Rectangle… and Add Bounding Circle… are +/// dimmed with nothing selected and open the command dialog with Offset 0, One per Object off and +/// Preview off. With Preview on the shape shows on the canvas; Cancel takes it away with no step of +/// history. OK with the defaults draws one shape around the whole selection; OK with an Offset and +/// One per Object draws a larger shape around each object, as one undo step. An Offset that takes +/// the shape past the canvas edge leaves the dialog open, the document unchanged and an error. +#[test] +fn add_bounding_rectangle_and_circle_open_a_dialog_with_offset_and_one_per_object() { + let mut app = app(); + let items = [("Add Bounding Rectangle…", super::BOUNDING_RECTANGLE), ("Add Bounding Circle…", super::BOUNDING_CIRCLE)]; + let find = |app: &VectorcraftApp, label: &str| { + let entries = menus::menu_entries(app); + entries.into_iter().find(|e| e.path == ["Object", "Plug-ins", "Path Precision Tools"] && e.label == label).expect(label) + }; + for (label, command) in items { + let item = find(&app, label); + assert_eq!((item.command.as_deref(), &item.params), (Some(command), &json!({"offset": 0, "each": false}))); + assert!(!item.enabled, "{label} with nothing selected"); + } + let a = app.run("shape.rectangle", json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let b = app.run("shape.rectangle", json!({"x": 100, "y": 20, "width": 20, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.node_count(); + let made = |app: &VectorcraftApp| { + let st = app.session.doc().unwrap(); + st.selection.objects.iter().map(|id| st.doc.bounds_of(&[*id], false).unwrap()).collect::>() + }; + let open = |app: &mut VectorcraftApp, label: &str| { + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let item = find(app, label); + assert!(item.enabled, "{label}"); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(app, &cmd, p); + }; + let near = |r: vectorcraft_geom::Rect, want: [f64; 4]| [r.x0, r.y0, r.x1, r.y1].iter().zip(want).all(|(v, w)| (v - w).abs() < 1e-6); + for (label, command) in items { + let (start, n, nodes) = (app.session.doc().unwrap().doc.clone(), steps(&app), count(&app)); + open(&mut app, label); + let d = app.ui.dialog.as_ref().unwrap_or_else(|| panic!("{label}: a dialog opens")); + assert_eq!((d.str("__command"), d.str("__label")), (command.to_string(), label.trim_end_matches('…').to_string())); + assert_eq!((d.f64("offset", -1.0), d.bool("each"), d.bool("preview")), (0.0, false, false), "{label}"); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in [label.trim_end_matches('…'), "Offset", "One per Object", "Preview"] { + assert!(shown.contains(s), "{label}: {s} in {shown}"); + } + assert_eq!(count(&app), nodes, "{label}: no preview without the checkbox"); + + // Preview on: the shape is on the canvas. Cancel: as it was, with no step of history. + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "preview".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(count(&app), nodes + 1, "{label}: previewed"); + crate::dialogs::cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, start, "{label}: Cancel takes the preview away"); + assert_eq!(steps(&app), n, "{label}: and adds no undo step"); + + // OK with the defaults: one shape around the whole selection, from (10, 20) to (120, 60). + open(&mut app, label); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!((steps(&app), count(&app)), (n + 1, nodes + 1), "{label}: one shape, one undo step"); + let whole = made(&app); + if command == super::BOUNDING_RECTANGLE { + assert!(near(whole[0], [10.0, 20.0, 120.0, 60.0]), "{label}: {:?}", whole[0]); + } else { + // The circle on the diagonal, with the 0.01 pt allowance. + let r = 110.0f64.hypot(40.0) / 2.0 + 0.01; + assert!(near(whole[0], [65.0 - r, 40.0 - r, 65.0 + r, 40.0 + r]), "{label}: {:?}", whole[0]); + } + + // OK with an Offset of 5 pt and One per Object: a shape around each object, one undo step. + open(&mut app, label); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "offset".into(), json!(5)); + crate::dialogs::set_field(d, "each".into(), json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((steps(&app), count(&app)), (n + 2, nodes + 3), "{label}: two shapes, one more undo step"); + let each = made(&app); + if command == super::BOUNDING_RECTANGLE { + assert!(near(each[0], [5.0, 15.0, 45.0, 65.0]) && near(each[1], [95.0, 15.0, 125.0, 65.0]), "{label}: {each:?}"); + } else { + let (ra, rb) = (30.0f64.hypot(40.0) / 2.0 + 5.01, 20.0f64.hypot(40.0) / 2.0 + 5.01); + let want = [[25.0 - ra, 40.0 - ra, 25.0 + ra, 40.0 + ra], [110.0 - rb, 40.0 - rb, 110.0 + rb, 40.0 + rb]]; + assert!(near(each[0], want[0]) && near(each[1], want[1]), "{label}: {each:?}"); + } + + // An Offset past the canvas edge: the dialog stays open, nothing is drawn, and the error + // says why. + let (n, nodes) = (steps(&app), count(&app)); + open(&mut app, label); + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "offset".into(), json!(5_000_000)); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("the shape would reach past the edge of the canvas"), "{label}: {e}"); + assert!(app.ui.dialog.is_some(), "{label}: the dialog stays open"); + crate::dialogs::cancel(&mut app); + assert_eq!((steps(&app), count(&app)), (n, nodes), "{label}: nothing drawn"); + } + // Every language with complete menus has the menu items, the dialog's headings and its labels. + for lang in crate::i18n::Lang::all().filter(|l| l.complete_menus()) { + for s in ["Add Bounding Rectangle…", "Add Bounding Circle…", "Offset", "One per Object"] { + assert!(crate::i18n::has(lang, s), "{}: {s}", lang.code()); + } + } +} diff --git a/crates/ui-egui/src/addons/shapes.rs b/crates/ui-egui/src/addons/shapes.rs index b856f15603..bdf8763927 100644 --- a/crates/ui-egui/src/addons/shapes.rs +++ b/crates/ui-egui/src/addons/shapes.rs @@ -48,6 +48,12 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) -> bool } fit.separator(ui); } + // The tools with live shape widgets: Hide/Show Shape Widgets first, so a narrow bar leaves out + // the shape's fields before it. + if vectorcraft_tools::shape::shows_shape_widgets(&tool) { + shape_widgets_button(app, ui, fit); + fit.separator(ui); + } match active_shape.as_str() { "ellipse" => draw_ellipse_controls(app, ui, fit, &opts, selected_custom), @@ -60,6 +66,15 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) -> bool true } +/// Hide Shape Widgets, or Show Shape Widgets while they are hidden (`view.shapeWidgets`), at least 52 +/// points wide and wider for a longer translated label, while `fit` has room for it. +fn shape_widgets_button(app: &mut VectorcraftApp, ui: &mut Ui, fit: &mut Fit) { + let label = if app.ui.view.shape_widgets { tl!("Hide Shape Widgets") } else { tl!("Show Shape Widgets") }; + if fit.room(ui, &[widgets::flat_button_fit_width(ui, label, 52.0)]) && widgets::flat_button_fit(ui, label, 52.0).clicked() { + app.run("view.shapeWidgets", json!({})).ok(); + } +} + /// Whether `fit` has room in the row `ui` for the label `text` with a field `field` wide after it. fn field_room(ui: &Ui, fit: &mut Fit, text: &egui::RichText, field: f32) -> bool { fit.room(ui, &[widgets::text_width(ui, text.clone()), field]) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index a05dcedb38..0fc0d136b0 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -152,6 +152,7 @@ impl VectorcraftApp { system_paste_at: f64::NEG_INFINITY, clipboard_probe: None, picks: picks::Picks::default(), + original_editor: Default::default(), screen_sampler: None, font_check: None, #[cfg(not(target_arch = "wasm32"))] @@ -164,12 +165,15 @@ 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(), forwarded_modifiers: None, forwarded_modifiers_held: false, forwarded_frame: false, + forwarded_clipboard: false, + forwarded_presses: vec![], synthetic_modifiers: false, ime_marked: None, ime_context: Default::default(), @@ -185,6 +189,8 @@ impl VectorcraftApp { automation_roots: None, synthetic_frame: false, pending_plugin_install: None, + pending_profile_open: None, + queued_profile_opens: Default::default(), script_picked: Vec::new(), script_picked_left_out: false, pen_end: Default::default(), @@ -197,6 +203,8 @@ impl VectorcraftApp { input_frames: vec![], shortcuts_frames: vec![], held_tool: Vec::new(), + alt_tap: Default::default(), + hold_keys: Default::default(), synthetic_injected: false, injected_events: vec![], injected_generation: InputGeneration::default(), @@ -635,9 +643,14 @@ impl VectorcraftApp { plugin_runs::show(self, &ctx); trace_runs::show(self, &ctx); opening::show(self, &ctx); + placing::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); + // A shape drawn on the canvas, in a dialog or by a command in this pass shows the Transform + // panel (Show on Shape Creation). + panels::transform::show_on_shape_creation(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/clipboard.rs b/crates/ui-egui/src/app/clipboard.rs index 5efe2db308..9e7263aee5 100644 --- a/crates/ui-egui/src/app/clipboard.rs +++ b/crates/ui-egui/src/app/clipboard.rs @@ -3,8 +3,9 @@ use super::VectorcraftApp; impl VectorcraftApp { /// Hand a queued text copy to egui. Called after `tick`, after the UI phase's input and at the /// end of the pass; the later calls are what an input- or menu-driven fallback Copy needs, and - /// `take` keeps it single-shot. - pub(super) fn flush_clipboard_out(&mut self, ctx: &egui::Context) { + /// `take` keeps it single-shot. A Copy or Cut that labels left to the next pass hands its text + /// over as soon as it runs ([`crate::shortcuts::handle`]). + pub(crate) fn flush_clipboard_out(&mut self, ctx: &egui::Context) { if let Some(t) = self.clipboard_out.take() { ctx.copy_text(t); } diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 701c0f5ffc..75a4f05164 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -214,10 +214,20 @@ impl VectorcraftApp { Ok(Some(started)) => return Ok(started), Ok(None) => {} } + // Edit › Color Settings' Ask When Pasting, then any swatch conflict. + if let Some(r) = dialogs::profile_mismatch::ask_paste(self, id, ¶ms) { + return r; + } if let Some(r) = dialogs::swatch_conflict::ask(self, id, ¶ms) { return r; } } + // A drag from another document asks as Paste does (its swatches are always added). + if id == dialogs::profile_mismatch::DROP + && let Some(r) = dialogs::profile_mismatch::ask_paste(self, id, ¶ms) + { + return r; + } // Native files carry the view they reopen at. if fileio::SaveMode::of(id).is_some() { io::remember_view(self); @@ -265,6 +275,10 @@ impl VectorcraftApp { } // 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); + // A renamed color group stays selected in the Swatches panel. + if let Some(ctx) = self.ui_ctx.clone() { + panels::swatches::after_command(&ctx, id, ¶ms, v); + } if id == "file.new" { self.status(""); // New Document's Pixel preview mode (Overprint Preview is the engine's). @@ -449,11 +463,18 @@ impl VectorcraftApp { /// and the tool remembered for the toolbar group and for the Touch workspace's drawing mode /// stays as it was. pub(crate) fn try_select_tool(&mut self, id: &str) -> Result<(), String> { + let back = self.ui.brush_key_color_pick.as_ref().map(|pick| pick.back.clone()); + crate::dialogs::cancel_brush_key_color(self, false); // The tip of a pen whose eraser end selected the Eraser doesn't undo this choice, and // neither does letting go of a held tool shortcut. self.pen_end.forget_tool(); self.held_tool.clear(); - self.activate_tool(id, true)?; + if let Err(error) = self.activate_tool(id, true) { + if let Some(back) = back.filter(|_| self.session.tool_id() == "eyedropper") { + self.return_to_tool(&back); + } + return Err(error); + } let now = self.session.tool_id(); if crate::touch::is_drawing_tool(now) { self.ui.touch_drawing_tool = Some(now.to_string()); diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs index 95f719d08b..b6c7eaae97 100644 --- a/crates/ui-egui/src/app/input.rs +++ b/crates/ui-egui/src/app/input.rs @@ -17,7 +17,9 @@ impl VectorcraftApp { if self.fonts_ready { tools_float::cancel_move_on_escape(self, ctx); crate::custom_toolbars::cancel_move_on_escape(self, ctx); - shortcuts::handle(self, ctx); + if !crate::menus::handle_keyboard_input(self, ctx) { + shortcuts::handle(self, ctx); + } } // A Copy taken in this UI phase (an egui copy event, or a command it runs) is published in // this same pass: waiting for the next `tick` can leave the command unissued when an idle @@ -214,6 +216,8 @@ impl VectorcraftApp { raw.events.insert(0, egui::Event::ModifiersChanged(self.host_modifiers)); } self.forwarded_frame = !self.forwarded.is_empty(); + self.forwarded_clipboard = self.forwarded.iter().any(|e| matches!(e, egui::Event::Copy | egui::Event::Cut)); + self.forwarded_presses = self.forwarded.iter().filter(|e| matches!(e, egui::Event::Key { pressed: true, .. })).cloned().collect(); if !self.forwarded.is_empty() { if let Some(m) = self.forwarded_modifiers.take() { raw.events.push(egui::Event::ModifiersChanged(m)); diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index 0949b9290f..a1c2af21ff 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -132,6 +132,7 @@ impl VectorcraftApp { snap_to_point: self.ui.view.snap_to_point, snap_to_glyph: self.ui.view.snap_to_glyph, corner_widgets: self.ui.view.corner_widgets && self.ui.view.edges, + shape_widgets: self.ui.view.shape_widgets, screen: self.screen_frame(), artboard: self.view().map_or(0, |v| v.artboard), } diff --git a/crates/ui-egui/src/background.rs b/crates/ui-egui/src/background.rs index b0bdcc6287..f1a3032cf0 100644 --- a/crates/ui-egui/src/background.rs +++ b/crates/ui-egui/src/background.rs @@ -1,7 +1,9 @@ //! Background Save and Background Export (Preferences → File Handling): a save or an export encodes //! and writes a snapshot of the document on a worker thread while editing goes on. The status bar //! shows what is in progress; the result is applied on the UI thread when it arrives (a save marks -//! the document saved as of its snapshot, so edits made meanwhile keep it modified). +//! the document saved as of its snapshot, so edits made meanwhile keep it modified). Exports and +//! saves show in the progress window ([`crate::export_progress`]) with Cancel and Continue in +//! Background. //! //! It needs a thread-safe writer from the host ([`crate::Services::write_shared`], desktop); //! without one (the web, which downloads) the work runs at once, as with the preference off. @@ -44,15 +46,27 @@ struct Task { scope: ScopeHandle, } +/// What a job that shows in the progress window does: its Cancel and Continue in Background act on +/// the jobs of its kind. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + /// An export (Background Export): `file.cancelExport`, `file.exportInBackground`. + Export, + /// A save (Background Save): `file.cancelSave`, `file.saveInBackground`. + Save, +} + /// A job in progress. pub struct Job { id: u64, + /// What the job does, for the progress window and its commands. + pub kind: Kind, /// What the status bar and `ui.inspect` show ("Saving Poster.vectorcraft"); empty for work they /// don't show. pub label: String, /// The document the job reads (`DocState::uid`), if any. pub doc: Option, - /// How far an export has got, and its Cancel ([`crate::export_progress`] shows it). + /// How far an export or a save has got, and its Cancel ([`crate::export_progress`] shows it). pub progress: Option>, /// Continue in Background: the progress dialog no longer shows this job. pub hidden: bool, @@ -83,6 +97,9 @@ pub struct Background { next_id: u64, /// Work started while this is set runs at once, whatever the preferences ([`in_foreground`]). foreground: bool, + /// [`crate::state::UiState::status_sets`] right after Cancel Save set its line, or after a save + /// it reached set the line that followed it; `None` before any Cancel Save. + pub(crate) save_cancel_line: Option, } impl Background { @@ -119,18 +136,41 @@ impl Background { /// Cancel every export in progress → how many there were. pub fn cancel_exports(&mut self) -> usize { + self.cancel(Kind::Export) + } + + /// Hide the exports in progress from the progress dialog (they go on) → how many there were. + pub fn hide_exports(&mut self) -> usize { + self.hide(Kind::Export) + } + + /// Cancel every save in progress that the progress window can show → how many there were. + pub fn cancel_saves(&mut self) -> usize { + self.cancel(Kind::Save) + } + + /// Hide the saves in progress from the progress window (they go on) → how many there were. + pub fn hide_saves(&mut self) -> usize { + self.hide(Kind::Save) + } + + /// Is a job of `kind` in progress that can still be canceled? + pub fn running(&self, kind: Kind) -> bool { + self.jobs.iter().any(|j| j.kind == kind && j.progress.is_some() && !j.cancelled()) + } + + fn cancel(&mut self, kind: Kind) -> usize { let mut n = 0; - for p in self.jobs.iter().filter(|j| !j.cancelled()).filter_map(|j| j.progress.as_ref()) { + for p in self.jobs.iter().filter(|j| j.kind == kind && !j.cancelled()).filter_map(|j| j.progress.as_ref()) { p.cancel(); n += 1; } n } - /// Hide the exports in progress from the progress dialog (they go on) → how many there were. - pub fn hide_exports(&mut self) -> usize { + fn hide(&mut self, kind: Kind) -> usize { let mut n = 0; - for j in self.jobs.iter_mut().filter(|j| j.progress.is_some() && !j.hidden && !j.cancelled()) { + for j in self.jobs.iter_mut().filter(|j| j.kind == kind && j.progress.is_some() && !j.hidden && !j.cancelled()) { j.hidden = true; n += 1; } @@ -163,6 +203,34 @@ pub fn run_with_progress( progress: Option>, work: impl FnOnce(Writer) -> Result + Send + 'static, then: impl FnOnce(&mut VectorcraftApp, Result) -> Result + 'static, +) -> Result { + start(app, enabled, label, doc, progress, Kind::Export, work, then) +} + +/// [`run_with_progress`] for a save of document `doc`: the progress window shows it as a save, and +/// its Cancel is `file.cancelSave`. +pub fn run_saving( + app: &mut VectorcraftApp, + enabled: bool, + label: String, + doc: u64, + progress: Arc, + work: impl FnOnce(Writer) -> Result + Send + 'static, + then: impl FnOnce(&mut VectorcraftApp, Result) -> Result + 'static, +) -> Result { + start(app, enabled, label, Some(doc), Some(progress), Kind::Save, work, then) +} + +#[allow(clippy::too_many_arguments)] +fn start( + app: &mut VectorcraftApp, + enabled: bool, + label: String, + doc: Option, + progress: Option>, + kind: Kind, + work: impl FnOnce(Writer) -> Result + Send + 'static, + then: impl FnOnce(&mut VectorcraftApp, Result) -> Result + 'static, ) -> Result { let mut work: Work = Box::new(work); let shared = app.services.write_shared.clone().filter(|_| enabled && !app.background.foreground && app.services.download.is_none()); @@ -174,7 +242,8 @@ pub fn run_with_progress( let (sets, status) = (app.ui.status_sets, if label.is_empty() { String::new() } else { format!("{label}…") }); let bg = &mut app.background; bg.next_id += 1; - bg.jobs.push(Job { id, label: label.clone(), doc, progress, hidden: false, sets, line: status.clone(), then: Box::new(then) }); + let line = status.clone(); + bg.jobs.push(Job { id, kind, label: label.clone(), doc, progress, hidden: false, sets, line, then: Box::new(then) }); if label.is_empty() { return Ok(json!({ "background": true })); } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ef7ef0ba78..921bb23c4e 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -52,7 +52,7 @@ use fill::{fill_view, polygon_area}; #[cfg(test)] use grid::ruler_rects; use grid::{LineLook, PIXEL_GRID, PIXEL_GRID_ZOOM, checker, clip_segment, grid, ruler_input, rulers, rulers_hidden, textured_quad, view_bounds}; -pub(crate) use grid::{RulerScale, checker_texture, ruler_label, ruler_origin_dragging}; +pub(crate) use grid::{RulerScale, checker_texture, checker_tile, ruler_label, ruler_origin_dragging}; #[cfg(test)] pub(crate) use grid::{TRANSPARENCY_GRID, vertical_label_height}; use home::home; @@ -63,7 +63,9 @@ use outline::{OVERLAY_MAX_ANCHORS, c32, node_outline, walk_drawn}; pub use overlays::SharedPaths; #[cfg(test)] use overlays::selected_anchor; -use overlays::{HandleLook, blend_widgets_overlay, draw_inside_overlay, draw_overlays, hover_highlight, ime_geometry, selection_overlay}; +use overlays::{ + HandleLook, blend_widgets_overlay, draw_inside_overlay, draw_overlays, hover_highlight, ime_geometry, overlay_hover_text, selection_overlay, +}; pub use panes::{Layout as TileLayout, Panes}; pub(crate) use panes::{consolidate, note_drop, noted_cursor, pane, release_on_noted, tile, tiled_area}; pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job}; @@ -79,6 +81,7 @@ pub use tool_overlays::{HiddenChars, SpellingMarks}; use tool_overlays::{ grid_repeat_overlay, hidden_chars_overlay, live_paint_gap_overlays, mirror_axis_overlay, nine_slice_overlay, original_path_overlay, print_tiling_overlay, radial_repeat_overlay, rotate_view_dial, shaper_widget_overlay, slice_overlay, spelling_overlay, thread_overlays, + trace_split_overlay, }; pub(crate) use view::animated_zoom; pub(crate) use view::drag_rotation; @@ -424,6 +427,11 @@ 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); + // The tooltips say what a click does, so none shows where the click does something else: + // while Space lends a view tool, or over an artboard's name. + let space = ui.input(|i| drag::space_lends_view_tools(app, i.modifiers, i.key_down(egui::Key::Space))); + let quiet = space || ui.data(|d| d.get_temp::(drag_id())).is_some(); + overlay_hover_text(ui, &xf, &overlays, quiet, |p| artboards::artboard_name_at(app, ui, &xf, p).is_some()); if !revolve_edit { shaper_widget_overlay(app, &painter, &xf); crate::panels::three_d::paint_graphic_handles(app, &painter, &xf); @@ -1349,6 +1357,7 @@ fn selection_visuals( mirror_axis_overlay(app, painter, xf); grid_repeat_overlay(app, painter, xf); radial_repeat_overlay(app, painter, xf); + trace_split_overlay(app, painter, xf); if app.ui.view.text_threads { // Under the tools' overlays: a selected frame's own ports are drawn over its thread's. let mut threads = thread_overlays(app, xf.zoom); @@ -1379,4 +1388,6 @@ fn selection_visuals( #[cfg(test)] mod tests; #[cfg(test)] +mod tests_edge_scroll; +#[cfg(test)] mod tests_ui_scaling; diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index bdda812306..36188617ac 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -16,6 +16,8 @@ pub(super) struct HoverContext { pub(super) center: Point, pub(super) zoom: f64, pub(super) rotation: f64, + /// A pen turning in place changes a Bristle tip even when its pointer stays still. + pub(super) pen: Option, /// The active document's id and revision (which moves with every edit, undo and selection /// change). pub(super) doc: Option<(u64, u64)>, diff --git a/crates/ui-egui/src/canvas/grid.rs b/crates/ui-egui/src/canvas/grid.rs index 001b2e31f7..5d533f7eaf 100644 --- a/crates/ui-egui/src/canvas/grid.rs +++ b/crates/ui-egui/src/canvas/grid.rs @@ -11,20 +11,31 @@ pub(crate) fn checker_texture( setup: &vectorcraft_doc::DocSetup, display: Option<&vectorcraft_color::cms::display::DisplayTransform>, ) -> (egui::TextureHandle, f32) { - let colors = setup.grid_colors.map(|c| crate::display_profile::color32(display, crate::panels::c32(&c))); // A tile of its own with a display profile, so a preview drawn in sRGB beside the canvas // doesn't make the canvas's tile again each frame. let id = egui::Id::unique("transparency-grid-tile").with(display.is_some()); + (checker_tile(ctx, setup.grid_colors, display, id), setup.grid_size.cell()) +} + +/// The transparency grid's 2 × 2-cell tile in the colors `grid_colors` (the first in the top-left +/// and bottom-right cells), converted into the display profile `display` when there is one, and +/// cached under `id` until the colors change. +pub(crate) fn checker_tile( + ctx: &egui::Context, + grid_colors: [vectorcraft_color::Color; 2], + display: Option<&vectorcraft_color::cms::display::DisplayTransform>, + id: egui::Id, +) -> egui::TextureHandle { + let colors = grid_colors.map(|c| crate::display_profile::color32(display, crate::panels::c32(&c))); let cached = ctx.data(|d| d.get_temp::<([Color32; 2], egui::TextureHandle)>(id)).filter(|(c, _)| *c == colors); - let tex = cached.map(|(_, t)| t).unwrap_or_else(|| { + cached.map(|(_, t)| t).unwrap_or_else(|| { let [a, b] = colors; let img = egui::ColorImage::new([2, 2], vec![a, b, b, a]); let opts = egui::TextureOptions { wrap_mode: egui::TextureWrapMode::Repeat, ..egui::TextureOptions::NEAREST }; let t = ctx.load_texture(TRANSPARENCY_GRID, img, opts); ctx.data_mut(|d| d.insert_temp(id, (colors, t.clone()))); t - }); - (tex, setup.grid_size.cell()) + }) } /// Name of the transparency grid's texture. diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index d811ad3bac..36f3cb2a5f 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -5,16 +5,23 @@ use super::drag::{ tool_drag_moved, tool_frame_moves, tool_holds, tool_press_doc_id, }; use super::view::{ - HOLD_DELAY, HOLD_ZOOM, SCRUB_SLOP, SCRUB_ZOOM, WheelTurn, animated_zoom, pan_pixels, pan_ppp, rotate_about, scroll_view, touch_gestures, - trackpad_turn, wheel, whole_pixels, zoom_about, + HOLD_DELAY, HOLD_ZOOM, SCRUB_SLOP, SCRUB_ZOOM, WheelTurn, animated_zoom, edge_scroll, edge_scroll_pixels, pan_pixels, pan_ppp, rotate_about, + scroll_view, touch_gestures, trackpad_turn, wheel, whole_pixels, zoom_about, }; use super::{Color32, Drag, Mods, Point, PointerEvent, PointerKind, Pos2, Shape, Stroke, Ui, VectorcraftApp, View, Xf, json}; /// 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 cancelled = crate::dialogs::refresh_brush_key_color(app); let modal = crate::panel_docking::modal_open(app, ui.ctx()); let (pointer, m, space, hover) = wheel_view(app, ui, resp, rect, modal); + if (cancelled && pointer.primary_pressed()) || crate::dialogs::brush_key_color_input(app, ui, resp, rect) { + return; + } let v = *app.view().unwrap_or(&View::default()); let xf = Xf::at(rect, &v, app.canvas_ui_zoom); // A lifted pen or finger takes the pointer away in the frame it lifts (egui's `PointerGone`), @@ -53,7 +60,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 +69,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 +145,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 +158,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); } @@ -350,6 +363,8 @@ fn begin_drag(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) { if !tool_holds(d) { app.session.tool_hover_ended(view); } + // Read before `data_mut`: the context is locked inside it. + let edge = edge_scroll_at_press(ui, p); ui.data_mut(|dd| { dd.insert_temp(drag_id(), d); dd.insert_temp(drag_pos_id(), p); @@ -357,6 +372,8 @@ fn begin_drag(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) { // A new press has not dragged yet, whatever an interrupted one left behind. dd.remove::(tool_drag_doc_id()); dd.insert_temp(tool_press_doc_id(), xf.to_doc(p)); + // Edge scrolling waits for the pointer to move away from the press ([`edge_scroll_held`]). + dd.insert_temp(edge_scroll_id(), edge); // Space held at the press (Cmd+Space lends the Zoom tool) sizes the marquee until // it is let go ([`zoom_marquee_start`]). if matches!(d, Drag::ZoomBox { .. }) { @@ -438,6 +455,11 @@ fn drag_held(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Pos2) // mouse's, a pen's on X11 among them, take the host's latest. Other tools get // the last position only, so a costly drag preview runs once a frame. let (moves, last_pose) = tool_frame_moves(ui, app, false); + // Held near an edge of the canvas, the drag scrolls the view so it can go on past + // what shows (#8551). The moves above came before the scroll and keep the view they + // were made in; the pointer's position takes the scrolled one, so the tool gets a + // new document position though the pointer stands still. + let xf = edge_scroll_held(app, ui, f, p).unwrap_or(xf); // A frame whose pointer ends where the last one did still moved in between. let backquote = ui.input(|i| i.key_down(egui::Key::Backtick)); let mods_changed = tool_drag_mods_changed(ui, mods(m, space), backquote); @@ -464,6 +486,77 @@ fn drag_held(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Pos2) } } +/// How far the pointer moves on screen from the press, in points, before a held tool drag +/// scrolls the view at an edge of the canvas ([`edge_scroll_held`]). +const EDGE_SCROLL_SLOP: f32 = 3.0; + +/// A tool press's edge scrolling ([`edge_scroll_held`]), set when the press begins: where on screen +/// it was pressed, whether the pointer has since moved away from there, and the part of a device +/// pixel the scrolls of this press have left along each axis. Its own remainder, so the scrolls of +/// one press neither take nor leave part of a wheel scroll's. +#[derive(Clone, Copy, Debug, PartialEq)] +struct EdgeScroll { + press: Pos2, + armed: bool, + rest: (f64, f64), +} + +fn edge_scroll_id() -> egui::Id { + egui::Id::unique("canvas-edge-scroll") +} + +/// A tool press's edge scrolling as it begins at `p`, the pointer's position at the end of the +/// frame: the press is where the primary button went down, which an input batch can leave behind +/// `p`, and the moves after it in the same frame may already have gone [`EDGE_SCROLL_SLOP`] from it. +fn edge_scroll_at_press(ui: &Ui, p: Pos2) -> EdgeScroll { + let (press, moved) = ui.input(|i| { + let down = i.events.iter().rposition(|e| matches!(e, egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: true, .. })); + let press = down.and_then(|k| match i.events.get(k) { + Some(egui::Event::PointerButton { pos, .. }) => Some(*pos), + _ => None, + }); + let press = press.unwrap_or(p); + let after = down.map_or(0, |k| k + 1); + let moved = i.events.iter().skip(after).any(|e| matches!(e, egui::Event::PointerMoved(q) if (*q - press).length() >= EDGE_SCROLL_SLOP)); + (press, moved) + }); + EdgeScroll { press, armed: moved || (p - press).length() >= EDGE_SCROLL_SLOP, rest: (0.0, 0.0) } +} + +/// Scroll the view for a tool drag held at `p` near an edge of the canvas ([`edge_scroll`]), and +/// return the canvas's transform after it; `None` when the view did not move. Only once the pointer +/// has moved [`EDGE_SCROLL_SLOP`] from the press on screen, in any move of a frame (a click near the edge stays a click, and +/// a view scrolled by the wheel under a still press is not a drag), with the pointer over the +/// canvas itself (over a panel the Selection tools hand the art to the panels), and not under a +/// modal dialog. The view moves by whole device pixels; the part of a pixel left over waits for the +/// next frame on an axis that scrolls on, and stays as it is on one that does not. +fn edge_scroll_held(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) -> Option { + let mut st = ui.data(|d| d.get_temp::(edge_scroll_id()))?; + // Any move of the frame counts, not only where the pointer ends up: one that went away and came + // back to the press still dragged. + let moved = |q: Pos2| (q - st.press).length() >= EDGE_SCROLL_SLOP; + if !st.armed && (moved(p) || ui.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::PointerMoved(q) if moved(*q))))) { + st.armed = true; + ui.data_mut(|d| d.insert_temp(edge_scroll_id(), st)); + } + if !st.armed || f.modal || !ui.input(|i| i.pointer.has_pointer()) || !on_canvas(ui, f.resp, p) { + return None; + } + let by = edge_scroll(f.rect, p, ui.input(|i| i.unstable_dt))?; + let ppp = pan_ppp(app, ui); + let ui_zoom = app.canvas_ui_zoom; + let ((dx, dy), rest) = edge_scroll_pixels(st.rest, by, ppp); + st.rest = rest; + ui.data_mut(|d| d.insert_temp(edge_scroll_id(), st)); + if dx == 0.0 && dy == 0.0 { + return None; + } + let vm = app.view_mut()?; + pan_pixels(vm, (ppp, ui_zoom), (dx, dy)); + let v = *vm; + Some(Xf::at(f.rect, &v, ui_zoom)) +} + /// A drag for each of this frame's moves before the pointer's position ([`tool_frame_moves`]), each /// with the pressure and the tilt and rotation the host's feed kept for that move, else the latest. fn dispatch_frame_moves(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, backquote: bool, moves: Vec) { diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index 613b0fae9c..b4d2d44aac 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -216,15 +216,16 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: anchor_square(p, xf.to_screen(a.p), color, false, anchor(direct)); } } - // Live Corners widgets (Selection and the shape tools on a live rectangle or polygon, Direct - // Selection on any path). + // Live Corners widgets (Selection and the shape tools on a live rectangle or polygon while Show + // Shape Widgets is on, Direct Selection on any path). + let shape_widgets = app.ui.view.shape_widgets; if (matches!(tool, "selection" | "directSelection") || (shape_tool && !drawing)) && let Some(w) = vectorcraft_tools::corners::CornerWidgets::showing( &st.doc, &st.selection, xf.zoom, tool == "directSelection", - app.ui.view.corner_widgets, + app.ui.view.corner_widgets && (tool == "directSelection" || shape_widgets), app.session.prefs.hide_corner_widget_above, ) { @@ -255,10 +256,22 @@ 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 and the shape widgets are drawn (the box hides during a turn and during + // a drag of the widget). + if !drawing_boxed + && shape_widgets + && 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. - if (tool == "selection" || (shape_tool && !drawing)) && app.ui.view.bounding_box { + // Pie widgets (Selection tool, with View › Show Bounding Box and Show Shape Widgets, on live + // ellipses): each joined by a line to the outline's point at its angle. They stay while one is + // dragged. + if (tool == "selection" || (shape_tool && !drawing)) && app.ui.view.bounding_box && shape_widgets { for w in vectorcraft_tools::pie::PieWidget::of(&st.doc, &st.selection, xf.zoom) { let (on, c, r, color) = (xf.to_screen(w.on), xf.to_screen(w.at), vectorcraft_tools::pie::RADIUS_PX, c32(st.doc.layer_color(w.id))); p.line_segment([on, c], Stroke::new(1.0, color)); @@ -596,6 +609,35 @@ 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. Only the part of a disc +/// inside the canvas (`xf.rect`) has a tooltip, not the part under the rulers or scroll bars. No +/// tooltip shows while `quiet` (a canvas drag, or Space lending a view tool), while a pointer +/// button is down, or where `taken` says a press goes elsewhere (an artboard's name). +pub(super) fn overlay_hover_text(ui: &egui::Ui, xf: &Xf, overlays: &[Overlay], quiet: bool, taken: impl Fn(Pos2) -> 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 area = egui::Rect::from_center_size(c, vec2(2.0 * r, 2.0 * r)).intersect(xf.rect); + if !area.is_positive() { + continue; + } + let id = egui::Id::unique("canvas-hover-text").with(i); + let resp = ui.interact(area, id, egui::Sense::hover()); + if !quiet && !pressed && resp.hover_pos().is_some_and(|p| p.distance(c) <= r && xf.rect.contains(p) && !taken(p)) { + resp.on_hover_text(crate::i18n::t(text)); } } } diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 6b1d8ac3f2..cef27dab18 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -10,12 +10,12 @@ use std::collections::HashMap; use std::sync::Arc; use super::grid::LineLook; -use super::outline::{c32, node_outline, stroke_path, too_many_anchors}; +use super::outline::{c32, node_outline, to_screen_path, too_many_anchors}; use super::view::fit_zoom; use super::{ - Affine, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, backdrop, cache_key, - dim_on_canvas, frame_options, frame_ppp, frame_view, grid, guides_of, json, paint_paper, pixel_region, placed_key, plugin_key, pos2, rulers, - shows_artboards, textured_quad, vec2, view_rects, + Affine, BezPath, CacheKey, Point, Rect, RulerScale, Sense, Stroke, StrokeKind, Tokens, Ui, VectorcraftApp, View, Xf, artboard_edges, backdrop, + cache_key, dim_on_canvas, frame_options, frame_ppp, frame_view, grid, guides_of, json, paint_paper, pixel_region, placed_key, plugin_key, pos2, + rulers, shows_artboards, textured_quad, vec2, view_rects, }; use crate::doc_windows::Win; use crate::thumb_worker::ThumbWorker; @@ -46,6 +46,29 @@ pub struct Panes { /// By slot: the size of the view's area its view was last fitted to in a pane, and the zoom and /// center the fit gave. fits: HashMap, + /// By slot: the outlines of the selected objects the pane drew last, and what they show. + outlines: HashMap, + /// How many times a pane's outlines were made. + outlines_made: u64, +} + +/// A pane's selected-object outlines as screen shapes, and the document revision, document, +/// selection and screen mapping they were made for. +struct Outlines { + revision: u64, + /// A weak reference to the document: while it exists, no other document can take the + /// allocation's address. + doc: std::sync::Weak, + selection: Vec, + affine: [f64; 6], + shapes: Vec, +} + +impl Outlines { + /// Whether these outlines show `st`'s selection through the screen mapping `affine`. + fn shows(&self, st: &vectorcraft_engine::DocState, affine: &[f64; 6]) -> bool { + self.revision == st.revision && self.doc.ptr_eq(&Arc::downgrade(&st.doc)) && self.affine == *affine && self.selection == st.selection.objects + } } impl Panes { @@ -56,6 +79,7 @@ impl Panes { self.last.clear(); self.last_slots.clear(); self.fits.clear(); + self.outlines.clear(); } /// Upload `img`, the render `key` describes, for `slot`. @@ -311,6 +335,9 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { app.canvas.panes.clear(); } app.canvas.panes.last.clear(); + // Only the floating windows draw panes now. + let floating = &app.ui.floating; + app.canvas.panes.outlines.retain(|(u, n), _| floating.iter().any(|w| w.uid == *u && w.view == *n)); app.canvas.panes.last_slots.clear(); return false; } @@ -326,6 +353,7 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { app.canvas.panes.shown.retain(|s, _| live.contains(s)); app.canvas.panes.pending.retain(|s, _| live.contains(s)); app.canvas.panes.fits.retain(|s, _| live.contains(s)); + app.canvas.panes.outlines.retain(|s, _| live.contains(s)); // A window that moved to another pane fits it, and so does a window whose pane changed place or // size because a window opened, closed, floated or docked, or because the panes came back from // one window. A window that keeps its pane keeps its zoom and scroll, as when a tab brings its @@ -563,7 +591,9 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo guides_of(app, st, (&painter, &xf, &t), rect); } if app.ui.view.edges { - selected_objects(st, &painter, &xf); + selected_objects(&mut app.canvas.panes, slot, st, &painter, &xf); + } else { + app.canvas.panes.outlines.remove(&slot); } if app.ui.view.rulers && app.ui.screen_mode < 3 { rulers(ui, full, &xf, None, RulerScale::document(app.session.general_unit(), st.doc.ruler_origin_for(v.artboard)), &t); @@ -581,23 +611,45 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo resp.contains_pointer() && ui.input(|inp| inp.pointer.any_pressed()) } -/// The outlines of the objects selected in `st`, in their layers' colors; their bounds when they -/// have too many points to outline. -fn selected_objects(st: &vectorcraft_engine::DocState, painter: &egui::Painter, xf: &Xf) { +/// Draw the outlines of the objects selected in `st` ([`outline_shapes`]) in `slot`'s pane, from +/// the outlines `panes` kept for the slot while they show the same revision, document, selection +/// and screen mapping, and made again otherwise. +fn selected_objects(panes: &mut Panes, slot: Slot, st: &vectorcraft_engine::DocState, painter: &egui::Painter, xf: &Xf) { + let affine = xf.affine().as_coeffs(); + if !panes.outlines.get(&slot).is_some_and(|o| o.shows(st, &affine)) { + let shapes = outline_shapes(st, xf); + let kept = Outlines { revision: st.revision, doc: Arc::downgrade(&st.doc), selection: st.selection.objects.clone(), affine, shapes }; + panes.outlines.insert(slot, kept); + panes.outlines_made += 1; + } + for shape in panes.outlines.get(&slot).map_or(&[][..], |o| &o.shapes) { + painter.add(shape.clone()); + } +} + +/// The outlines of the objects selected in `st` as lines on the screen through `xf`, in their +/// layers' colors; their bounds when they have too many points to outline. +fn outline_shapes(st: &vectorcraft_engine::DocState, xf: &Xf) -> Vec { + let mut shapes = vec![]; + if st.selection.objects.is_empty() { + return shapes; + } let symbols = st.doc.symbol_boxes(); let nodes: Vec<(vectorcraft_doc::NodeId, &vectorcraft_doc::Node)> = st.selection.objects.iter().filter_map(|id| Some((*id, st.doc.node(*id)?))).collect(); let color = |id: vectorcraft_doc::NodeId| Stroke::new(1.0, c32(st.doc.layer_color(id))); + let mut stroke = |bp: &BezPath, s: Stroke| shapes.extend(to_screen_path(bp, xf).into_iter().map(|line| egui::Shape::line(line, s))); if too_many_anchors(nodes.iter().map(|(_, n)| *n)) { let bounds = nodes.iter().filter_map(|(_, n)| n.geometric_bounds_with(&symbols)).reduce(|a, b| a.union(b)); if let (Some(b), Some((id, _))) = (bounds, nodes.first()) { - stroke_path(painter, &vectorcraft_geom::shapes::rectangle(b).to_bezpath(), xf, color(*id)); + stroke(&vectorcraft_geom::shapes::rectangle(b).to_bezpath(), color(*id)); } - return; + return shapes; } for (id, n) in nodes { - stroke_path(painter, &node_outline(n, &symbols), xf, color(id)); + stroke(&node_outline(n, &symbols), color(id)); } + shapes } #[cfg(test)] diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 6c7a8cf755..b7829a7542 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -691,12 +691,16 @@ fn art_carried_through_a_tab_drops_into_a_third_documents_pane() { app.run("window.arrange.tile", json!({})).unwrap(); let source = app.session.documents()[0].doc.clone(); let third = app.session.documents()[2].doc.clone(); + // A tab's title starts with its document's name (an inactive tab shows the name alone). + let names: Vec = app.session.documents().iter().map(|d| d.title()).collect(); let titles = |out: egui::FullOutput| -> Vec { let mut t: Vec<_> = out .shapes .iter() .filter_map(|s| match &s.shape { - Shape::Text(t) if t.galley.text().contains(" @ ") => Some(egui::Rect::from_min_size(t.pos, t.galley.size())), + Shape::Text(t) if names.iter().any(|n| t.galley.text().starts_with(n.as_str())) => { + Some(egui::Rect::from_min_size(t.pos, t.galley.size())) + } _ => None, }) .collect(); @@ -875,6 +879,149 @@ fn other_panes_draw_their_guides_and_selected_objects() { assert_ne!(layer, Color32::TRANSPARENT); } +/// The selected objects' outlines as the panes made them on every frame before they kept them, +/// to hold the kept outlines against. +fn outlines_made_each_frame(st: &vectorcraft_engine::DocState, xf: &Xf) -> Vec { + let mut shapes = vec![]; + let symbols = st.doc.symbol_boxes(); + let nodes: Vec<(vectorcraft_doc::NodeId, &vectorcraft_doc::Node)> = + st.selection.objects.iter().filter_map(|id| Some((*id, st.doc.node(*id)?))).collect(); + let color = |id: vectorcraft_doc::NodeId| Stroke::new(1.0, c32(st.doc.layer_color(id))); + let mut stroke_path = |bp: &BezPath, s: Stroke| { + for line in to_screen_path(bp, xf) { + shapes.push(Shape::line(line, s)); + } + }; + if too_many_anchors(nodes.iter().map(|(_, n)| *n)) { + let bounds = nodes.iter().filter_map(|(_, n)| n.geometric_bounds_with(&symbols)).reduce(|a, b| a.union(b)); + if let (Some(b), Some((id, _))) = (bounds, nodes.first()) { + stroke_path(&vectorcraft_geom::shapes::rectangle(b).to_bezpath(), color(*id)); + } + return shapes; + } + for (id, n) in nodes { + stroke_path(&node_outline(n, &symbols), color(id)); + } + shapes +} + +/// The first document's pane in a tiled pair: the outlines it keeps, after checking that they +/// equal the outlines made afresh through its view and that the frame `drawn` holds them in order. +fn kept_outlines<'a>(app: &'a VectorcraftApp, ctx: &egui::Context, drawn: &[Shape]) -> &'a [Shape] { + let pane = panes(app).1[0]; + let xf = Xf::new(view_rects(app, pane, ctx.pixels_per_point()).1, &app.views[0]); + let slot = (app.session.documents()[0].uid, 1); + let kept = &app.canvas.panes.outlines.get(&slot).expect("the pane keeps its outlines").shapes; + assert_eq!(kept, &outlines_made_each_frame(&app.session.documents()[0], &xf), "the kept outlines are the ones made afresh"); + assert!(kept.is_empty() || drawn.windows(kept.len()).any(|w| w == kept.as_slice()), "the pane draws the kept outlines"); + kept +} + +/// Run `cmd` on the first document of a tiled pair, then make the second current again. +fn in_first(app: &mut VectorcraftApp, cmd: &str, args: serde_json::Value) -> serde_json::Value { + app.run("document.activate", json!({"index": 0})).unwrap(); + let out = app.session.execute(cmd, &args).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + out +} + +#[test] +fn kept_outlines_do_not_show_for_a_new_document_that_takes_a_freed_documents_address() { + let affine = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + let st = vectorcraft_engine::DocState::new(vectorcraft_doc::Document::new(400.0, 300.0), None); + let kept = Outlines { revision: st.revision, doc: Arc::downgrade(&st.doc), selection: vec![], affine, shapes: vec![] }; + assert!(kept.shows(&st, &affine), "the outlines show the document they were made for"); + let freed = Arc::as_ptr(&st.doc); + drop(st); + let mut reused = false; + for _ in 0..64 { + let other = vectorcraft_engine::DocState::new(vectorcraft_doc::Document::new(400.0, 300.0), None); + reused |= Arc::as_ptr(&other.doc) == freed; + assert!(!kept.shows(&other, &affine), "a different document with the same revision, selection and mapping is not the one shown"); + } + assert!(!reused, "the weak reference keeps the freed document's address from being taken"); +} + +#[test] +fn other_panes_keep_their_selected_outlines_until_the_document_selection_or_view_changes() { + let mut app = app_with(2); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("window.arrange.tile", json!({})).unwrap(); + let ctx = egui::Context::default(); + let rect = in_first(&mut app, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 80}))["id"].clone(); + let ellipse = in_first(&mut app, "shape.ellipse", json!({"x": 200, "y": 100, "width": 90, "height": 60}))["id"].clone(); + in_first(&mut app, "select.set", json!({"ids": [rect, ellipse]})); + frame(&mut app, &ctx, vec![]); + let drawn = frame(&mut app, &ctx, vec![]); + assert!(kept_outlines(&app, &ctx, &drawn).len() >= 2, "the rectangle and the ellipse are outlined"); + let made = app.canvas.panes.outlines_made; + let drawn = frame(&mut app, &ctx, vec![]); + kept_outlines(&app, &ctx, &drawn); + assert_eq!(app.canvas.panes.outlines_made, made, "an unchanged frame draws the kept outlines"); + let changed = |app: &mut VectorcraftApp, what: &str| { + let made = app.canvas.panes.outlines_made; + let drawn = frame(app, &ctx, vec![]); + kept_outlines(app, &ctx, &drawn); + assert_eq!(app.canvas.panes.outlines_made, made + 1, "{what} makes the outlines again, once"); + let drawn = frame(app, &ctx, vec![]); + kept_outlines(app, &ctx, &drawn); + assert_eq!(app.canvas.panes.outlines_made, made + 1, "the frame after {what} draws the kept outlines"); + }; + in_first(&mut app, "select.set", json!({"ids": [ellipse]})); + changed(&mut app, "a new selection"); + in_first(&mut app, "object.move", json!({"dx": 30, "dy": -10})); + changed(&mut app, "a move"); + let layer = app.session.documents()[0].doc.layers[0].id.0; + in_first(&mut app, "layer.setProps", json!({"id": layer, "color": "#20a040"})); + changed(&mut app, "a new layer color"); + app.views[0].center.x += 25.0; + changed(&mut app, "a pan"); + app.views[0].zoom *= 1.5; + app.views[0].rotation = 20.0; + changed(&mut app, "a zoom and a turn"); + app.ui.view.edges = false; + frame(&mut app, &ctx, vec![]); + assert!(app.canvas.panes.outlines.is_empty(), "with Edges off no outlines are kept"); + app.ui.view.edges = true; + changed(&mut app, "Edges on again"); + in_first(&mut app, "select.none", json!({})); + changed(&mut app, "an empty selection"); + let drawn = frame(&mut app, &ctx, vec![]); + assert!(kept_outlines(&app, &ctx, &drawn).is_empty()); + // 30,000 rectangles have more points than the outlines are made for: the pane keeps the bounds. + let st = &app.session.documents()[0]; + let rect = st.doc.node(vectorcraft_doc::NodeId(rect.as_u64().unwrap())).cloned().unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.session + .edit("Fill", |d, _| { + let layer = d.layers[0].id; + for _ in 0..30_000 { + let mut n = rect.clone(); + n.id = d.alloc_id(); + d.insert(Some(layer), usize::MAX, n)?; + } + Ok(()) + }) + .unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + changed(&mut app, "selecting more points than are outlined"); + let drawn = frame(&mut app, &ctx, vec![]); + assert_eq!(kept_outlines(&app, &ctx, &drawn).len(), 1, "one rectangle around the bounds"); + app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert!(app.canvas.panes.outlines.is_empty(), "Consolidate All Windows forgets the outlines"); + // Panes that stop showing before their render arrives keep no outlines either. + app.run("window.arrange.tile", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(app.canvas.panes.outlines.len(), 1); + app.ui.tiled = false; + app.canvas.panes.shown.clear(); + app.canvas.panes.last.clear(); + frame(&mut app, &ctx, vec![]); + assert!(app.canvas.panes.outlines.is_empty(), "no pane shows, so no outlines are kept"); +} + #[test] fn opening_a_document_while_tiled_fits_each_document_to_its_new_pane() { let mut app = app_with(2); @@ -1209,3 +1356,82 @@ fn tiled_documents_blend_translucent_art_over_their_own_paper_before_display_con assert!(differs(want, blend(s, front_paper)), "the front document's paper blends to another color"); assert!(differs(got, over(plain(s), under)), "the art converted alone shows another color"); } + +fn thread_cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// Time a pane's selected-object outlines with every object of a document selected: 2,000 and +/// 20,000 rectangles, 20,000 ellipses, and 150,000 rectangles (more points than are outlined, so +/// the pane draws their bounds). Each frame is a whole egui pass that draws the outlines and the +/// tessellation of what it drew, made afresh on every frame ([`outlines_made_each_frame`]) or +/// drawn from the kept outlines ([`selected_objects`]). The sides alternate, and the median time +/// per frame of 7 runs is printed. +/// Run with `cargo test --release -p vectorcraft-ui-egui --lib pane_outlines_timing -- --ignored --nocapture`. +#[test] +#[ignore = "manual timing probe; performance depends on machine load"] +fn pane_outlines_timing() { + const FRAMES: u32 = 20; + let clock = if thread_cpu_ns().is_some() { "thread CPU time" } else { "wall-clock time" }; + eprintln!("{clock} per frame, median of 7 runs of {FRAMES} frames"); + for (count, shape) in [(2_000, "shape.rectangle"), (20_000, "shape.rectangle"), (20_000, "shape.ellipse"), (150_000, "shape.rectangle")] { + let mut app = app_with(1); + let id = app.run(shape, json!({"x": 20, "y": 20, "width": 60, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let node = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).cloned().unwrap(); + app.session + .edit("Fill", |d, _| { + let layer = d.layers[0].id; + for _ in 1..count { + let mut n = node.clone(); + n.id = d.alloc_id(); + d.insert(Some(layer), usize::MAX, n)?; + } + Ok(()) + }) + .unwrap(); + app.run("select.all", json!({})).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!(st.selection.objects.len(), count); + let ctx = egui::Context::default(); + let area = egui::Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 800.0)); + let xf = Xf { rect: area, zoom: 4.0, center: Point::new(50.0, 40.0), rot: 0.0 }; + let mut kept = Panes::default(); + let slot = (st.uid, 1); + let mut pass = |fresh: bool| { + let raw = egui::RawInput { screen_rect: Some(area), ..Default::default() }; + let out = ctx.run_ui(raw, |ui| { + let painter = ui.painter_at(area); + if fresh { + for s in outlines_made_each_frame(st, &xf) { + painter.add(s); + } + } else { + selected_objects(&mut kept, slot, st, &painter, &xf); + } + }); + ctx.tessellate(out.shapes, out.pixels_per_point).len() + }; + assert_eq!(pass(true), pass(false), "both sides draw as much"); + let mut time = |fresh: bool| { + let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now()); + for _ in 0..FRAMES { + pass(fresh); + } + let ns = thread_cpu_ns().zip(cpu).map_or_else(|| wall.elapsed().as_nanos(), |(b, a)| b - a); + ns as f64 / f64::from(FRAMES) / 1e6 + }; + let (mut fresh, mut cached) = (vec![], vec![]); + for _ in 0..7 { + fresh.push(time(true)); + cached.push(time(false)); + } + let median = |v: &mut Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + let shapes = kept.outlines.get(&slot).map_or(0, |o| o.shapes.len()); + eprintln!("{count} x {shape} ({shapes} lines drawn)"); + eprintln!(" made every frame: {:>9.3} ms {fresh:.3?}", median(&mut fresh)); + eprintln!(" kept: {:>9.3} ms {cached:.3?}", median(&mut cached)); + } +} diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index cea61e42bb..35c9fd3737 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1165,6 +1165,211 @@ 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"); + } +} + +/// The screen centers and radii of the Artboard tool's add-button tooltips (`tip`) in the view `xf`. +fn add_button_tips(app: &mut VectorcraftApp, xf: &Xf, tip: &str) -> Vec<(Pos2, f32)> { + let view = app.view_info(); + app.session + .overlays(view) + .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() +} + +/// Whether `tip` shows while the pointer rests at `at` for two seconds from `*t`, which moves on. +fn rests_with_tooltip(app: &mut VectorcraftApp, ctx: &egui::Context, t: &mut f64, at: Pos2, tip: &str) -> bool { + texts_at(app, ctx, *t, vec![egui::Event::PointerMoved(at)]); + let mut seen = false; + for _ in 0..20 { + *t += 0.1; + seen |= texts_at(app, ctx, *t, vec![]).iter().any(|s| s == tip); + } + seen +} + +/// While Space lends a view tool, a press on an add button pans the view instead of adding an +/// artboard: the button shows no tooltip until Space is up. +#[test] +fn an_artboard_add_button_has_no_tooltip_while_space_is_held() { + use egui::{Event, Modifiers}; + 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()); + let (at, _) = add_button_tips(&mut app, &xf, tip).into_iter().max_by(|a, b| a.0.y.total_cmp(&b.0.y)).unwrap(); + let space = |pressed| Event::Key { key: egui::Key::Space, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }; + let mut t = 1.0; + texts_at(&mut app, &ctx, t, vec![Event::PointerMoved(at), space(true)]); + for _ in 0..20 { + t += 0.1; + assert!(!texts_at(&mut app, &ctx, t, vec![]).iter().any(|s| s == tip), "no tooltip while Space is held"); + } + t += 0.1; + texts_at(&mut app, &ctx, t, vec![space(false)]); + assert!(rests_with_tooltip(&mut app, &ctx, &mut t, at, tip), "the tooltip shows again once Space is up"); +} + +/// On a narrow artboard with a long name, the name can cover part of the top add button, and a +/// press there selects the named artboard: that part shows no tooltip, and the rest of the button +/// keeps it. +#[test] +fn an_artboard_add_button_has_no_tooltip_where_the_artboard_name_covers_it() { + let tip = vectorcraft_tools::xform::EDGE_BUTTON_TIP; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 20, "height": 100})).unwrap(); + let name = "An artboard name long enough to run past the middle of its top edge"; + app.session.execute("artboard.setProps", &json!({"artboards": [{"index": 0, "name": name}]})).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()); + let (at, r) = add_button_tips(&mut app, &xf, tip).into_iter().min_by(|a, b| a.0.y.total_cmp(&b.0.y)).unwrap(); + // The points of the button's disc, split by whether the canvas's name hit test takes them. + let probe = egui::Context::default(); + let named = |p: Pos2| { + let mut hit = false; + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; + let mut out = probe.run_ui(raw, |ui| hit = super::artboards::artboard_name_at(&app, ui, &xf, p).is_some()); + out.textures_delta.clear(); + hit + }; + let steps = || (-6i8..=6).map(f32::from); + let disc: Vec = steps().flat_map(|dx| steps().map(move |dy| at + vec2(dx, dy))).filter(|p| p.distance(at) <= r - 0.5).collect(); + let covered = disc.iter().copied().find(|p| named(*p)).expect("the name covers part of the button"); + let clear = disc.iter().copied().rev().find(|p| !named(*p)).expect("part of the button is clear of the name"); + let mut t = 1.0; + assert!(!rests_with_tooltip(&mut app, &ctx, &mut t, covered, tip), "no tooltip where the name takes the press"); + assert!(rests_with_tooltip(&mut app, &ctx, &mut t, clear, tip), "the tooltip shows on the rest of the button"); +} + +/// An add button panned under the scroll bars is not drawn and takes no press: none of it shows a +/// tooltip, in the square where the scroll bars meet or over a scroll bar, while the part of a +/// button still on the canvas keeps its tooltip. +#[test] +fn an_artboard_add_button_has_no_tooltip_outside_the_canvas() { + 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 rect = app.canvas_rect.unwrap(); + // Pan the view so the right button's center lands on `to`, and return the button. + let pan_right_button_to = |app: &mut VectorcraftApp, t: f64, to: Pos2| { + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let (at, _) = add_button_tips(app, &xf, tip).into_iter().max_by(|a, b| a.0.x.total_cmp(&b.0.x)).unwrap(); + let d = to - at; + if let Some(v) = app.view_mut() { + v.center = Point::new(v.center.x - f64::from(d.x) / v.zoom, v.center.y - f64::from(d.y) / v.zoom); + v.fitted = true; + } + texts_at(app, &ctx, t, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let (at, r) = add_button_tips(app, &xf, tip).into_iter().max_by(|a, b| a.0.x.total_cmp(&b.0.x)).unwrap(); + assert!(at.distance(to) < 0.5, "the button moved to {to:?}: {at:?}"); + (at, r) + }; + // The middle of the square where the scroll bars meet, right of and below the canvas. + let corner = rect.max + vec2(SCROLL_BAR / 2.0, SCROLL_BAR / 2.0); + let mut t = 1.0; + let (at, _) = pan_right_button_to(&mut app, t, corner); + assert!(!rect.contains(at)); + assert!(!rests_with_tooltip(&mut app, &ctx, &mut t, at, tip), "no tooltip in the corner between the scroll bars"); + // Half on the canvas, half over the vertical scroll bar. + let (at, r) = pan_right_button_to(&mut app, t, pos2(rect.max.x, rect.center().y)); + assert!(!rests_with_tooltip(&mut app, &ctx, &mut t, at + vec2(r - 2.0, 0.0), tip), "no tooltip over the scroll bar"); + assert!(rests_with_tooltip(&mut app, &ctx, &mut t, at - vec2(r - 2.0, 0.0), tip), "the tooltip shows on the part on the canvas"); +} + #[test] fn shift_clicking_canvas_artboard_label_toggles_multi_selection() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -4854,6 +5059,91 @@ fn mirror_axis_drag_uses_canvas_coordinates_in_a_zoomed_rotated_view() { } } +/// The Split view's divider of a selected Image Trace object is drawn where the Selection tool +/// takes it in a zoomed, turned view. Dragging its middle across the image previews the divider, +/// commits one undo step and leaves the traced art where it was; Undo puts the divider back. +#[test] +fn trace_split_divider_drag_in_a_zoomed_rotated_view_is_one_undo_step() { + use vectorcraft_tools::trace_split::TraceDivider; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let data = vectorcraft_format::base64_encode(&crate::tests_sysclip::blue_png()); + app.run("file.place", json!({"name": "blue.png", "dataBase64": data, "link": false, "at": [200, 150]})).unwrap(); + app.run("imageTrace.make", json!({"preset": "Default"})).unwrap(); + app.run("imageTrace.setView", json!({"view": "split"})).unwrap(); + app.select_tool("selection"); + app.ui.task_bar = false; + app.ui.view.rulers = false; + let divider = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + TraceDivider::of(&st.doc, &st.selection, app.view().unwrap().zoom).unwrap() + }; + let initial = divider(&app); + assert_eq!(initial.split, 0.5); + let middle = initial.ends[0].midpoint(initial.ends[1]); + { + let v = app.view_mut().unwrap(); + (v.zoom, v.rotation, v.center, v.fitted) = (30.0, 30.0, middle, true); + } + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let art = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + st.doc.node(initial.id).unwrap().geometric_bounds() + }; + let before = (art(&app), app.session.active().unwrap().history.undo.len()); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + // The divider is drawn between its ends on screen. + let ends = initial.ends.map(|q| xf.to_screen(q)); + let drawn = shapes(&mut app, &ctx); + assert!( + drawn.iter().any(|s| matches!(s, Shape::LineSegment { points, .. } + if points.iter().zip(ends).all(|(a, b)| a.distance(b) < 0.5) || points.iter().rev().zip(ends).all(|(a, b)| a.distance(b) < 0.5))), + "the divider is drawn from {:?} to {:?}", + ends[0], + ends[1] + ); + // A quarter of the image's width to the right, in the image's own direction. + let from = xf.to_screen(middle); + let st = app.session.active().unwrap(); + let NodeKind::Image(im) = &st.doc.node(initial.id).unwrap().children().unwrap()[0].kind else { panic!("no source image") }; + let to = xf.to_screen(im.xf * vectorcraft_geom::Point::new(f64::from(im.width) * 0.75, f64::from(im.height) * 0.5)); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from), button(from, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(to)]); + assert!((divider(&app).split - 0.75).abs() < 0.01, "the divider previews during the drag: {}", divider(&app).split); + frame(&mut app, &ctx, vec![button(to, false)]); + assert!((divider(&app).split - 0.75).abs() < 0.01); + assert_eq!((art(&app), app.session.active().unwrap().history.undo.len()), (before.0, before.1 + 1), "one undo step, the art unmoved"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(divider(&app).split, 0.5); + // Escape during a drag puts the divider back with no undo step. + let steps = app.session.active().unwrap().history.undo.len(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from), button(from, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(to)]); + assert!((divider(&app).split - 0.75).abs() < 0.01); + let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + let raw = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events: vec![escape], ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + crate::shortcuts::handle(&mut app, ui.ctx()); + show(&mut app, ui) + }); + out.textures_delta.clear(); + assert!(!app.session.tool_busy(), "Escape ends the drag"); + assert_eq!(divider(&app).split, 0.5, "Escape puts the divider back"); + frame(&mut app, &ctx, vec![button(to, false)]); + assert_eq!(divider(&app).split, 0.5, "Escape cancels the drag"); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps, "no undo step"); + // With the bounding box hidden, the divider is not drawn. + app.ui.view.bounding_box = false; + let drawn = shapes(&mut app, &ctx); + assert!( + !drawn.iter().any(|s| matches!(s, Shape::LineSegment { points, .. } if points.iter().zip(ends).all(|(a, b)| a.distance(b) < 0.5))), + "no divider with the bounding box hidden" + ); +} + /// A selected grid repeat draws its row handle below the grid and a slider between its first /// two columns (none with the bounding box hidden). Dragging the row handle down two tiles in /// a zoomed view makes five rows without scaling the source, as one undo step, and the slider @@ -6653,6 +6943,117 @@ 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"); +} + +/// Hide Shape Widgets (`view.shapeWidgets`) hides a selected live rectangle's and polygon's corner +/// widgets, a polygon's side widget and an ellipse's pie widgets with the Selection tool and the +/// shape tools, and leaves the bounding box and its eight handles; the Selection tool then shows no +/// corner cursor over a hidden widget. Direct Selection keeps its corner widgets, which follow View › +/// Hide Corner Widget alone. Show Shape Widgets brings them back, neither adds an undo step, and a +/// tool switch keeps the setting. +#[test] +fn hidden_shape_widgets_leave_the_bounding_box() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = |v: serde_json::Value| v["id"].as_u64().unwrap(); + let rect = id(app.session.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 80, "height": 80})).unwrap()); + let polygon = id(app.session.execute("shape.polygon", &json!({"cx": 200, "cy": 150, "radius": 50, "sides": 5})).unwrap()); + let ellipse = id(app.session.execute("shape.ellipse", &json!({"x": 280, "y": 100, "width": 100, "height": 60})).unwrap()); + let ctx = egui::Context::default(); + let side = 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) - side).abs() < 0.01 && (span(|p| p.y) - side).abs() < 0.01 + }; + // The selection's corner, pie and side widgets drawn, and the bounding box's handles. + let drawn = |app: &mut VectorcraftApp, id: u64| { + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + let (_, handles) = bounding_box_drawn(app, &ctx); + let all = shapes(app, &ctx); + let circles = |r: f32| all.iter().filter(|s| matches!(s, Shape::Circle(c) if c.radius == r && c.fill == Color32::WHITE)).count(); + let diamonds = all.iter().filter(|s| matches!(s, Shape::Path(ps) if diamond(ps))).count(); + (circles(3.0), circles(vectorcraft_tools::pie::RADIUS_PX), diamonds, handles) + }; + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + for tool in ["selection", "polygon", "rectangle"] { + app.select_tool(tool); + assert_eq!(drawn(&mut app, rect), (4, 0, 0, 8), "{tool}"); + assert_eq!(drawn(&mut app, polygon), (5, 0, 1, 8), "{tool}"); + assert_eq!(drawn(&mut app, ellipse), (0, 2, 0, 8), "{tool}"); + let before = steps(&app); + assert_eq!(app.run("view.shapeWidgets", json!({})).unwrap(), json!(false)); + assert_eq!(steps(&app), before, "{tool}: the setting adds no undo step"); + assert_eq!(drawn(&mut app, rect), (0, 0, 0, 8), "{tool}"); + assert_eq!(drawn(&mut app, polygon), (0, 0, 0, 8), "{tool}"); + assert_eq!(drawn(&mut app, ellipse), (0, 0, 0, 8), "{tool}"); + assert_eq!(app.run("view.shapeWidgets", json!({})).unwrap(), json!(true)); + } + // Direct Selection: the corner widgets stay until View › Hide Corner Widget. + app.run("view.shapeWidgets", json!({"on": false})).unwrap(); + app.select_tool("directSelection"); + assert_eq!(drawn(&mut app, rect).0, 4); + app.run("view.cornerWidget", json!({})).unwrap(); + assert_eq!(drawn(&mut app, rect).0, 0); + app.run("view.cornerWidget", json!({})).unwrap(); + // The Selection tool shows no corner cursor over a hidden widget, and the tool switches kept the + // setting. + app.select_tool("selection"); + assert!(!app.ui.view.shape_widgets); + drawn(&mut app, rect); + let at = { + let st = app.session.active().unwrap(); + vectorcraft_tools::corners::CornerWidgets::of(&st.doc, &st.selection, app.view_info().zoom, false).unwrap().visible().next().unwrap() + }; + let view = app.view_info(); + assert_ne!(app.session.cursor(at, Mods::default(), view), Cursor::CornerRadius); + app.run("view.shapeWidgets", json!({"on": true})).unwrap(); + let view = app.view_info(); + assert_eq!(app.session.cursor(at, Mods::default(), view), Cursor::CornerRadius); +} + /// A selected Objects on Path group shows its Rotate All widget with the Selection and Objects on /// Path tools. #[test] @@ -8889,6 +9290,11 @@ fn retype_all_of_a_copied_type(ime: bool) { frame(&mut app, vec![button(at, pressed, Modifiers::NONE)]); } frame(&mut app, vec![]); + // Without Georgia on this computer, the Type tool asks first; OK starts the edit. + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == crate::dialogs::confirm::MISSING_FONT_EDIT) { + crate::dialogs::confirm(&mut app).unwrap(); + frame(&mut app, vec![]); + } assert_eq!(app.session.tool_options()["editing"], json!(copy)); // 3. Select all of its text and type over it. frame(&mut app, vec![key(Key::A, true, Modifiers::COMMAND)]); @@ -8976,6 +9382,90 @@ 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")); +} + +/// A Type tool press that reaches type in a missing font while another dialog is open (as one sent +/// with `ui.pointer` does) leaves that dialog open and starts no edit. +#[test] +fn a_press_on_type_in_a_missing_font_keeps_an_open_dialog() { + 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 8408"}); + let id = app.session.execute("text.create", ¶ms).unwrap()["id"].as_u64().unwrap(); + app.session.execute("select.none", &json!({})).unwrap(); + app.select_tool("type"); + let doc = app.session.active().unwrap().uid; + crate::dialogs::confirm::ask_replace_files(&mut app, doc, &["/tmp/a.svg".to_string()], &[], "file.export", json!({})); + let b = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().geometric_bounds().unwrap(); + let view = app.view_info(); + for kind in [PointerKind::Down, PointerKind::Up] { + crate::canvas::dispatch(&mut app, &PointerEvent::new(kind, b.center().x, b.center().y), view); + } + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(crate::dialogs::confirm::REPLACE_FILES)); + crate::dialogs::cancel(&mut app); + let r = app.session.tool_poll(view, false); + crate::canvas::apply_requests(&mut app, r); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.tool_options()["editing"], json!(null)); +} + #[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()); @@ -10795,8 +11285,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() }); } @@ -10821,7 +11311,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() }); } @@ -10847,7 +11337,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() }); } @@ -11292,6 +11782,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] @@ -11326,7 +11856,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 @@ -11357,7 +11887,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() }) }; @@ -11400,8 +11930,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)); @@ -12893,6 +13426,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] @@ -12943,6 +13638,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/tests_edge_scroll.rs b/crates/ui-egui/src/canvas/tests_edge_scroll.rs new file mode 100644 index 0000000000..977914d559 --- /dev/null +++ b/crates/ui-egui/src/canvas/tests_edge_scroll.rs @@ -0,0 +1,267 @@ +//! A tool drag held near an edge of the canvas scrolls the view so the drag can go on past what +//! shows (#8551): a Selection tool move carries the art along, a drawing tool's shape grows, and +//! the view stops once the pointer leaves the edge. A click near the edge scrolls nothing. + +use super::view::{EDGE_SCROLL_SPEED, EDGE_SCROLL_ZONE, edge_scroll, edge_scroll_pixels}; +use super::*; +use vectorcraft_engine::Session; + +/// One headless canvas frame on an 800 × 600 window. +fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) { + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); +} + +fn button(pos: Pos2, pressed: bool) -> egui::Event { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() } +} + +/// A 400 × 300 document with a 100 pt square at (50, 50), zoomed in to 4× about the square's +/// centre, with `tool` selected; the frame drawn once. +fn zoomed_in(tool: &str) -> (VectorcraftApp, egui::Context, vectorcraft_doc::NodeId) { + 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": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.select_tool(tool); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let v = app.view_mut().unwrap(); + v.zoom = 4.0; + v.center = Point::new(100.0, 100.0); + frame(&mut app, &ctx, vec![]); + (app, ctx, vectorcraft_doc::NodeId(id)) +} + +fn center(app: &VectorcraftApp) -> Point { + app.view().unwrap().center +} + +#[test] +fn edge_scroll_moves_the_content_away_from_the_edge_the_pointer_is_near() { + let r = egui::Rect::from_min_size(pos2(100.0, 50.0), vec2(600.0, 400.0)); + let dt = 0.1; + let full = EDGE_SCROLL_SPEED * dt; + // Away from the edges, or off the canvas, nothing. + assert_eq!(edge_scroll(r, r.center(), dt), None); + assert_eq!(edge_scroll(r, pos2(r.right() + 5.0, r.center().y), dt), None, "over a panel"); + assert_eq!(edge_scroll(r, pos2(r.right() - EDGE_SCROLL_ZONE, r.center().y), dt), None, "at the zone's inner side"); + assert_eq!(edge_scroll(r, pos2(r.right() - 1.0, r.center().y), 0.0), None, "no time passed"); + assert_eq!(edge_scroll(r, pos2(f32::NAN, r.center().y), dt), None); + // At the right edge the content moves left at full speed; half way into the zone, at half. + let right = edge_scroll(r, pos2(r.right(), r.center().y), dt).unwrap(); + assert!((right.x + full).abs() < 1e-3 && right.y == 0.0, "{right:?}"); + let half = edge_scroll(r, pos2(r.right() - EDGE_SCROLL_ZONE / 2.0, r.center().y), dt).unwrap(); + assert!((half.x + full / 2.0).abs() < 1e-3, "{half:?}"); + // Near the left and top edges it moves right and down; in a corner, both ways. + assert!(edge_scroll(r, pos2(r.left() + 1.0, r.center().y), dt).unwrap().x > 0.0); + let corner = edge_scroll(r, pos2(r.left() + 1.0, r.top() + 1.0), dt).unwrap(); + assert!(corner.x > 0.0 && corner.y > 0.0, "{corner:?}"); + // In a corner both ways, but no faster than at one edge. + let corner = edge_scroll(r, pos2(r.right() - 1.0, r.bottom() - 1.0), dt).unwrap(); + assert!(corner.x < 0.0 && corner.y < 0.0 && corner.length() <= full + 1e-3, "{corner:?}"); + assert!(edge_scroll(r, pos2(r.center().x, r.bottom() - 1.0), dt).unwrap().y < 0.0); + // A stalled frame scrolls a tenth of a second's worth at most. + assert_eq!(edge_scroll(r, pos2(r.right(), r.center().y), 5.0), Some(right)); +} + +/// The view moves by whole device pixels, keeping the rest for the press's next scroll; an axis +/// the scroll does not move keeps its remainder untouched rather than rounding it each frame. +#[test] +fn edge_scroll_pixels_keep_the_remainder_of_an_axis_that_does_not_scroll() { + // 10.5 pixels: 11 now (rounded away from zero), half a pixel back owed. + let (d, rest) = edge_scroll_pixels((0.0, 0.0), vec2(-10.5, 0.0), 1.0); + assert_eq!(d, (-11.0, 0.0)); + assert_eq!(rest, (0.5, 0.0)); + // Along the top edge only: x keeps its half pixel, frame after frame, and does not move. + let mut rest = rest; + for _ in 0..4 { + let (d, r) = edge_scroll_pixels(rest, vec2(0.0, 7.0), 1.0); + assert_eq!(d, (0.0, 7.0)); + assert_eq!(r.0, 0.5, "x keeps its remainder"); + rest = r; + } + // Scrolling that way again, it counts: 0.5 + 1.5 = 2 pixels. + assert_eq!(edge_scroll_pixels(rest, vec2(1.5, 0.0), 1.0).0, (2.0, 0.0)); + // At 2 device pixels a point. + assert_eq!(edge_scroll_pixels((0.0, 0.0), vec2(0.25, -1.0), 2.0), ((1.0, -2.0), (-0.5, 0.0))); +} + +/// The issue's case: zoomed in, a selected object dragged towards the panels on the right reaches +/// the canvas's edge. Held there, the view scrolls right and the object goes on with the pointer; +/// back away from the edge, the view stops. +#[test] +fn a_move_held_near_the_right_edge_scrolls_the_view_and_carries_the_art() { + let (mut app, ctx, id) = zoomed_in("selection"); + let rect = app.canvas_rect.unwrap(); + let xf = Xf::new(rect, app.view().unwrap()); + let left = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap().x0; + let start = xf.to_screen(Point::new(100.0, 100.0)); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start), button(start, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start + vec2(20.0, 0.0))]); + let edge = pos2(rect.right() - 4.0, start.y); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(edge)]); + let (c0, x0) = (center(&app), left(&app)); + // Held still at the edge, frame after frame the view scrolls right and the art keeps up. + let mut last = (c0, x0); + for _ in 0..5 { + frame(&mut app, &ctx, vec![]); + let now = (center(&app), left(&app)); + assert!(now.0.x > last.0.x, "the view scrolls right: {:?} then {:?}", last.0, now.0); + assert!((now.0.y - c0.y).abs() < 1e-9, "and only right"); + assert!(now.1 > last.1, "the art moves with the pointer: {} then {}", last.1, now.1); + last = now; + } + // The art stays under the pointer: it moved as far as the view (give or take the move's + // rounding to the pixel grid). + assert!(((last.1 - x0) - (last.0.x - c0.x)).abs() < 1.0, "art {} view {}", last.1 - x0, last.0.x - c0.x); + assert!(app.session.active().unwrap().interaction.is_some(), "still the same move"); + // Back away from the edge the view stops. + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(rect.center())]); + let stopped = center(&app); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + assert_eq!(center(&app), stopped, "the view stops away from the edge"); + // The release ends the move where the art is. + let moved = left(&app); + frame(&mut app, &ctx, vec![button(rect.center(), false)]); + let st = app.session.active().unwrap(); + assert!(st.interaction.is_none()); + assert!((left(&app) - moved).abs() < 1e-6); + assert!(moved > 50.0 + (last.0.x - c0.x), "the art went past where the edge showed at first"); +} + +/// A drawing tool's drag scrolls too: a rectangle dragged to the bottom edge goes on growing. +#[test] +fn a_rectangle_drag_held_near_the_bottom_edge_keeps_growing() { + let (mut app, ctx, _) = zoomed_in("rectangle"); + let rect = app.canvas_rect.unwrap(); + // Away from the selected square's centre point, where a press moves the square (#5477). + let start = rect.center() - vec2(150.0, 100.0); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start), button(start, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start + vec2(10.0, 10.0))]); + let edge = pos2(start.x + 10.0, rect.bottom() - 2.0); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(edge)]); + let c0 = center(&app); + // The bottom of the rectangle drawn so far: the preview in the document. + let preview_bottom = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + let mut bottom = f64::MIN; + st.doc.walk(|n| { + if let Some(b) = n.geometric_bounds() { + bottom = bottom.max(b.y1); + } + }); + bottom + }; + for _ in 0..4 { + frame(&mut app, &ctx, vec![]); + // Each held frame the preview reaches the pointer in the view as it is now. + let now = Xf::new(rect, app.view().unwrap()).to_doc(edge).y; + assert!((preview_bottom(&app) - now).abs() < 0.5, "the preview follows the pointer: {} vs {now}", preview_bottom(&app)); + } + let c1 = center(&app); + assert!(c1.y > c0.y && (c1.x - c0.x).abs() < 1e-9, "the view scrolls down: {c0:?} then {c1:?}"); + let xf = Xf::new(rect, app.view().unwrap()); + let bottom = xf.to_doc(edge).y; + frame(&mut app, &ctx, vec![button(edge, false)]); + let st = app.session.active().unwrap(); + let made = st.selection.objects.first().and_then(|id| st.doc.node(*id)).and_then(|n| n.geometric_bounds()).unwrap(); + assert!((made.y1 - bottom).abs() < 0.5, "the rectangle reaches the pointer in the scrolled view: {} vs {bottom}", made.y1); +} + +/// A press near the edge that has not dragged is a click: the view stays. +#[test] +fn a_press_held_still_near_the_edge_does_not_scroll() { + let (mut app, ctx, _) = zoomed_in("selection"); + let rect = app.canvas_rect.unwrap(); + let at = pos2(rect.right() - 4.0, rect.center().y); + let c0 = center(&app); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), button(at, true)]); + for _ in 0..4 { + frame(&mut app, &ctx, vec![]); + } + assert_eq!(center(&app), c0); + frame(&mut app, &ctx, vec![button(at, false)]); + assert_eq!(center(&app), c0); +} + +/// The Hand tool's own drag is not a tool drag: held near the edge it pans with the pointer only. +#[test] +fn a_hand_drag_held_near_the_edge_does_not_scroll_on() { + let (mut app, ctx, _) = zoomed_in("hand"); + let rect = app.canvas_rect.unwrap(); + let start = rect.center(); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start), button(start, true)]); + let edge = pos2(rect.right() - 4.0, start.y); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(edge)]); + let c0 = center(&app); + for _ in 0..3 { + frame(&mut app, &ctx, vec![]); + } + assert_eq!(center(&app), c0); + frame(&mut app, &ctx, vec![button(edge, false)]); +} + +/// A press held still near the edge while the wheel scrolls the view is not a drag: the pointer +/// has not moved on screen, so the view does not go on scrolling after the wheel stops. +#[test] +fn a_wheel_scroll_under_a_still_press_near_the_edge_does_not_start_edge_scrolling() { + let (mut app, ctx, _) = zoomed_in("selection"); + let rect = app.canvas_rect.unwrap(); + let at = pos2(rect.right() - 4.0, rect.center().y); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), button(at, true)]); + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, 40.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }; + let c0 = center(&app); + frame(&mut app, &ctx, vec![wheel]); + let wheeled = center(&app); + assert_ne!(wheeled, c0, "the wheel scrolls the view"); + for _ in 0..4 { + frame(&mut app, &ctx, vec![]); + } + // The wheel's own scroll eases out along y over these frames; the right edge would scroll x. + assert_eq!(center(&app).x, wheeled.x, "no edge scrolling"); + frame(&mut app, &ctx, vec![button(at, false)]); +} + +/// The press is where the button went down, not where the frame's input left the pointer: a press +/// well inside the canvas and a move to the edge in the same input batch has dragged, so holding +/// the pointer still there scrolls. +#[test] +fn a_press_and_a_move_to_the_edge_in_one_frame_scroll_once_held() { + let (mut app, ctx, _) = zoomed_in("selection"); + let rect = app.canvas_rect.unwrap(); + let start = pos2(rect.center().x, rect.bottom() - 30.0); + let edge = pos2(start.x, rect.bottom() - 4.0); + let c0 = center(&app); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start), button(start, true), egui::Event::PointerMoved(edge)]); + for _ in 0..3 { + frame(&mut app, &ctx, vec![]); + } + assert!(center(&app).y > c0.y, "the view scrolls down: {:?} vs {c0:?}", center(&app)); + frame(&mut app, &ctx, vec![button(edge, false)]); +} + +/// A move away from the press and back within one frame still dragged: the press held near the +/// edge then scrolls, though the pointer ends the frame where it was pressed. +#[test] +fn a_move_away_and_back_within_a_frame_still_arms_edge_scrolling() { + let (mut app, ctx, _) = zoomed_in("selection"); + let rect = app.canvas_rect.unwrap(); + let at = pos2(rect.right() - 4.0, rect.center().y); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), button(at, true)]); + let c0 = center(&app); + let away = at - vec2(8.0, 0.0); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(away), egui::Event::PointerMoved(at + vec2(-0.5, 0.0))]); + for _ in 0..3 { + frame(&mut app, &ctx, vec![]); + } + assert!(center(&app).x > c0.x, "the view scrolls right: {:?} vs {c0:?}", center(&app)); + frame(&mut app, &ctx, vec![button(at, false)]); +} diff --git a/crates/ui-egui/src/canvas/tool_overlays.rs b/crates/ui-egui/src/canvas/tool_overlays.rs index 5ccf5e4b9a..958872d6b0 100644 --- a/crates/ui-egui/src/canvas/tool_overlays.rs +++ b/crates/ui-egui/src/canvas/tool_overlays.rs @@ -446,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]); @@ -637,6 +661,35 @@ pub(super) fn mirror_axis_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: & p.rect_stroke(handle, 2.0, Stroke::new(2.0, t.measure_bg), StrokeKind::Outside); } +/// The Split view's divider of the selected Image Trace object, where the Selection tool's hit +/// testing finds it: a line across the source image with a grip in its middle, at its place in the +/// zoomed, scrolled or turned view. Hidden with the bounding box and in Outline mode, as the hit +/// testing is. +pub(super) fn trace_split_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) { + if app.session.tool_id() != "selection" || !app.ui.view.bounding_box || app.outline_view() { + return; + } + let Some(st) = app.session.active() else { return }; + let Some(d) = vectorcraft_tools::trace_split::TraceDivider::of(&st.doc, &st.selection, xf.zoom) else { return }; + let ends = d.ends.map(|q| xf.to_screen(q)); + if !ends.iter().all(|q| q.is_finite()) { + return; + } + let t = Tokens::get(p.ctx()); + if let Some((a, b)) = clip_segment(ends[0], ends[1], xf.rect) { + p.line_segment([a, b], Stroke::new(4.0, t.measure_bg)); + p.line_segment([a, b], Stroke::new(1.5, t.selection)); + } + let along = ends[1] - ends[0]; + let length = along.length(); + if length > 1.0 { + let mid = ends[0] + along * 0.5; + let half = along / length * vectorcraft_tools::trace_split::GRIP_HALF.min(length * 0.5); + p.line_segment([mid - half, mid + half], Stroke::new(7.0, t.measure_bg)); + p.line_segment([mid - half, mid + half], Stroke::new(4.0, t.selection)); + } +} + /// A selected grid repeat's row, column and corner handles and its spacing sliders (#2691), at /// the places the Selection tool's hit testing finds them. pub(super) fn grid_repeat_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf) { diff --git a/crates/ui-egui/src/canvas/view.rs b/crates/ui-egui/src/canvas/view.rs index e0e5cc9f75..b2669b128d 100644 --- a/crates/ui-egui/src/canvas/view.rs +++ b/crates/ui-egui/src/canvas/view.rs @@ -125,6 +125,67 @@ pub(super) fn rotate_about(vm: &mut View, rect: egui::Rect, p: Pos2, degrees: f6 vm.center += before - Xf::at(rect, vm, ui_zoom).to_doc(p); } +/// How far in from each edge of the canvas a held tool drag scrolls the view ([`edge_scroll`]), in +/// screen points. +pub(super) const EDGE_SCROLL_ZONE: f32 = 24.0; + +/// How fast the view scrolls with the pointer at the canvas's very edge ([`edge_scroll`]), in +/// screen points a second. Nearer the inner side of the zone it scrolls slower. +pub(super) const EDGE_SCROLL_SPEED: f32 = 900.0; + +/// How far a tool drag held at `p` near an edge of the canvas `rect` scrolls the view in `dt` +/// seconds (#8551), as the screen points the content moves: away from that edge, so what lies +/// past it comes into view, faster the nearer the pointer is to the edge. `None` with the pointer +/// outside the canvas or away from its edges, or with no time passed. A stalled frame counts a +/// tenth of a second at most, and in a corner the content moves no faster than near one edge. +pub(super) fn edge_scroll(rect: egui::Rect, p: Pos2, dt: f32) -> Option { + if !rect.contains(p) || !p.x.is_finite() || !p.y.is_finite() || !dt.is_finite() || dt <= 0.0 { + return None; + } + // On a canvas narrower than two zones, each zone reaches the middle at most. + let zone_x = EDGE_SCROLL_ZONE.min(rect.width() / 2.0); + let zone_y = EDGE_SCROLL_ZONE.min(rect.height() / 2.0); + // How deep into a zone the pointer is (0 at its inner side, 1 at the edge), signed by the way + // the content moves: near the left or top edge it moves right or down. + let depth = |near: f32, far: f32, zone: f32| { + if zone <= 0.0 { + 0.0 + } else if near < zone { + 1.0 - near / zone + } else if far < zone { + far / zone - 1.0 + } else { + 0.0 + } + }; + let dx = depth(p.x - rect.left(), rect.right() - p.x, zone_x); + let dy = depth(p.y - rect.top(), rect.bottom() - p.y, zone_y); + if dx == 0.0 && dy == 0.0 { + return None; + } + // In a corner the scroll goes both ways, no faster than along one edge. + let v = egui::vec2(dx, dy); + let v = if v.length() > 1.0 { v / v.length() } else { v }; + Some(v * (EDGE_SCROLL_SPEED * dt.min(0.1))) +} + +/// An edge scroll of `by` screen points ([`edge_scroll`]) at `ppp` device pixels a point, after the +/// scrolls of the same press left `rest` device pixels along each axis: the whole device pixels to +/// move the content by, and what is left. An axis this scroll does not move keeps its remainder as +/// it is: rounding a half pixel there would move the view one pixel back and forth each frame. +pub(super) fn edge_scroll_pixels(rest: (f64, f64), by: egui::Vec2, ppp: f32) -> ((f64, f64), (f64, f64)) { + let step = |rest: f64, by: f32| { + if by == 0.0 { + return (0.0, rest); + } + let total = rest + f64::from(by) * f64::from(ppp); + let whole = total.round(); + (whole, total - whole) + }; + let ((dx, rx), (dy, ry)) = (step(rest.0, by.x), step(rest.1, by.y)); + ((dx, dy), (rx, ry)) +} + /// Move view `vm`'s content by `(dx, dy)` device pixels along the screen's axes, at `ppp` device /// pixels a point of an interface zoomed by `ui_zoom`: the canvas's frame moves by exactly those /// pixels. diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 43b9f5b69c..261534e643 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -27,12 +27,13 @@ use control_bar::{CONTROL_BAR_FLOAT_AT, ISOLATION_BUTTON}; pub(crate) use control_bar::{Fit, group_separator, left_out, link_reserve}; #[cfg(test)] use hints::hint_segments; +pub(crate) use hints::tool_hint; pub use hints::{hint_bar, hint_strings}; pub use status_bar::{StatusBarShow, deserialize_status_bar_show, set_status_bar_show, status_bar}; #[cfg(test)] use status_bar::{StatusReadoutWidths, color_profile_name, date_time_label, status_readouts}; #[cfg(test)] -use tabs::{CLOSE_BEFORE_TITLE, first_tab_shown, tab_drop, tab_groups, tab_title}; +use tabs::{CLOSE_BEFORE_TITLE, first_tab_shown, leading_tab, shortened_title, tab_drop, tab_groups, tab_room, tab_title}; pub use tabs::{doc_tabs, isolation_bar, step_document}; pub(crate) use tabs::{document_window_title, show_document, window_tab}; diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 2c7ae8ed20..ab5c9b121c 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"; @@ -997,26 +1039,26 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, snapping_menu(app, ui); } let Some(st) = app.session.active() else { return }; - let sel = st.selection.objects.clone(); + let count = st.selection.objects.len(); let units = app.session.general_unit(); - let first = sel.first().and_then(|id| st.doc.node(*id)); + let first = st.selection.objects.first().and_then(|id| st.doc.node(*id)); let anchors = anchor_controls(app); let label = match first { _ if app.session.tool_id() == "artboard" => tl!("Artboard"), - Some(_) if sel.len() == 1 && anchors != AnchorControls::None => { + Some(_) if count == 1 && anchors != AnchorControls::None => { tl!("Anchor Point") } - Some(vectorcraft_doc::Node { kind: NodeKind::Image(im), .. }) if sel.len() == 1 => { + Some(vectorcraft_doc::Node { kind: NodeKind::Image(im), .. }) if count == 1 => { if im.link.is_some() { tl!("Linked File") } else { tl!("Embedded") } } - Some(n) if sel.len() == 1 && crate::panels::image_trace::is_trace(n) => { + Some(n) if count == 1 && crate::panels::image_trace::is_trace(n) => { tl!("Image Tracing") } - _ => tl!(crate::panels::appearance::object_label(app)), + _ => tl!(crate::panels::appearance::summary(app, ui.ctx()).map_or("No Selection", |s| s.label)), }; let has_first = first.is_some(); let label = egui::RichText::new(label).font(theme::semibold(12.0)).color(t.text); @@ -1035,6 +1077,8 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, } if anchors != AnchorControls::None && group_on(app, "anchors") { anchor_buttons(app, ui, anchors); + let reserve = transform_reserve(app, ui, count > 0); + corner_radius(app, ui, t, reserve); } let object_options = group_on(app, "objectOptions"); if object_options { @@ -1043,7 +1087,7 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, if ui.available_width() >= 6.0 { ui.add_space(6.0); } - let reserve = transform_reserve(app, ui, !sel.is_empty()); + let reserve = transform_reserve(app, ui, count > 0); // An image or an Image Trace object shows its own controls in place of Fill and Stroke, // and leaves Fill and Stroke out while the Image Options group is off too. These groups, // the tool options, the envelope's and the symbol instances' each show a control only while @@ -1064,11 +1108,11 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, if !image && group_on(app, "fillStroke") { fill_and_stroke(app, ui, reserve); } - opacity_and_style(app, ui, t, opacity, !sel.is_empty(), reserve); + opacity_and_style(app, ui, t, opacity, count > 0, reserve); // The Character group shows whole, with the Transform link's room left after it, or not at // all; left out, it leaves out the groups between it and the link too. let room = !group_on(app, "character") || crate::panels::character::control_bar(app, ui, reserve); - if !groups_before_transform(app, ui, sel.len(), room) { + if !groups_before_transform(app, ui, count, room) { // With the Transform group off, its link and X/Y/W/H fields take no room. trailing_select_similar(app, ui); erase_trailing(ui); diff --git a/crates/ui-egui/src/chrome/hints.rs b/crates/ui-egui/src/chrome/hints.rs index 02f34438a6..2c679c72a1 100644 --- a/crates/ui-egui/src/chrome/hints.rs +++ b/crates/ui-egui/src/chrome/hints.rs @@ -206,6 +206,17 @@ pub(super) fn hint_segments(tool: &str) -> Vec<(Cow<'static, str>, bool)> { &search } }; + shown_segments(segments) +} + +/// The hint bar's segments for `tool` as [`hint_segments`] shows them, the Zoom tool's for animated +/// zoom when `animated_zoom` is on; none for a tool without a hint of its own. +pub(crate) fn tool_hint(tool: &str, animated_zoom: bool) -> Option, bool)>> { + let tool = if tool == "zoom" && animated_zoom { ANIMATED_ZOOM_HINT } else { tool }; + hint_for(tool).map(shown_segments) +} + +fn shown_segments(segments: &[(&'static str, bool)]) -> Vec<(Cow<'static, str>, bool)> { segments .iter() .map(|&(text, bold)| { diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 45cd600771..57b1b2a457 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -277,7 +277,7 @@ pub(super) fn clipped_label(ui: &mut Ui, text: impl Into) -> e } /// Show `text` on hover in a tooltip that wraps to fit inside the window. -fn full_text_tooltip(response: egui::Response, text: impl Into) -> egui::Response { +pub(super) fn full_text_tooltip(response: egui::Response, text: impl Into) -> egui::Response { let text = text.into(); response.on_hover_ui(|ui| { let margins = ui.spacing().menu_margin.sum().x + 2.0 * ui.spacing().item_spacing.x; @@ -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 f88372e75b..b92d1e5d04 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -16,8 +16,14 @@ fn view_tab_title(d: &vectorcraft_engine::DocState, number: Option, zoom: f let color = if d.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk { "CMYK" } else { "RGB" }; format!("{color}/{}", if outline { tl!("Outline") } else { tl!("Preview") }) }; + format!("{} @ {} ({mode})", view_tab_name(d, number), zoom_label(zoom, display_print_size).replace('%', " %")) +} + +/// The start of [`view_tab_title`], which an inactive document tab shows alone (#8582): "Name*", +/// or for a view of a document with more than one view, "Name:2*". +fn view_tab_name(d: &vectorcraft_engine::DocState, number: Option) -> String { let number = number.map(|n| format!(":{n}")).unwrap_or_default(); - format!("{}{number}{} @ {} ({mode})", d.title(), if d.is_dirty() { "*" } else { "" }, zoom_label(zoom, display_print_size).replace('%', " %")) + format!("{}{number}{}", d.title(), if d.is_dirty() { "*" } else { "" }) } /// The title of window `w`, a view of document `d`: with the view's zoom and Outline or Preview, @@ -128,9 +134,63 @@ pub(super) fn first_tab_shown(widths: &[f32], active: Option, room: f32) first } -/// Document tab strip: "Name* @ 66.67% (RGB/Preview)". User Interface › Large Tabs makes the tabs -/// taller, with larger titles. Tabs that don't fit are reached from a » button at the strip's -/// right end, which lists every open document, and the active tab is always in view (#746). +/// When the tabs `widths` wide from `first` to the last one leave at least `least` of `room` before +/// the » button, the tab before `first` fills that room with its title shortened (#8584). → the +/// first tab the strip shows and, when it is that tab, the width it gets. +pub(super) fn leading_tab(widths: &[f32], first: usize, room: f32, least: f32) -> (usize, Option) { + let rest: f32 = widths.get(first..).map_or(0.0, |w| w.iter().sum()); + if first > 0 && room - rest >= least { (first - 1, Some(room - rest)) } else { (first, None) } +} + +/// The room a tab `w` wide has: `left` of the strip, or with a leading tab `lead` wide +/// ([`leading_tab`]), `lead` for it (`leading`) and its whole width for each tab after it. +pub(super) fn tab_room(lead: Option, leading: bool, w: f32, left: f32) -> f32 { + match lead { + Some(l) if leading => l, + Some(_) => w, + None => left, + } +} + +/// `title` in one line at most `max_width` wide, ending in "…" when it is cut short, and whether +/// it fits in `max_width`. egui rounds a wrap width to the nearest point, so the width is rounded +/// down first. +pub(super) fn shortened_title( + ctx: &egui::Context, + title: &str, + font: egui::FontId, + color: egui::Color32, + max_width: f32, +) -> (std::sync::Arc, bool) { + let max_width = max_width.max(0.0); + let mut job = egui::text::LayoutJob::simple_singleline(title.to_owned(), font, color); + job.wrap = egui::text::TextWrapping { max_width: max_width.floor(), max_rows: 1, break_anywhere: true, overflow_character: Some('…') }; + let galley = ctx.fonts_mut(|f| f.layout_job(job)); + let fits = galley.size().x <= max_width; + (galley, fits) +} + +/// The × of a document tab `w` wide, drawn in `xr` and clicked within 3 pt of it, or `None` for a +/// tab shortened narrower than the × and its click area. +fn tab_close_box(ui: &Ui, t: &Tokens, xr: egui::Rect, w: f32, id: egui::Id) -> Option { + /// The least width of a tab that holds its × and the ×'s click area. + const CLOSE_ROOM: f32 = 25.0; + if w < CLOSE_ROOM { + return None; + } + let xresp = ui.interact(xr.expand(3.0), id, Sense::click()); + icons::paint(ui, "x", xr, if xresp.hovered() { t.text_strong } else { t.text }); + Some(xresp) +} + +/// Document tab strip: the active tab's title is "Name* @ 66.67 % (RGB/Preview)", and each other +/// tab shows "Name*" alone, with the whole title in its tooltip (#8582). User Interface › Large +/// Tabs makes the tabs taller, with larger titles. Tabs that don't fit are reached from a » button +/// at the strip's right end, which lists every open document, and the active tab is always in view +/// (#746). The first tab that doesn't fit whole fills the room left before the » button with its +/// title shortened, when that room holds some of the title (#8584). When the active tab is among +/// the last ones and the tabs from it to the end leave room, the tab before them fills that room +/// instead. An active tab wider than the whole strip is shortened to it. /// Each view Window › New Window opened has a tab of its own. Windows floating have no tab /// ([`crate::doc_windows`]); while the current window is a floating one, the tab of the window the /// strip shows is the highlighted one. A tab dragged more than [`crate::doc_windows::TEAR_OFF`] @@ -140,6 +200,10 @@ pub(super) fn first_tab_shown(widths: &[f32], active: Option, room: f32) pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { /// The width of the » button. const MORE: f32 = 30.0; + /// A tab's width beyond its title's: the margins and the ×. + const TAB_PADDING: f32 = 50.0; + /// The least width of title a tab shortened to fit the strip shows. + const MIN_TITLE: f32 = 40.0; let t = Tokens::get(ui.ctx()); let (height, title_size) = tab_size(app); let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover()); @@ -148,22 +212,28 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { ui.painter().line_segment([strip.left_bottom(), strip.right_bottom()], Stroke::new(1.0, t.border)); // On the Home screen no tab is the current one. let shown = crate::doc_windows::tab_window(app).filter(|_| app.ui.home.is_none()); - // The windows under the tabs; `active` is the position of the highlighted one. - let docked = crate::doc_windows::docked_windows(app); - let active = docked.iter().position(|w| Some(*w) == shown); - let tabs: Vec<(String, std::sync::Arc)> = docked - .iter() - .filter_map(|w| Some((*w, app.session.documents().get(w.0)?))) + // The windows under the tabs, with the text each tab shows, its whole title and the text laid + // out; `active` is the position of the highlighted one. An inactive tab shows the name alone, + // without the zoom and the mode in parentheses (color mode and view, or the opacity mask being + // edited) (#8582), and its tooltip shows the whole title. + type Tab = (crate::doc_windows::Win, String, String, std::sync::Arc); + let tabs: Vec = crate::doc_windows::docked_windows(app) + .into_iter() + .filter_map(|w| Some((w, app.session.documents().get(w.0)?))) .map(|(w, d)| { let title = window_tab_title(app, w, d); - let color = if Some(w) == shown { t.text_strong } else { t.text_dim }; - (title.clone(), ui.painter().layout_no_wrap(title, theme::semibold(title_size), color)) + let (text, color) = + if Some(w) == shown { (title.clone(), t.text_strong) } else { (view_tab_name(d, crate::doc_windows::label(app, w)), t.text_dim) }; + let galley = ui.painter().layout_no_wrap(text.clone(), theme::semibold(title_size), color); + (w, text, title, galley) }) .collect(); - let widths: Vec = tabs.iter().map(|(_, g)| g.size().x + 50.0).collect(); + let active = tabs.iter().position(|(w, ..)| Some(*w) == shown); + let widths: Vec = tabs.iter().map(|(.., g)| g.size().x + TAB_PADDING).collect(); let overflow = widths.iter().sum::() > strip.width(); let room = strip.width() - if overflow { MORE } else { 0.0 }; let first = if overflow { first_tab_shown(&widths, active, room) } else { 0 }; + let (first, lead) = leading_tab(&widths, first, room, TAB_PADDING + MIN_TITLE); let mut x = strip.left(); let mut activate = None; let mut close = None; @@ -173,15 +243,31 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { // the drag just ended), for moving it along the strip. let mut slots: Vec<(usize, egui::Rect)> = vec![]; let mut dragged = None; - for (k, ((_, galley), w)) in tabs.iter().zip(&widths).enumerate().skip(first) { - if x + w > strip.left() + room && Some(k) != active { - break; - } - let Some(&win) = docked.get(k) else { break }; - let i = win.0; + for (k, ((win, text, title, galley), w)) in tabs.iter().zip(&widths).enumerate().skip(first) { + // A tab that doesn't fit whole takes the rest of the strip with its title shortened, as + // long as some of the title fits (#8584); its tooltip shows the whole title. The active + // tab always shows, shortened to the strip when it is wider than the whole strip. The + // leading tab before the ones that fit whole takes only the room they leave, and the tabs + // after it are drawn whole. + let left = tab_room(lead, k == first, *w, strip.left() + room - x); let is_active = Some(k) == active; - let r = egui::Rect::from_min_size(egui::pos2(x, strip.top()), vec2(*w, strip.height() - 1.0)); + // A shortened title too wide for its room even as "…" is not drawn, so it stays clear of + // the ×. + let (galley, w, shortened, title_fits) = if *w > left { + if left < TAB_PADDING + MIN_TITLE && !is_active { + break; + } + let color = if Some(*win) == shown { t.text_strong } else { t.text_dim }; + let (galley, fits) = shortened_title(ui.ctx(), text, theme::semibold(title_size), color, left - TAB_PADDING); + (galley, left.max(0.0), true, fits) + } else { + (galley.clone(), *w, false, true) + }; + let win = *win; + let i = win.0; + let r = egui::Rect::from_min_size(egui::pos2(x, strip.top()), vec2(w, strip.height() - 1.0)); let resp = ui.interact(r, ui.scope_id().with(("tab", i, win.1)), Sense::click_and_drag()); + let resp = if shortened || text != title { super::status_bar::full_text_tooltip(resp, title.as_str()) } else { resp }; slots.push((i, r)); if resp.dragged() || resp.drag_stopped() { dragged = Some((i, resp.drag_stopped())); @@ -196,13 +282,16 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { // (#673). let (x_center, title_left) = if CLOSE_BEFORE_TITLE { (r.left() + 16.0, r.left() + 32.0) } else { (r.right() - 16.0, r.left() + 14.0) }; let xr = egui::Rect::from_center_size(egui::pos2(x_center, r.center().y), vec2(12.0, 12.0)); - let xresp = ui.interact(xr.expand(3.0), ui.scope_id().with(("tabx", i, win.1)), Sense::click()); - icons::paint(ui, "x", xr, if xresp.hovered() { t.text_strong } else { t.text }); - ui.painter().galley(egui::pos2(title_left, r.center().y - galley.size().y / 2.0), galley.clone(), t.text); - hovering_art |= crate::document_drag::hover_tab(app, &resp, win, xr.expand(3.0)); + let xresp = tab_close_box(ui, &t, xr, w, ui.scope_id().with(("tabx", i, win.1))); + if title_fits { + ui.painter().galley(egui::pos2(title_left, r.center().y - galley.size().y / 2.0), galley, t.text); + } + let x_area = if xresp.is_some() { xr.expand(3.0) } else { egui::Rect::NOTHING }; + hovering_art |= crate::document_drag::hover_tab(app, &resp, win, x_area); // A middle-click anywhere on the tab closes it as the × does (#6506), so closing a // modified document's last view still asks to save first. - if xresp.clicked() || resp.middle_clicked() || xresp.middle_clicked() { + let x_clicked = xresp.as_ref().is_some_and(|x| x.clicked() || x.middle_clicked()); + if x_clicked || resp.middle_clicked() { close = Some(win); } else if resp.clicked() { activate = Some(win); @@ -485,10 +574,12 @@ pub(super) fn artboard_list(app: &VectorcraftApp, ui: &mut Ui, cur: usize) -> Op } // Every number ends where the widest one ends. let numbers = ui.painter().layout_no_wrap(boards.len().to_string(), egui::FontId::proportional(12.0), t.text_dim).size().x; - let width = ui.available_width().max(LIST_W); let mut chosen = None; ui.spacing_mut().item_spacing.y = 0.0; area.show_rows(ui, ROW_H, boards.len(), |ui, range| { + // The width beside the scroll bar's column: rows as wide as the list + // itself would widen it by the bar on every pass. + let width = ui.available_width().max(LIST_W); for i in range { let Some(board) = boards.get(i) else { continue }; let (r, resp) = ui.allocate_exact_size(vec2(width, ROW_H), Sense::click()); diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 09d31f1a5f..20828b0287 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -8,6 +8,50 @@ fn the_active_tab_stays_in_view() { assert_eq!(super::first_tab_shown(&widths, Some(4), 50.0), 4, "a tab wider than the room still shows"); } +/// When the tabs shown from a later one to the end leave room, the tab before them takes that room +/// (#8584). +#[test] +fn the_tab_before_the_shown_ones_takes_the_room_they_leave() { + let widths = [100.0; 10]; + assert_eq!(super::leading_tab(&widths, 7, 350.0, 90.0), (7, None), "50 left is less than the least room"); + assert_eq!(super::leading_tab(&widths, 7, 390.0, 90.0), (6, Some(90.0)), "exactly the least room"); + assert_eq!(super::leading_tab(&widths, 7, 389.0, 90.0), (7, None), "just under the least room"); + assert_eq!(super::leading_tab(&widths, 0, 2000.0, 90.0), (0, None), "no tab before the first"); + assert_eq!(super::leading_tab(&widths, 9, 50.0, 90.0), (9, None), "the tabs shown are wider than the room"); +} + +/// After a leading tab, the tabs are drawn whole, even when the strip's running sum leaves a hair +/// less than a tab's width; without one, a tab has the rest of the strip (#8584). +#[test] +fn the_tabs_after_the_leading_one_are_drawn_whole() { + assert_eq!(super::tab_room(Some(90.0), true, 200.0, 500.0), 90.0, "the leading tab"); + assert_eq!(super::tab_room(Some(90.0), false, 120.0, 119.99), 120.0, "a tab after it"); + assert_eq!(super::tab_room(None, false, 120.0, 119.99), 119.99, "no leading tab"); +} + +/// A shortened title shows at every width that holds "…", fractional ones included (#8584). +#[test] +fn a_shortened_title_fits_at_fractional_widths() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let font = crate::theme::semibold(13.0); + let title = "Untitled-12 @ 66.67 % (RGB/Preview)"; + let mut too_wide = vec![]; + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + let (ellipsis, _) = super::shortened_title(ui.ctx(), "…", font.clone(), egui::Color32::WHITE, 1000.0); + let mut width = ellipsis.size().x.ceil() + 1.0; + while width < 200.0 { + let (galley, fits) = super::shortened_title(ui.ctx(), title, font.clone(), egui::Color32::WHITE, width); + if !fits { + too_wide.push((width, galley.size().x)); + } + width += 0.25; + } + }); + output.textures_delta.clear(); + assert!(too_wide.is_empty(), "shortened titles wider than their room (room, width): {too_wide:?}"); +} + /// Tabs 100 wide at 0, 100, 200…, for documents `docs` (a document listed twice has two views). fn slots(docs: &[usize]) -> Vec<(usize, egui::Rect)> { docs.iter().enumerate().map(|(k, &d)| (d, egui::Rect::from_min_size(egui::pos2(k as f32 * 100.0, 0.0), egui::vec2(100.0, 30.0)))).collect() @@ -899,6 +943,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. @@ -1600,6 +1697,32 @@ fn the_artboard_list_lays_out_only_the_rows_near_the_view() { assert_eq!(app.view().unwrap().artboard, 999); } +/// #5941: with the app's scroll bar, which takes a column of its own, the artboard list's rows took +/// the whole list's width, so the list grew by the bar's width on every pass. Open, it keeps its +/// width. +#[test] +fn the_artboard_list_keeps_its_width_while_it_is_open() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100, "artboards": 30})).unwrap(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(460.0, 260.0))); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + let texts = status_texts(&mut app, &ctx, vec![]); + let field = texts.iter().find(|(s, _)| s == "1 Artboard 1").map(|(_, r)| *r).expect("the field"); + status_click(&mut app, &ctx, field.center()); + let list = |ctx: &egui::Context| { + ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id))) + }; + let widths: Vec = (0..8) + .map(|_| { + status_texts(&mut app, &ctx, vec![]); + list(&ctx).expect("the list is open").width() + }) + .collect(); + assert!(widths.windows(2).skip(2).all(|w| w[0] == w[1]), "the list keeps its width: {widths:?}"); +} + fn artboard_navigation_app(tool: &str) -> (crate::VectorcraftApp, vectorcraft_doc::NodeId) { let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 200, "height": 100, "artboards": 3})).unwrap(); @@ -2413,11 +2536,13 @@ fn artboard_document_tabs_frame(app: &mut crate::VectorcraftApp, ctx: &egui::Con let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 700.0)); let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| super::doc_tabs(app, ui)); out.textures_delta.clear(); + // A tab's title starts with its document's name (an inactive tab shows the name alone). + let names: Vec = app.session.documents().iter().map(|d| d.title()).collect(); let mut titles: Vec<_> = out .shapes .iter() .filter_map(|shape| match &shape.shape { - egui::Shape::Text(t) if t.galley.text().contains(" @ ") => Some(t.visual_bounding_rect()), + egui::Shape::Text(t) if names.iter().any(|n| t.galley.text().starts_with(n.as_str())) => Some(t.visual_bounding_rect()), _ => None, }) .collect(); @@ -2906,6 +3031,71 @@ fn full_screen_modes_fill_the_screen_and_normal_mode_restores_the_window() { assert!(sent(&mut app, true).is_empty(), "still full screen, as the user had it"); } +/// The Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools show Hide Shape Widgets in the +/// Control bar, with a selection and without one; a click hides the widgets and the button then reads +/// Show Shape Widgets, and a second click shows them again. The button comes before the shape's own +/// fields, so a window too narrow for the Polygon tool's Reset button still shows it. The Selection, +/// Spiral and Line Segment tools show no such button. +#[test] +fn the_shape_tools_control_bar_hides_and_shows_the_shape_widgets() { + struct RestoreLanguage(crate::i18n::Lang); + impl Drop for RestoreLanguage { + fn drop(&mut self) { + crate::i18n::set_current(self.0); + } + } + let _language = RestoreLanguage(crate::i18n::current()); + 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 ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let frame_in = |app: &mut crate::VectorcraftApp, width: f32, events: Vec| { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 400.0)); + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| super::control_bar(app, ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() + }; + let frame = |app: &mut crate::VectorcraftApp, events: Vec| frame_in(app, 1600.0, events); + let button_in = |app: &mut crate::VectorcraftApp, width: f32, name: &str| { + frame_in(app, width, vec![]); + frame_in(app, width, vec![]).into_iter().find(|(_, n)| n.label() == Some(name)).and_then(|(_, n)| n.bounds()) + }; + let button = |app: &mut crate::VectorcraftApp, name: &str| button_in(app, 1600.0, name); + let click = |app: &mut crate::VectorcraftApp, name: &str| { + let b = button(app, name).unwrap_or_else(|| panic!("no {name}")); + let at = egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, vec![egui::Event::PointerMoved(at), press(true)]); + frame(app, vec![press(false)]); + }; + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap()["id"].clone(); + for ids in [json!([id]), json!([])] { + app.run("select.set", json!({ "ids": ids })).unwrap(); + for tool in ["rectangle", "roundedRectangle", "ellipse", "polygon", "star"] { + app.select_tool(tool); + assert!(button(&mut app, "Hide Shape Widgets").is_some(), "{tool} {ids}"); + click(&mut app, "Hide Shape Widgets"); + assert!(!app.ui.view.shape_widgets, "{tool} {ids}"); + assert!(button(&mut app, "Hide Shape Widgets").is_none(), "{tool} {ids}"); + click(&mut app, "Show Shape Widgets"); + assert!(app.ui.view.shape_widgets, "{tool} {ids}"); + } + } + // Narrower and narrower: once the Polygon tool's Reset button is left out, the toggle still shows. + app.select_tool("polygon"); + let reset = button(&mut app, "Reset").expect("Reset in a wide window"); + let toggle = button(&mut app, "Hide Shape Widgets").expect("the toggle in a wide window"); + assert!(toggle.x1 <= reset.x0, "the toggle comes first: {toggle:?} {reset:?}"); + let narrow = (400..1600).step_by(10).rev().map(|w| w as f32).find(|w| button_in(&mut app, *w, "Reset").is_none()).expect("a width without Reset"); + assert!(button_in(&mut app, narrow, "Hide Shape Widgets").is_some(), "{narrow} wide"); + for tool in ["selection", "spiral", "lineSegment"] { + app.select_tool(tool); + assert!(button(&mut app, "Hide Shape Widgets").is_none(), "{tool}"); + } +} + /// Snapping quick access includes the existing glyph and alignment settings. Pointer clicks use /// their commands, and reopening reads the same state as View and Preferences (#6164). #[test] @@ -3592,6 +3782,30 @@ fn the_control_bar_keeps_its_label_and_menu_with_every_group_off() { assert!(!has(&bar, "Document Setup") && !has(&bar, "Preferences"), "{bar:?}"); } +/// The Control bar's selection label follows a selection whose middle object changes while its +/// length, first and last object stay the same, and a target circle with the selection unchanged. +#[test] +fn the_control_bar_label_follows_every_selected_object() { + use crate::tests_removeanchors::{control_frame, has}; + 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": 200})).unwrap(); + let id = |v: serde_json::Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap()); + let r: Vec<_> = (0..3).map(|i| id(app.run("shape.rectangle", json!({"x": i * 30, "y": 10, "width": 20, "height": 20})).unwrap())).collect(); + let t = id(app.run("text.create", json!({"x": 10, "y": 100, "text": "Hi"})).unwrap()); + app.run("select.set", json!({ "ids": r })).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let alike = crate::panels::appearance::object_label(&app); + assert!(has(&control_frame(&mut app, &ctx, vec![]), alike), "{alike}"); + app.session.active_mut().unwrap().selection.objects[1] = t; + let bar = control_frame(&mut app, &ctx, vec![]); + assert!(has(&bar, "Mixed Objects"), "{bar:?}"); + let layer = app.session.active().unwrap().doc.default_layer().unwrap(); + app.session.active_mut().unwrap().selection.target = Some(layer); + assert!(has(&control_frame(&mut app, &ctx, vec![]), "Layer"), "the targeted layer"); +} + /// `window.control.options {group, visible?}` turns a group of the Control bar's options on or /// off, or toggles it, and the panel menu's item shows it; an unknown or missing group, or a /// `visible` that is not true or false, is an error and changes nothing. diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 15f456d51f..b5b829ebbf 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1609,6 +1609,8 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRequest) let names = crate::dialogs::field_names(d).join(", "); return err(format!("the `{}` dialog has no field `{f}`; its fields: {names}", d.kind)); } + // Create Object Mosaic converts New Size against the selected image's size as it is now. + crate::dialogs::object_mosaic::refresh(app); // In order: a field that sets others (an export preset) goes before the fields after it. // A field that fails leaves the dialog as it was before the request. let before = app.ui.dialog.clone(); diff --git a/crates/ui-egui/src/custom_toolbars.rs b/crates/ui-egui/src/custom_toolbars.rs index e54085e304..2b70748c9c 100644 --- a/crates/ui-egui/src/custom_toolbars.rs +++ b/crates/ui-egui/src/custom_toolbars.rs @@ -686,14 +686,16 @@ pub fn sync(ui: &UiState) { } } -/// Window › Toolbars: Advanced, Double Column and Keep Tools Beside the Canvas, the toolbars made -/// with New Toolbar (each checked while it shows), New Toolbar… and Manage Toolbars…. +/// Window › Toolbars: Advanced, Double Column, Compact Tools and Keep Tools Beside the Canvas, +/// the toolbars made with New Toolbar (each checked while it shows), New Toolbar… and Manage +/// Toolbars…. pub fn menu_items() -> Vec { use crate::menus::Item; let c = |label: &'static str, id: &'static str| Item::Cmd(label, id, Value::Null); let mut v = vec![ c("Advanced", "window.toolbarAdvanced"), c("Double Column", "window.toolbarColumns"), + c("Compact Tools", "window.toolbarCompact"), c("Keep Tools Beside the Canvas", "window.toolsBesideCanvas"), Item::Sep, ]; @@ -1121,6 +1123,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)); } @@ -1351,7 +1354,7 @@ fn slot_button(ui: &mut egui::Ui, t: &Tokens, p: &Press, slot: &[String], action } let tip = crate::toolbar::tip(shown); resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), is_active, &tip)); - resp.on_hover_text(tip); + crate::toolbar::card::hover(resp, shown, crate::toolbar::card::Side::Beside, Some(tip)); Some((rect, shown.id)) } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index b96f5a7af0..a0341b71a4 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -15,8 +15,10 @@ 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(crate) use brush_art_options::{brush_key_color_canvas, brush_key_color_input, cancel_brush_key_color, refresh_brush_key_color}; pub mod brush_delete; pub mod brush_options; pub mod brush_replace_art; @@ -24,6 +26,7 @@ pub mod bullets_numbering; pub mod char_style_options; pub mod check_spelling; pub mod color_balance; +pub mod color_group_options; pub mod color_guide_options; pub(crate) mod color_picker; mod command; @@ -48,6 +51,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,11 +64,13 @@ 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; pub mod javascript_files; pub mod justification; +pub mod kinsoku_sets; pub mod layer_options; pub mod layers_panel_options; pub mod liquify; @@ -80,6 +86,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; @@ -98,6 +105,7 @@ pub mod plugin; mod png_options; pub mod print; pub mod print_presets; +pub mod profile_mismatch; pub mod psd_import; mod psd_options; pub mod raster_effects; @@ -171,6 +179,7 @@ pub(crate) use form::{humanize, number_list_text, plugin_color_button, ppi_suffi 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; +pub(crate) use save_pdf::{SAVE_SUMMARY as SAVE_PDF_SUMMARY, save_summary as save_pdf_summary, summary_open as pdf_summary_open}; pub use save_pdf::{open as open_save_pdf, open_preset as open_pdf_preset}; pub use tools::open_tool_dialog; @@ -343,8 +352,10 @@ 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, + ColorGroupOptions: [color_group_options::KIND] => color_group_options::SPEC, GraphData: [graph_data::KIND] => graph_data::SPEC, GraphDesign: [graph_design::DESIGN] => graph_design::DESIGN_SPEC, GraphColumn: [graph_design::COLUMN] => graph_design::COLUMN_SPEC, @@ -381,6 +392,7 @@ registry! { TateChuYokoSettings: [tate_chu_yoko::KIND] => tate_chu_yoko::SPEC, WarichuSettings: [warichu::KIND] => warichu::SPEC, CompositeFonts: [composite_fonts::KIND] => composite_fonts::SPEC, + KinsokuSets: [kinsoku_sets::KIND] => kinsoku_sets::SPEC, SavePdf: [save_pdf::KIND] => save_pdf::SPEC, SvgOptions: [svg_options::KIND] => svg_options::SPEC, JavaScriptFiles: [javascript_files::KIND] => javascript_files::SPEC, @@ -392,15 +404,19 @@ registry! { ExportAs: ["exportAs"] => export_as::SPEC, ImportPdf: [import_pdf::KIND] => import_pdf::SPEC, SwatchConflict: [swatch_conflict::KIND] => swatch_conflict::SPEC, + ProfileMismatchOpen: [profile_mismatch::OPEN_KIND] => profile_mismatch::OPEN_SPEC, + ProfileMismatchPaste: [profile_mismatch::PASTE_KIND] => profile_mismatch::PASTE_SPEC, FileInfo: [file_info::KIND] => file_info::SPEC, RasterEffectsSettings: [raster_effects::KIND] => raster_effects::SPEC, EffectGallery: [effect_gallery::KIND] => effect_gallery::SPEC, 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, + PdfFlattenerOptions: [save_pdf::CUSTOM_KIND] => save_pdf::CUSTOM_SPEC, SaveOptions: [save_options::KIND] => save_options::SPEC, TextExport: [text_export::KIND] => text_export::SPEC, OfficeExport: [office_export::KIND] => office_export::SPEC, @@ -420,6 +436,7 @@ registry! { 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, @@ -442,6 +459,7 @@ registry! { ScriptNotice: [script_run::NOTICE_KIND] => script_run::NOTICE_SPEC, ScriptFiles: [script_run::PICKER_KIND] => script_run::PICKER_SPEC, VectorHalftone: [halftone::KIND] => halftone::SPEC, + ObjectMosaic: [object_mosaic::KIND] => object_mosaic::SPEC, SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC, SmoothSlider: [smooth_slider::KIND] => smooth_slider::SPEC, SmartPunctuation: [smart_punctuation::KIND] => smart_punctuation::SPEC, @@ -472,6 +490,7 @@ registry! { LayerOptions: [layer_options::KIND] => layer_options::SPEC, LayersPanelOptions: [layers_panel_options::KIND] => layers_panel_options::SPEC, NavigatorPanelOptions: [navigator_panel_options::KIND] => navigator_panel_options::SPEC, + AttributesPanelOptions: [attributes_panel_options::KIND] => attributes_panel_options::SPEC, PathfinderOptions: [pathfinder_options::KIND] => pathfinder_options::SPEC, PixelSnapOptions: [pixel_snap_options::KIND] => pixel_snap_options::SPEC, RearrangeArtboards: [rearrange_artboards::KIND] => rearrange_artboards::SPEC, @@ -540,15 +559,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 entries and the preset name being typed. - Some(DialogKind::SaveForWeb) => &["__color", "__colors", "__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. @@ -600,8 +620,10 @@ 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. An Import PDF -/// `allPages` set this way to the other pick sets Import PDF pages as links back to its default. +/// A Graph Data Column Width set this way sets every column, as Cell Style's does. A Width Point +/// Edit side width set this way for several points sets it on every point, as typing it 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); @@ -621,15 +643,28 @@ pub fn set_field(d: &mut Dialog, field: String, value: Value) { if d.kind == new_document::KIND || new_document::popup_open(d) { new_document::note_set(d, &field); } + // Create Object Mosaic's Resize Using Percentages shows the new size the other way, as its checkbox does. + if d.kind == object_mosaic::KIND && field == "percentages" { + object_mosaic::set_percentages(d, &value); + return; + } let dxf = (d.kind == dxf_options::KIND).then(|| field.clone()); + let mosaic = (d.kind == object_mosaic::KIND).then(|| field.clone()); let graph = (d.kind == graph_data::KIND).then(|| field.clone()); + let width = (d.kind == width_point::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); } + if let Some(field) = width { + width_point::note_set(d, &field); + } } /// The fields `ui.dialog.set` can set on `d`, sorted: those it holds other than its `__` ones, the @@ -674,11 +709,12 @@ 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`, EPS Options' -/// `flattenerPreset`, which drops the Custom… options), a change +/// and Save PDF's `flattenerPreset`, which drop the Custom… options), a change /// to Export for Screens' sub-folder controls ends an applied preset's item folders, as it does in /// the dialog, Transform Each's Relative / Absolute keeps the Scale fields' size, and Recolor -/// Artwork's `group` selects that color group and its `groupAction` runs the button at once. A value -/// Composite Fonts' Show Sample can't take is refused. +/// Artwork's `group` selects that color group and its `groupAction` runs the button at once. Save +/// PDF's bleed link links the bleed as its button does. A value Composite Fonts' Show Sample or +/// Save PDF's bleed link can't take is refused. pub(crate) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Value>) -> Result<(), String> { if app.ui.dialog.as_ref().is_some_and(|d| d.kind == transform_each::KIND) { transform_each::field_set(app, field, old); @@ -690,6 +726,9 @@ pub(crate) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Valu if let Some(d) = app.ui.dialog.as_ref().filter(|d| d.kind == composite_fonts::KIND) { return composite_fonts::field_set(d, field); } + if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == save_pdf::KIND || d.kind == save_pdf::PRESET_KIND) { + return save_pdf::field_set(d, field); + } if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == eps_options::KIND) { eps_options::field_set(d, field); return Ok(()); @@ -710,21 +749,34 @@ pub(crate) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Valu /// Close the open dialog as Cancel does, rolling back a live preview and showing the dialog it was /// opened over (`ui.dialog.cancel`). pub fn cancel(app: &mut VectorcraftApp) { + cancel_brush_key_color(app, true); missing_fonts::requeue_replaced(app); // More Settings' pop-up and Save Preset end on their own; New Document stays. if app.ui.dialog.as_mut().is_some_and(new_document::close_popup) { return; } if let Some(d) = app.ui.dialog.take() { + if d.kind == "preferences" { + crate::original_editor::cancel(app); + } if d.kind == swatch_conflict::KIND { crate::placing::cancel_swatch_paste(app); } + if d.kind == profile_mismatch::OPEN_KIND { + profile_mismatch::cancel_open(app); + } + if d.kind == profile_mismatch::PASTE_KIND { + crate::placing::cancel_swatch_paste(app); + } if d.kind == plugin::INSTALL_KIND { app.pending_plugin_install = None; } 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(); @@ -736,6 +788,10 @@ pub fn cancel(app: &mut VectorcraftApp) { script_run::picker_cancel(app, &d); } missing_links::cancelled(app, &d); + // Cancel discards Recolor Artwork's own history of color edits with them. + if d.kind == recolor::KIND { + app.ui.recolor_history = Default::default(); + } // Find Font's next open starts with an empty replacement search. if d.kind == "findFont" && let Some(ctx) = app.ui_ctx.clone() @@ -773,6 +829,7 @@ pub(crate) fn reset(app: &mut VectorcraftApp) -> DialogResult { /// Apply the open dialog (OK). pub fn confirm(app: &mut VectorcraftApp) -> DialogResult { + cancel_brush_key_color(app, true); missing_fonts::requeue_replaced(app); let Some(d) = app.ui.dialog.clone() else { return Err("no dialog open".into()) }; // A file dialog it shows off the UI thread confirms the dialog as it is again. @@ -789,6 +846,7 @@ pub fn confirm(app: &mut VectorcraftApp) -> DialogResult { /// time). pub(crate) fn settle(app: &mut VectorcraftApp) { crate::placing::settle_swatch_paste(app); + profile_mismatch::settle(app); missing_fonts::requeue_replaced(app); missing_fonts::stop_when_closed(app); find_links::stop_when_closed(app); @@ -812,6 +870,7 @@ pub(crate) fn opened_by_panel(app: &mut VectorcraftApp) { /// Draws the active dialog and handles shared initial focus, keyboard shortcuts and actions. /// Inline actions and footer buttons use the same confirmation and preview rollback paths. pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { + refresh_brush_key_color(app); crate::shortcuts::hold_back_keys(app, ctx); about::show(app, ctx); settle(app); @@ -872,11 +931,13 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let revolves = revolve_gizmo::active(&d); if revolves { revolve_gizmo::show(app, ctx, &mut d); + three_d_classic::surface_outline(app, ctx, &d); } let initial = if revolves { egui::vec2((ctx.content_rect().width() / 2.0 - 226.0).max(0.0), -40.0) } else { egui::vec2(0.0, -40.0) }; let id = egui::Id::unique(("dialog", d.kind.as_str())); let id = if revolves { id.with("revolve") } else { id }; - modal::show_at(ctx, &heading, id, initial, MARGIN, |ui| { + let canvas_pick = brush_key_color_canvas(app, ctx); + modal::show_at(ctx, &heading, id, initial, MARGIN, canvas_pick, |ui| { // Never wider than the window (a large UI scale in a small window): the text wraps. let room = (ctx.content_rect().width() - 2.0 * (f32::from(MARGIN) + EDGE_GAP)).max(EDGE_GAP); ui.set_min_width(spec.min_width.min(room)); diff --git a/crates/ui-egui/src/dialogs/action_new.rs b/crates/ui-egui/src/dialogs/action_new.rs index dab6013e1d..838331d7a7 100644 --- a/crates/ui-egui/src/dialogs/action_new.rs +++ b/crates/ui-egui/src/dialogs/action_new.rs @@ -4,7 +4,8 @@ //! Fields: `set` (the index of the set the action goes into), `name`, `key` (0 for none, 1 to 15 //! for F1 to F15), `cmd` (Ctrl, Command on macOS), `shift`, `color` (a value of //! [`crate::panels::actions::COLORS`], `""` for none). An invalid set or function key is an error: -//! Record then adds nothing and the dialog stays open. +//! Record then adds nothing and the dialog stays open. `automaticAlignTo` (false) chooses the live +//! selection's reference for Align at playback while keeping recorded step targets. use serde_json::{Value, json}; @@ -46,7 +47,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<(), String> { let Some(s) = app.ui.action_sets.get(set) else { return Err("no such action set".into()) }; let taken = |n: usize| s.actions.iter().any(|a| a.name == format!("Action {n}")); let n = (s.actions.len() + 1..).find(|&n| !taken(n)).unwrap_or(1); - let fields = json!({"set": set, "name": format!("Action {n}"), "key": 0, "cmd": false, "shift": false, "color": ""}); + let fields = json!({"set": set, "name": format!("Action {n}"), "key": 0, "cmd": false, "shift": false, "color": "", "automaticAlignTo": false}); app.ui.dialog = Some(Dialog::new(KIND, fields)); Ok(()) } @@ -64,6 +65,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } }); key_and_color(ui, d); + automatic_align_options(ui, d); false } @@ -94,6 +96,14 @@ pub(super) fn key_and_color(ui: &mut egui::Ui, d: &mut Dialog) { super::form::choice(ui, d, "color", "Color:", (LABEL_W, 120.0), &colors); } +/// The Align playback option shared by New Action and Action Options. +pub(super) fn automatic_align_options(ui: &mut egui::Ui, d: &mut Dialog) { + super::form::check(ui, d, "automaticAlignTo", "Choose Align To at playback"); + widgets::dim_label(ui, "Align steps use the key object, key anchor or key guide when one is set."); + widgets::dim_label(ui, "With one whole object selected and no key, they use the artboard."); + widgets::dim_label(ui, "Otherwise they use the selection."); +} + /// The function key and color params the dialog's fields give, as `ui.action.new` and /// `ui.action.options` take them. pub(super) fn key_and_color_params(d: &Dialog) -> Value { @@ -114,6 +124,9 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut p = key_and_color_params(d); p["set"] = d.fields.get("set").cloned().unwrap_or(Value::Null); p["name"] = json!(name); + if let Some(value) = d.fields.get("automaticAlignTo") { + p["automaticAlignTo"] = value.clone(); + } app.run(crate::panels::actions::NEW_ACTION, p)?; app.ui.dialog = None; Ok(Value::Null) diff --git a/crates/ui-egui/src/dialogs/action_set_options.rs b/crates/ui-egui/src/dialogs/action_set_options.rs index 357f6e6840..660c36e07e 100644 --- a/crates/ui-egui/src/dialogs/action_set_options.rs +++ b/crates/ui-egui/src/dialogs/action_set_options.rs @@ -8,7 +8,8 @@ //! one, renames the set, or changes the action's name, function key and color //! (`ui.action.options`). An invalid `set`, `action` or function key is an error, and so is a name //! that would give the set a file that Load Actions… refuses (larger than 8 MiB). OK then changes no -//! set or action, and the dialog stays open. +//! set or action, and the dialog stays open. `automaticAlignTo` enables the live-selection Align +//! reference at playback without changing recorded targets. use serde_json::{Value, json}; @@ -52,7 +53,7 @@ pub fn open_action(app: &mut VectorcraftApp, set: usize, action: usize) { if let Some(a) = app.ui.action_sets.get(set).and_then(|s| s.actions.get(action)) { let (key, cmd, shift) = a.key.map_or((0, false, false), |k| (k.key, k.cmd, k.shift)); let color = a.color.clone().unwrap_or_default(); - let fields = json!({"set": set, "action": action, "name": a.name, "key": key, "cmd": cmd, "shift": shift, "color": color}); + let fields = json!({"set": set, "action": action, "name": a.name, "key": key, "cmd": cmd, "shift": shift, "color": color, "automaticAlignTo": a.automatic_align_to}); app.ui.dialog = Some(Dialog::new(KIND, fields)); } } @@ -65,6 +66,7 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { }); if action { super::action_new::key_and_color(ui, d); + super::action_new::automatic_align_options(ui, d); } false } @@ -82,6 +84,9 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { p["set"] = d.fields.get("set").cloned().unwrap_or(Value::Null); p["action"] = d.fields.get("action").cloned().unwrap_or(Value::Null); p["name"] = json!(name); + if let Some(value) = d.fields.get("automaticAlignTo") { + p["automaticAlignTo"] = value.clone(); + } app.run(crate::panels::actions::ACTION_OPTIONS, p)?; } else if let Some(set) = d.fields.get("set") { let i = set.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|&i| i < app.ui.action_sets.len()).ok_or("no such action set")?; 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 64ea036fa2..8054553d22 100644 --- a/crates/ui-egui/src/dialogs/brush_art_options.rs +++ b/crates/ui-egui/src/dialogs/brush_art_options.rs @@ -255,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) } @@ -436,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); @@ -450,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(); @@ -472,7 +474,7 @@ 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())); } @@ -734,12 +736,130 @@ fn tile_doc(art: &Node, w: f64, h: f64) -> Option { Some(doc) } +/// The private dialog marker survives with its draft, never in the brush definition. +const KEY_COLOR_DOC: &str = "__keyColorDoc"; + +fn key_color_owner_valid(app: &VectorcraftApp) -> bool { + let Some(pick) = app.ui.brush_key_color_pick.as_ref() else { return false }; + app.session.active().is_some_and(|doc| doc.uid == pick.doc) + && app.ui.dialog.as_ref().is_some_and(|dialog| { + dialog.kind == super::brush_options::KIND + && dialog.str("colorization") == "hueShift" + && dialog.fields.get(KEY_COLOR_DOC).and_then(Value::as_u64) == Some(pick.doc) + }) +} + +fn key_color_pick_active(app: &VectorcraftApp) -> bool { + key_color_owner_valid(app) && app.session.tool_id() == "eyedropper" && app.session.tool_options()["brushKeyColor"] == true +} + +/// Only the owned Brush Options pick opens an input aperture; other modal owners still block it. +pub(crate) fn brush_key_color_canvas(app: &VectorcraftApp, ctx: &egui::Context) -> Option { + (key_color_pick_active(app) + && !app.ui.about + && !app.ui.palette_open + && !app.file_dialog_open() + && !crate::updates_ui::blocks_input(app) + && !egui::Popup::is_any_open(ctx)) + .then_some(app.canvas_rect) + .flatten() +} + +/// Clear only the transient mode owned by this dialog, including a parked eyedropper. +pub(crate) fn cancel_brush_key_color(app: &mut VectorcraftApp, restore: bool) { + let Some(pick) = app.ui.brush_key_color_pick.take() else { return }; + let options = Map::from_iter([("brushKeyColor".into(), json!(false)), ("stop".into(), Value::Null)]); + app.session.set_tool_options(Some("eyedropper"), &options); + if restore && app.session.tool_id() == "eyedropper" { + app.return_to_tool(&pick.back); + } +} + +/// Refresh before real canvas input and dialog layout, so a stale press cannot reach another tool. +pub(crate) fn refresh_brush_key_color(app: &mut VectorcraftApp) -> bool { + if app.ui.brush_key_color_pick.is_none() || key_color_pick_active(app) { + return false; + } + let restore = !key_color_owner_valid(app) && app.session.tool_id() == "eyedropper"; + cancel_brush_key_color(app, restore); + true +} + +/// A foreground color click owns its physical Down/Up; the restored tool receives neither. +pub(crate) fn brush_key_color_input(app: &mut VectorcraftApp, ui: &egui::Ui, response: &egui::Response, rect: egui::Rect) -> bool { + if app.ui.brush_key_color_pick.is_none() { + return false; + } + let (pointer, focused, lost) = ui.input(|input| { + let up = input + .events + .iter() + .position(|event| matches!(event, egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, .. })); + let gone = input.events.iter().position(|event| matches!(event, egui::Event::PointerGone)); + let lost = gone.is_some_and(|gone| up.is_none_or(|up| gone < up)) + || input.events.iter().any(|event| matches!(event, egui::Event::Touch { phase: egui::TouchPhase::Cancel, .. })) + || input.multi_touch().is_some() + || response.long_touched(); + (input.pointer.clone(), input.focused, lost) + }); + let pending = app.ui.brush_key_color_pick.as_ref().is_some_and(|pick| pick.press.is_some()); + if pending && (!focused || lost || (!pointer.primary_down() && !pointer.primary_released())) { + cancel_brush_key_color(app, true); + return true; + } + if brush_key_color_canvas(app, ui.ctx()).is_none() { + if let Some(pick) = app.ui.brush_key_color_pick.as_mut() { + pick.press = None; + } + return false; + } + if !focused { + return true; + } + if pointer.primary_pressed() + && response.hovered() + && let Some(point) = pointer.interact_pos().filter(|point| rect.contains(*point) && ui.clip_rect().contains(*point)) + { + let xf = crate::canvas::Xf::at(rect, app.view().unwrap_or(&crate::View::default()), app.canvas_ui_zoom); + if let Some(pick) = app.ui.brush_key_color_pick.as_mut() { + pick.press = Some(xf.to_doc(point)); + } + } + if pointer.button_released(egui::PointerButton::Primary) + && let Some(point) = app.ui.brush_key_color_pick.as_mut().and_then(|pick| pick.press.take()) + { + // The existing tool returns a deferred SwitchTool request. Release Eye before applying + // that request, so a held color click cannot start or finish a stroke in the prior tool. + let view = app.view_info(); + let down = vectorcraft_tools::PointerEvent::new(vectorcraft_tools::PointerKind::Down, point.x, point.y); + let up = vectorcraft_tools::PointerEvent::new(vectorcraft_tools::PointerKind::Up, point.x, point.y); + let sampled = app.session.pointer(&down, view); + let released = app.session.pointer(&up, view); + crate::canvas::apply_requests(app, sampled); + crate::canvas::apply_requests(app, released); + } + true +} + /// Key Color eyedropper: sample the next click on the art into this dialog's `keyColor`. -fn key_color_eyedropper(app: &mut VectorcraftApp) { - let back = app.session.tool_id(); - app.select_tool("eyedropper"); +fn key_color_eyedropper(app: &mut VectorcraftApp, dialog: &mut Dialog) { + if app.ui.brush_key_color_pick.is_some() { + cancel_brush_key_color(app, true); + return; + } + let Some(doc) = app.session.active().map(|doc| doc.uid) else { return }; + if dialog.fields.get(KEY_COLOR_DOC).and_then(Value::as_u64).is_some_and(|owner| owner != doc) { + return; + } + let back = app.session.tool_id().to_string(); + if let Err(error) = app.try_select_tool("eyedropper") { + app.status(error); + return; + } app.session.set_tool_option("brushKeyColor", &json!(true)); app.session.set_tool_option("stop", &json!(back)); + dialog.fields.insert(KEY_COLOR_DOC.into(), json!(doc)); + app.ui.brush_key_color_pick = Some(crate::state::BrushKeyColorPick { doc, back, press: None }); } fn colorization_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { @@ -777,7 +897,7 @@ fn colorization_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog } } if widgets::icon_button(ui, "pipette", tl!("Eyedropper: click the art to sample the key color"), false, 22.0).clicked() { - key_color_eyedropper(app); + key_color_eyedropper(app, d); } }); }); @@ -785,6 +905,17 @@ fn colorization_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog /// Apply a sampled colour to the open Brush Options dialog (`brushKeyColor` tool request). pub(super) fn apply_key_color_sample(app: &mut VectorcraftApp, color: &Value) { + let marked = app.ui.dialog.as_ref().is_some_and(|dialog| dialog.fields.contains_key(KEY_COLOR_DOC)); + if app.ui.brush_key_color_pick.is_some() { + if !key_color_owner_valid(app) { + cancel_brush_key_color(app, false); + return; + } + cancel_brush_key_color(app, false); + } else if marked { + // A reply cannot change the draft after its owned pick was cancelled or replaced. + return; + } let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == super::brush_options::KIND) else { return }; if d.str("colorization") != "hueShift" { return; diff --git a/crates/ui-egui/src/dialogs/brush_options.rs b/crates/ui-egui/src/dialogs/brush_options.rs index eafe697a0f..f8b25e8249 100644 --- a/crates/ui-egui/src/dialogs/brush_options.rs +++ b/crates/ui-egui/src/dialogs/brush_options.rs @@ -454,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/color_group_options.rs b/crates/ui-egui/src/dialogs/color_group_options.rs new file mode 100644 index 0000000000..101b5496a3 --- /dev/null +++ b/crates/ui-egui/src/dialogs/color_group_options.rs @@ -0,0 +1,182 @@ +//! Color Group Options: the name of a color group in the Swatches panel. OK renames the group +//! (`swatch.renameGroup`) and keeps it selected in the panel; its swatches and their colors stay +//! as they are. +//! +//! Fields: `name`, `__group` (the group being renamed), `__swatches` (the names of its swatches +//! when the dialog opened), `__index` (its place in the list of color groups) and `__doc` (the uid +//! of its document). + +use serde_json::{Value, json}; + +use super::swatch_options::{grid, label}; +use super::{DialogSpec, form}; +use crate::VectorcraftApp; +use crate::state::Dialog; + +/// The dialog kind of Color Group Options. +pub const KIND: &str = "colorGroupOptions"; + +pub(super) const SPEC: DialogSpec = + DialogSpec { heading: |_| tl!("Color Group Options").into(), body, confirm, min_width: 320.0, ..DialogSpec::FORM }; + +/// The field that holds the uid of the document the dialog opened on. +const DOC: &str = "__doc"; + +/// The field that holds the names of the group's swatches when the dialog opened. +const SWATCHES: &str = "__swatches"; + +/// The field that holds the group's place in the document's list of color groups. +const INDEX: &str = "__index"; + +/// `ui.colorGroupOptions {group?}`: open Color Group Options for color group `group`, or without +/// `group` for the color group selected alone in the Swatches panel. +pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { + let key = "group"; + let group = match p.get(key) { + Some(Value::String(g)) => g.clone(), + None | Some(Value::Null) => crate::panels::swatches::sole_selected_group(app).ok_or("missing `group`")?, + Some(_) => return Err(format!("`{key}` must be a string")), + }; + let st = app.session.active().ok_or("no document open")?; + let at = st.doc.swatch_groups.iter().position(|g| g.name == group).ok_or_else(|| format!("no colour group `{group}`"))?; + let g = &st.doc.swatch_groups[at]; + let swatches: Vec<&str> = g.swatches.iter().map(|w| w.name.as_str()).collect(); + let fields = json!({ "name": g.name.clone(), "__group": g.name.clone(), SWATCHES: swatches, INDEX: at, DOC: st.uid }); + app.ui.dialog = Some(Dialog::new(KIND, fields)); + Ok(Value::Null) +} + +/// Whether the dialog's group is still in its document, at the place in the list, under the name +/// and with the swatches it opened with, and that document is the active one. +fn same_group(app: &VectorcraftApp, d: &Dialog) -> bool { + let Some(st) = app.session.active().filter(|st| d.fields.get(DOC).and_then(Value::as_u64) == Some(st.uid)) else { return false }; + let at = d.fields.get(INDEX).and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()); + let opened: Vec<&str> = + d.fields.get(SWATCHES).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); + let group = d.str("__group"); + at.and_then(|i| st.doc.swatch_groups.get(i)) + .is_some_and(|g| g.name == group && g.swatches.iter().map(|w| w.name.as_str()).eq(opened.iter().copied())) +} + +fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + grid(ui, |ui| { + label(ui, tl!("Name:")); + form::text(ui, d, "name", 190.0); + ui.end_row(); + }); + false +} + +/// OK: rename the group (the Swatches panel keeps it selected, [`crate::panels::swatches::after_command`]). +/// A name that is empty or that another group or a swatch has keeps the dialog open. When another +/// document has become the active one, or the color group at the group's place in the list no +/// longer has the name and swatches it opened with, it closes as Cancel does and renames nothing. +/// Color groups carry nothing else to tell them apart. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if !same_group(app, d) { + app.ui.dialog = None; + return Ok(json!({})); + } + let r = app.run("swatch.renameGroup", json!({ "group": d.str("__group"), "name": d.str("name") })); + if r.is_ok() { + app.ui.dialog = None; + } + r +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app + } + + fn set(app: &mut VectorcraftApp, v: &str) { + app.ui.dialog.as_mut().unwrap().fields.insert("name".into(), json!(v)); + } + + fn groups(app: &VectorcraftApp) -> Vec { + app.session.active().unwrap().doc.swatch_groups.iter().map(|g| g.name.clone()).collect() + } + + fn undo_len(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() + } + + /// The dialog opens on the group's name; OK renames it in one undo step, a taken or empty name + /// keeps the dialog open with nothing changed, Cancel changes nothing, and OK with the name + /// unchanged records no undo step. + #[test] + fn renames_the_group_and_keeps_a_refused_name_open() { + let mut app = app(); + app.run("ui.colorGroupOptions", json!({"group": "Brights"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), d.str("name").as_str(), d.str("__group").as_str()), (KIND, "Brights", "Brights")); + // 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 undo = undo_len(&app); + for taken in ["Grays", "White", " "] { + set(&mut app, taken); + assert!(super::super::confirm(&mut app).is_err(), "{taken:?}"); + assert!(app.ui.dialog.is_some(), "{taken:?} keeps the dialog open"); + assert_eq!(undo_len(&app), undo, "{taken:?}"); + } + set(&mut app, "Vivid"); + super::super::cancel(&mut app); + assert!(app.ui.dialog.is_none() && groups(&app).contains(&"Brights".to_string()), "Cancel keeps the name"); + assert_eq!(undo_len(&app), undo); + app.run("ui.colorGroupOptions", json!({"group": "Brights"})).unwrap(); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(undo_len(&app), undo, "the same name records no undo step"); + app.run("ui.colorGroupOptions", json!({"group": "Brights"})).unwrap(); + set(&mut app, "Vivid"); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none() && groups(&app).contains(&"Vivid".to_string())); + assert_eq!(undo_len(&app), undo + 1); + assert!(app.run("ui.colorGroupOptions", json!({"group": "Brights"})).is_err()); + assert!(app.run("ui.colorGroupOptions", json!({"group": "White"})).is_err(), "a swatch is not a group"); + assert!(app.run("ui.colorGroupOptions", json!({})).is_err()); + assert!(app.run("ui.colorGroupOptions", json!({"group": 5})).is_err()); + } + + /// OK closes the dialog and renames nothing when another document has become the active one, + /// or when another group took the name of the group it opened on while it was open. + #[test] + fn renames_only_the_group_it_opened_on() { + let mut app = app(); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("ui.colorGroupOptions", json!({"group": "Brights"})).unwrap(); + app.run("document.activate", json!({"index": 1})).unwrap(); + set(&mut app, "Vivid"); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert!(groups(&app).contains(&"Brights".to_string()), "the document made active keeps its group"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert!(groups(&app).contains(&"Brights".to_string()), "the group it opened on keeps its name"); + // Its group ungrouped, and another group renamed to its name. + app.run("ui.colorGroupOptions", json!({"group": "Brights"})).unwrap(); + app.run("swatch.ungroup", json!({"name": "Brights"})).unwrap(); + app.run("swatch.renameGroup", json!({"group": "Grays", "name": "Brights"})).unwrap(); + set(&mut app, "Vivid"); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert!(groups(&app).contains(&"Brights".to_string()) && !groups(&app).contains(&"Vivid".to_string())); + // Its group moved to another place in the list. + app.run("swatch.newGroup", json!({"name": "Extra", "swatches": ["White"]})).unwrap(); + let first = groups(&app)[0].clone(); + app.run("ui.colorGroupOptions", json!({"group": first})).unwrap(); + app.run("swatch.move", json!({"names": [first]})).unwrap(); + set(&mut app, "Vivid"); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none() && groups(&app).contains(&first) && !groups(&app).contains(&"Vivid".to_string())); + } +} diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index 758832cd92..52a6086816 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -300,12 +300,20 @@ pub(super) fn over_effect(parent: &Dialog, field: &str, colour: Color) -> Dialog /// The entry of the dialog's color list that a Color Picker opened with [`over_list_entry`] sets. const COLOUR_INDEX: &str = "__colourIndex"; +/// The list a Color Picker opened with [`over_list_entry`] puts in the dialog's field before its OK +/// sets the entry. +const COLOUR_LIST: &str = "__colourList"; + /// 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 { +/// the other entries as they are. With `fill`, its OK first puts `fill` in the field and then sets +/// the entry. 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, fill: Option) -> Dialog { let mut d = over_effect(parent, field, colour); d.fields.insert(COLOUR_INDEX.into(), json!(index)); + if let Some(list) = fill { + d.fields.insert(COLOUR_LIST.into(), list); + } d } @@ -346,22 +354,46 @@ fn button_width(ui: &Ui) -> f32 { }) } -/// A compact width shared by the heading and body, bounded by the available window width. -fn layout_size(ui: &Ui) -> (f32, f32, f32, bool) { +/// A compact width shared by the heading and body, bounded by the available window width, and the +/// width of the body's scroll bar column. While the body scrolls, the width leaves out that column, +/// so the body and its bar fit in the window side by side. +fn layout_size(ui: &Ui) -> (f32, f32, f32, bool, f32) { let button_w = button_width(ui); let values_w = PREVIEW_W + COLUMN_GAP + button_w; let fixed_w = SLIDER_GAP + SLIDER_W + COLUMN_GAP + values_w; - let stacked = ui.available_width() < MIN_FIELD + fixed_w; - let side = (ui.available_width() - fixed_w).clamp(MIN_FIELD, FIELD); - (side, values_w, button_w, stacked) + let fit = |room: f32| ((room - fixed_w).clamp(MIN_FIELD, FIELD), room < MIN_FIELD + fixed_w); + let (side, stacked) = fit(ui.available_width()); + // The margin keeps the bar's column whenever the body may scroll, as its height is estimated. + if body_height(ui, side, stacked) + 40.0 > scroll_height(ui) { + let bar = ui.spacing().scroll.allocated_width(); + let (side, stacked) = fit(ui.available_width() - bar); + (side, values_w, button_w, stacked, bar) + } else { + (side, values_w, button_w, stacked, 0.0) + } +} + +/// The tallest the body's scrolling content is drawn. +fn scroll_height(ui: &Ui) -> f32 { + (ui.ctx().content_rect().height() - 112.0).max(1.0) +} + +/// How tall the body's field, slider and value columns are with a field `side` wide, `stacked` or +/// side by side. +fn body_height(ui: &Ui, side: f32, stacked: bool) -> f32 { + // Let the auto-sized window grow for the checkbox too, rather than clipping it to the + // scroll area's previous height while the dialog measures itself. + let field_h = side + 8.0 + 20.0 + 2.0 * ui.spacing().item_spacing.y; + if stacked { field_h + COLUMN_GAP + FIELD } else { field_h.max(FIELD) } } /// Full-width, draggable title band using the app's existing theme colours. fn header(ui: &mut Ui, title: &str) { - let (side, values_w, _, stacked) = layout_size(ui); + let (side, values_w, _, stacked, bar) = layout_size(ui); let field_w = side + SLIDER_GAP + SLIDER_W; let width = if stacked { field_w.max(values_w) } else { field_w + COLUMN_GAP + values_w }; - ui.set_width(width.min(ui.available_width())); + // The width includes the bar's column: the body measures from it and leaves the column out. + ui.set_width((width + bar).min(ui.available_width())); let margin = f32::from(super::MARGIN); let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), HEADER_H - margin), Sense::hover()); let band = Rect::from_min_max(r.min - vec2(margin, margin), r.max + vec2(margin, 0.0)); @@ -385,7 +417,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> DialogAction { 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 (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 }; let mut pick: Option = None; @@ -395,11 +427,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> DialogAction { let mut action = DialogAction::None; // Shrink the field first, then stack the columns in narrow windows. Only vertical // scrolling is needed, so no controls depend on a horizontal scrollbar. - let height = (ui.ctx().content_rect().height() - 112.0).max(1.0); - // Let the auto-sized window grow for the checkbox too, rather than clipping it to the - // scroll area's previous height while the dialog measures itself. - let field_h = side + 8.0 + 20.0 + 2.0 * ui.spacing().item_spacing.y; - let body_height = if stacked { field_h + COLUMN_GAP + FIELD } else { field_h.max(FIELD) }; + let height = scroll_height(ui); + let body_height = body_height(ui, side, stacked); let layout = if stacked { egui::Layout::top_down(egui::Align::Min) } else { egui::Layout::left_to_right(egui::Align::Min) }; egui::ScrollArea::vertical() .id_salt("cp-content") @@ -702,8 +731,9 @@ fn swatch_list(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, current: &Colo ui.add_space(4.0); widgets::list_box(ui, |ui| { let max_h = (side - 28.0).max(1.0); - egui::ScrollArea::vertical().id_salt("cp-swatches").max_height(max_h).show(ui, |ui| { - ui.set_width(list_w - 8.0); + // The rows take the list's width less its scroll bar's column. + egui::ScrollArea::vertical().id_salt("cp-swatches").max_width(list_w - 8.0).max_height(max_h).auto_shrink([false, true]).show(ui, |ui| { + ui.set_width(ui.available_width()); let cur = d.str("library"); if cur.is_empty() || cur == swatchlib::DOCUMENT_SWATCHES { let Some(st) = app.session.active() else { @@ -769,6 +799,9 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { parent.fields.insert(field.to_string(), hex); } Some(index) => { + if let Some(list) = d.fields.get(COLOUR_LIST) { + parent.fields.insert(field.to_string(), list.clone()); + } let entry = index .as_u64() .and_then(|i| usize::try_from(i).ok()) diff --git a/crates/ui-egui/src/dialogs/color_picker/tests.rs b/crates/ui-egui/src/dialogs/color_picker/tests.rs index 15344a131c..081c5324d5 100644 --- a/crates/ui-egui/src/dialogs/color_picker/tests.rs +++ b/crates/ui-egui/src/dialogs/color_picker/tests.rs @@ -776,6 +776,73 @@ fn compact_picker_shrinks_then_scrolls_without_enlarging_the_window() { } } +/// #5941: in a window short enough to scroll the picker, at any width, its scroll bar shows +/// inside the window and the content fits beside it: no label is cut off at the side. +#[test] +fn a_scrolling_picker_shows_its_bar_and_fits_its_content_beside_it() { + fn sideways_clipped(shape: &egui::Shape, clip: Rect, out: &mut Vec) { + match shape { + egui::Shape::Text(t) => { + let r = t.visual_bounding_rect(); + let rows_shown = clip.top() <= r.top() && r.bottom() <= clip.bottom(); + if rows_shown && !t.galley.text().trim().is_empty() && (r.left() < clip.left() - 1.0 || r.right() > clip.right() + 1.0) { + out.push(format!("{:?} {r:?} in {clip:?}", t.galley.text())); + } + } + egui::Shape::Vec(v) => v.iter().for_each(|s| sideways_clipped(s, clip, out)), + _ => {} + } + } + for width in (400..=800).step_by(8) { + let size = vec2(width as f32, 380.0); + let (ctx, mut app) = (context(), app()); + app.run("ui.colorPicker", json!({"color": "#0000ff"})).unwrap(); + settled(&ctx, &mut app, size); + let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, size)), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| super::super::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + let mut clipped = vec![]; + for s in &out.shapes { + sideways_clipped(&s.shape, s.clip_rect, &mut clipped); + } + assert!(clipped.is_empty(), "{size:?}: {clipped:?}"); + let outer = ctx.memory(|m| m.area_rect(egui::Id::unique(("dialog", KIND)))).unwrap(); + assert!(outer.left() >= -0.5 && outer.right() <= size.x + 0.5, "{size:?}: the window {outer:?} stays on screen"); + // The content's scroll bar: a narrow filled rectangle taller than a row, inside the window. + let mut bars = vec![]; + let mut walk = vec![]; + out.shapes.iter().for_each(|c| walk.push(c.shape.clone())); + while let Some(s) = walk.pop() { + match s { + egui::Shape::Vec(v) => walk.extend(v), + egui::Shape::Rect(r) if r.fill.a() > 0 && r.rect.width() <= 8.0 && r.rect.height() > 40.0 => bars.push(r.rect), + _ => {} + } + } + assert!(bars.iter().any(|b| outer.contains_rect(*b)), "{size:?}: the content scrolls and its bar shows in {outer:?}: {bars:?}"); + } +} + +/// #5941: while the body scrolls, the heading sets the dialog's width to the one the body lays its +/// field and columns out in, with the scroll bar's column, so the body measures the same layout from +/// it and does not leave out the bar's column a second time. +#[test] +fn the_heading_leaves_the_body_the_width_of_the_layout_it_measured() { + let ctx = context(); + for width in (400..=800).step_by(4) { + let size = vec2(width as f32, 380.0); + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, size)), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + let (side, _, _, stacked, bar) = layout_size(ui); + assert!(bar > 0.0, "{size:?}: the body scrolls"); + header(ui, "Color Picker"); + let (body_side, _, _, body_stacked, _) = layout_size(ui); + assert_eq!((body_side, body_stacked), (side, stacked), "{size:?}: the body lays out the field and columns the heading measured"); + }); + out.textures_delta.clear(); + } +} + /// Type all three Lab components through the numeric fields, then apply the picked color. #[test] fn native_lab_entry_in_color_picker() { diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index de7836f0a5..6fd3009921 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -84,7 +84,8 @@ fn heading_in(lang: crate::i18n::Lang, label: &str) -> String { /// too (#5360), as public tutorials of the dialog show, and Type Tools › Release Type on a Path /// works the same way (#5532), and so do Image Tools › Remove Background and Color Mask and /// Cutting Tools › Weed Box and Lines, Banner Hems and Grommets and Nest Shapes, and Path -/// Precision Tools › Common Tangents. (Cancel rolls a preview back whichever dialog started it.) +/// Precision Tools › Common Tangents and the bounding shapes (Add Bounding Rectangle… and Add +/// Bounding Circle…). (Cancel rolls a preview back whichever dialog started it.) fn previews(d: &Dialog) -> bool { match d.str("__command").as_str() { "object.repeat.options" => d.fields.contains_key("gridType"), @@ -95,7 +96,9 @@ fn previews(d: &Dialog) -> bool { | crate::addons::cutting::WEED | crate::addons::cutting::BANNER | crate::addons::cutting::NEST - | crate::addons::pathtools::COMMON_TANGENTS => true, + | crate::addons::pathtools::COMMON_TANGENTS + | crate::addons::pathtools::BOUNDING_RECTANGLE + | crate::addons::pathtools::BOUNDING_CIRCLE => true, _ => false, } } @@ -150,6 +153,7 @@ fn lengths(command: &str) -> &'static [&'static str] { "object.pathfinder.trap" => &["thickness"], crate::addons::cutting::BRIDGES => &["width"], "object.textWrap.options" => &["offset"], + crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE => &["offset"], _ => &[], } } @@ -159,6 +163,11 @@ fn lengths(command: &str) -> &'static [&'static str] { pub(super) fn length_range(command: &str, key: &str) -> Option> { match (command, key) { ("object.textWrap.options", "offset") => Some(vectorcraft_engine::TEXT_WRAP_OFFSET_RANGE), + // The bounding shapes take an offset of 0 or more, and the command refuses one that takes + // the shape past the canvas edge. + (crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE, "offset") => { + Some(0.0..=vectorcraft_engine::MAX_COORD) + } _ => None, } } @@ -182,6 +191,7 @@ fn order(command: &str) -> &'static [&'static str] { crate::addons::cutting::BRIDGES => &["width", "count", "direction", "keepOriginal"], crate::addons::packaging::SET_ROLE_SWATCH => &["role", "swatch"], crate::addons::pathtools::COMMON_TANGENTS => &["tangents", "centerline"], + crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE => &["offset", "each"], _ => &[], } } diff --git a/crates/ui-egui/src/dialogs/confirm.rs b/crates/ui-egui/src/dialogs/confirm.rs index 15b28c2d27..756bf71255 100644 --- a/crates/ui-egui/src/dialogs/confirm.rs +++ b/crates/ui-egui/src/dialogs/confirm.rs @@ -130,6 +130,7 @@ pub(crate) fn ask_reset_prefs(app: &mut VectorcraftApp) { fn reset_prefs(app: &mut VectorcraftApp, d: &Dialog) -> Result { let mut prefs = super::parent(d).filter(|p| p.kind == "preferences").ok_or("the dialog it was opened over is no longer open")?; crate::prefs_dialog::reset_fields(&mut prefs); + crate::original_editor::reset(app); app.ui.dialog = Some(prefs); Ok(Value::Null) } @@ -156,6 +157,53 @@ 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. +/// While another dialog is open (a press sent with `ui.pointer` reaches the tool then), that dialog +/// stays and the Type tool forgets the edit, as Cancel would. +pub(crate) fn ask_missing_font_edit(app: &mut VectorcraftApp, p: &Value) { + if app.ui.dialog.as_ref().is_some_and(|d| d.kind != MISSING_FONT_EDIT) { + app.session.set_tool_option("missingFontEdit", &json!({"token": p.get("token"), "ok": false})); + return; + } + 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 3a977e76c6..950e8bfabd 100644 --- a/crates/ui-egui/src/dialogs/dimension.rs +++ b/crates/ui-egui/src/dialogs/dimension.rs @@ -338,6 +338,12 @@ pub fn properties_section(app: &mut VectorcraftApp, ui: &mut Ui) { changed |= color(ui, &mut f, "lineColor"); }); ui.horizontal(|ui| changed |= arrow_style(ui, &mut f, "props-arrowStyle")); + widgets::section_header(ui, tl!("Extension Lines")); + ui.horizontal(|ui| { + changed |= number(ui, &mut f, "extensionWeight", "Line Weight:", (0.1, 100.0), "pt"); + changed |= color(ui, &mut f, "extensionColor"); + }); + widgets::section_header(ui, tl!("Dimension Text")); ui.horizontal(|ui| { changed |= number(ui, &mut f, "fontSize", "Font Size:", (1.0, 1000.0), "pt"); changed |= color(ui, &mut f, "textColor"); diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 187e36e6b0..575603e926 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; @@ -39,6 +42,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { fields["bleedLinked"] = json!(linked); fields["tab"] = json!(TABS[0]); if let Some(st) = app.session.active() { + fields["gridColors"] = json!(st.doc.setup.grid_colors.map(|c| grid_color_entry(&c))); let (rgb, cmyk) = doc_profiles(&st.doc); fields["colorMode"] = json!(mode_id(st.doc.color_mode)); fields["rgbProfile"] = json!(rgb); @@ -102,6 +106,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 +115,24 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { }; if r.is_ok() { app.ui.dialog = None; + if let Some(note) = before.and_then(|b| short_of_bleed_note(app, b)) { + app.status(note); + } } r } +/// The status note after OK raised the bleed on a side from `before`: how many objects reach an +/// artboard's trim edge on a side whose bleed grew but stop short of the new bleed there. `None` +/// when no side grew or no object stops short. +fn short_of_bleed_note(app: &VectorcraftApp, before: [f64; 4]) -> Option { + let doc = &app.session.active()?.doc; + // In the range the PDF pages keep the document's bleed to. + let (bleed, before) = (bleed_in_range(doc.setup.bleed), bleed_in_range(before)); + let raised: [f64; 4] = std::array::from_fn(|i| if bleed[i] > before[i] { bleed[i] } else { 0.0 }); + pdf::short_of_bleed_warning(pdf::short_of_bleed(doc, raised, None, false)) +} + fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let tab = TABS.iter().position(|t| *t == d.str("tab")).unwrap_or(0); if let Some(i) = widgets::tab_bar(ui, &TABS, tab) { @@ -180,15 +199,80 @@ fn grid_color_box_id(index: usize) -> egui::Id { egui::Id::unique(("grid-color-box", index)) } -/// The grid colors' hex codes that Document Setup `d` holds now (empty strings for entries that are -/// not strings). -fn grid_colors(d: &Dialog) -> Vec { - d.fields.get("gridColors").and_then(Value::as_array).map(|a| a.iter().map(|c| c.as_str().unwrap_or("").to_string()).collect()).unwrap_or_default() +/// The size of the Transparency tab's grid preview, in points. +const GRID_PREVIEW: egui::Vec2 = egui::vec2(112.0, 72.0); + +/// The grid size and the two colors the grid preview shows for the dialog's fields `fields`, read +/// as `document.setup` reads them (a preset name or two colors): a field that is missing or not a +/// valid value shows as `setup`, the document's setting. +fn preview_grid(fields: &Map, setup: &vectorcraft_doc::DocSetup) -> (GridSize, [vectorcraft_color::Color; 2]) { + let size = fields.get("gridSize").and_then(Value::as_str).and_then(GridSize::parse).unwrap_or(setup.grid_size); + (size, grid_colors(fields, setup)) +} + +/// The two grid colors the dialog's fields `fields` hold, read as `document.setup` reads +/// `gridColors` (a preset name, in any letter case, or two colors): a field that is missing or not +/// a valid value gives `setup`'s colors, the document's setting. +fn grid_colors(fields: &Map, setup: &vectorcraft_doc::DocSetup) -> [vectorcraft_color::Color; 2] { + let colors = match fields.get("gridColors") { + Some(Value::String(name)) => GRID_COLOR_PRESETS.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, pair)| *pair), + Some(Value::Array(a)) if a.len() == 2 => a.iter().map(vectorcraft_engine::cmd::color_value).collect::>>().map(|c| [c[0], c[1]]), + _ => None, + }; + colors.unwrap_or(setup.grid_colors) +} + +/// The dialog's `gridColors` when it is a list of two colors `document.setup` reads, entries as +/// they are. +fn pending_grid_pair(fields: &Map) -> Option> { + let entries = fields.get("gridColors").and_then(Value::as_array)?; + (entries.len() == 2 && entries.iter().all(|c| vectorcraft_engine::cmd::color_value(c).is_some())).then(|| entries.clone()) +} + +/// Color `c` as an entry of the dialog's `gridColors` that `document.setup` reads back as `c`: its +/// hex code when that reads back as `c`, else the color in its own model (a Lab or CMYK color, or +/// an RGB color whose hex code is converted to display RGB or rounded). +fn grid_color_entry(c: &vectorcraft_color::Color) -> Value { + let hex = json!(c.to_hex()); + if vectorcraft_engine::cmd::color_value(&hex) == Some(*c) { hex } else { serde_json::to_value(c).unwrap_or(hex) } +} + +/// The checkered preview of the grid the dialog's Grid Size and Grid Colors hold, drawn with the +/// canvas's transparency grid tile and cell size: the first color in the top-left cell. It goes +/// beside the rows that start at `top`, against the right edge, or below them when they leave no +/// room. It shows the grid whatever Simulate Colored Paper and View › Show Transparency Grid are, +/// and changes nothing in the document. +fn grid_preview(app: &VectorcraftApp, ui: &mut egui::Ui, d: &Dialog, top: f32) { + let t = Tokens::get(ui.ctx()); + let fallback = vectorcraft_doc::DocSetup::default(); + let setup = app.session.active().map_or(&fallback, |st| &st.doc.setup); + let (size, colors) = preview_grid(&d.fields, setup); + let right = ui.max_rect().right(); + let rect = if ui.min_rect().right() + 16.0 + GRID_PREVIEW.x <= right { + egui::Rect::from_min_size(egui::pos2(right - GRID_PREVIEW.x, top), GRID_PREVIEW) + } else { + ui.add_space(4.0); + ui.allocate_exact_size(GRID_PREVIEW, egui::Sense::hover()).0 + }; + let resp = ui.interact(rect, grid_preview_id(), egui::Sense::hover()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tl!("Transparency Grid"))); + let display = app.display_profile.transform(app.session.prefs.monitor_profile_display); + let id = egui::Id::unique("document-setup-grid-preview").with(display.is_some()); + let tile = crate::canvas::checker_tile(ui.ctx(), colors, display.as_deref(), id); + let uv = egui::Rect::from_min_max(egui::Pos2::ZERO, (rect.size() / (2.0 * size.cell())).to_pos2()); + ui.painter().image(tile.id(), rect, uv, egui::Color32::WHITE); + ui.painter().rect_stroke(rect, 0.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Outside); +} + +/// The id of the Transparency tab's grid preview. +fn grid_preview_id() -> egui::Id { + egui::Id::unique("grid-preview") } fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { let t = Tokens::get(ui.ctx()); widgets::subheader(ui, tl!("Transparency Grid")); + let top = ui.cursor().top(); let sizes: Vec<(&str, &str)> = GridSize::ALL.iter().map(|g| (g.id(), g.label())).collect(); choice(ui, d, "gridSize", tl!("Grid Size:"), &sizes); // A preset name in the fields (any case, as `document.setup` takes it) becomes the preset's two @@ -196,25 +280,28 @@ fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { 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()))); + d.fields.insert("gridColors".into(), json!(pair.map(|c| grid_color_entry(&c)))); } - let colors = grid_colors(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()))) - .map_or("Custom", |(n, _)| n); + // 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. The + // menu names the preset whose colors the pair is, as `document.setup` names it. + let fallback = vectorcraft_doc::DocSetup::default(); + let setup = app.session.active().map_or(&fallback, |st| &st.doc.setup); + let resolved = grid_colors(&d.fields, setup); + let colors: Vec = resolved.iter().map(vectorcraft_color::Color::to_hex).collect(); + let preset = GRID_COLOR_PRESETS.iter().find(|(_, pair)| *pair == resolved).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| { if let Some((_, pair)) = widgets::dropdown(ui, "gridColors", preset, &names, 220.0).and_then(|i| GRID_COLOR_PRESETS.get(i)) { - d.fields.insert("gridColors".into(), json!(pair.map(|c| c.to_hex()))); + d.fields.insert("gridColors".into(), json!(pair.map(|c| grid_color_entry(&c)))); } }); // The two colours (the first is also the paper colour): editing either makes them Custom. A // click on a color's box, or Space or Enter with the keyboard on it, opens the Color Picker on - // that color (white when its hex is not a color), and the picker's OK sets that color. The - // picker opens after the row, on the color Document Setup holds then: a press on a box ends a - // hex field's editing in the same frame, and that field's edit is the color the picker opens on. - // A hex field's edit replaces its own color in the pair Document Setup holds when it commits. + // that color, and the picker's OK sets that color. The picker opens after the row, on the color + // Document Setup holds then: a press on a box ends a hex field's editing in the same frame, and + // that field's edit is the color the picker opens on. A hex field's edit replaces its own color + // in the pair Document Setup holds when it commits, and the other entry stays as it is. let mut pick = None; widgets::label_row(ui, "", LABEL, |ui| { for i in 0..2 { @@ -242,17 +329,21 @@ fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { ui.painter().rect_stroke(chip.expand(2.0), 3.0, ui.visuals().selection.stroke, egui::StrokeKind::Outside); } if let Some(c) = widgets::hex_field_named(ui, ("grid-color", i), Some(&name), hex).and_then(|h| vectorcraft_color::Color::from_hex(&h)) { - let mut v = grid_colors(d); - v.resize(2, "#ffffff".into()); - v[i] = c.to_hex(); + let mut v = pending_grid_pair(&d.fields).unwrap_or_else(|| grid_colors(&d.fields, setup).iter().map(grid_color_entry).collect()); + v[i] = grid_color_entry(&c); d.fields.insert("gridColors".into(), json!(v)); } ui.add_space(10.0); } }); + grid_preview(app, ui, d, top); if let Some(i) = pick { - let c = grid_colors(d).get(i).and_then(|h| vectorcraft_color::Color::from_hex(h.trim_start_matches('#'))); - *d = super::color_picker::over_list_entry(d, "gridColors", i, c.unwrap_or(vectorcraft_color::Color::WHITE)); + // A field that is not two colors becomes the pair the boxes show when the picker's OK sets + // its entry; its Cancel goes back to the field as it was. + let pair = grid_colors(&d.fields, setup); + let fill = pending_grid_pair(&d.fields).is_none().then(|| json!(pair.map(|c| grid_color_entry(&c)))); + let c = pair.get(i).copied().unwrap_or(vectorcraft_color::Color::WHITE); + *d = super::color_picker::over_list_entry(d, "gridColors", i, c, fill); } ui.add_space(4.0); check(ui, d, "simulatePaper", tl!("Simulate Colored Paper")); @@ -351,7 +442,7 @@ fn color(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { #[cfg(test)] mod tests { use egui::{Event, PointerButton, Pos2, Rect, vec2}; - use serde_json::json; + use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint, cms}; use vectorcraft_doc::{ColorMode, NodeId}; use vectorcraft_engine::Session; @@ -467,6 +558,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] @@ -684,7 +820,7 @@ mod tests { /// 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() + d.fields["gridColors"].as_array().unwrap().iter().map(|c| vectorcraft_engine::cmd::color_value(c).unwrap()).collect() } /// A new document with Document Setup open on its Transparency tab, drawn in the context returned. @@ -783,6 +919,36 @@ mod tests { } } + /// When Grid Colors holds a preset name (in any letter case) or a list that is not two colors, + /// the boxes and hex fields show the preset's pair or the document's, a box opens the Color + /// Picker on its color, and the picker's OK sets only that entry of a two-color list. + #[test] + fn a_grid_color_box_opens_on_a_preset_name_or_a_short_list() { + for (field, index, opens, kept, name) in [ + (json!("Blue"), 1, "#c4dcff", "#ffffff", "Blue"), + (json!("purple"), 0, "#ffffff", "#e2c9ff", "Purple"), + (json!(["#ff0000"]), 1, "#cccccc", "#ffffff", "Light"), + ] { + let (mut app, ctx) = transparency_tab(); + app.ui.dialog.as_mut().unwrap().fields.insert("gridColors".into(), field.clone()); + dialog_frame(&mut app, &ctx, vec![]); + let texts: Vec = dialog_frame(&mut app, &ctx, vec![]).into_iter().map(|(t, _)| t).collect(); + for shown in [name, opens.trim_start_matches('#'), kept.trim_start_matches('#')] { + assert!(texts.iter().any(|t| t.eq_ignore_ascii_case(shown)), "{field}: no {shown} in {texts:?}"); + } + click_grid_box(&mut app, &ctx, index); + assert_picker_over_setup(&app, opens, &field.to_string()); + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#00ff00")); + crate::dialogs::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + let mut pair = [hex(kept); 2]; + pair[index] = hex("#00ff00"); + assert_eq!((d.kind.as_str(), dialog_grid(d)), (super::KIND, pair.to_vec()), "{field}"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.session.active().unwrap().doc.setup.grid_colors, pair, "{field}"); + } + } + /// With a preset name in Document Setup's `gridColors` field, the grid color boxes show the /// preset's colors, and the Color Picker opens on the clicked one; its OK sets that color and /// keeps the preset's other one. @@ -901,9 +1067,9 @@ mod tests { 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); + let mut orphan = crate::dialogs::color_picker::over_list_entry(&setup, "gridColors", 0, Color::WHITE, None); orphan.fields.remove(crate::dialogs::PARENT); - for picker in [crate::dialogs::color_picker::over_list_entry(&short, "gridColors", 1, Color::WHITE), orphan] { + for picker in [crate::dialogs::color_picker::over_list_entry(&short, "gridColors", 1, Color::WHITE, None), 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()); @@ -912,4 +1078,190 @@ mod tests { assert_eq!(app.session.active().unwrap().doc.setup.grid_colors, LIGHT.map(hex)); assert_eq!(undo_steps(&app), 0); } + + /// [`transparency_tab`] on a document whose grid colors `document.setup` set to `grid` first. + fn transparency_tab_on(grid: Value) -> (VectorcraftApp, egui::Context) { + let (mut app, ctx) = transparency_tab(); + app.ui.dialog = None; + app.run("document.setup", json!({"gridColors": grid})).unwrap(); + app.run("file.documentSetup", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("tab".into(), json!("Transparency")); + for _ in 0..4 { + dialog_frame(&mut app, &ctx, vec![]); + } + (app, ctx) + } + + /// Document Setup opens on the document's own grid colors, a Lab color included: the grid + /// preview reads them as the document holds them, and an unchanged OK keeps them. + #[test] + fn document_setup_opens_on_the_documents_own_grid_colors() { + let (mut app, _ctx) = transparency_tab_on(json!(["lab 55 60 40", "#cccccc"])); + let grid = app.session.active().unwrap().doc.setup.grid_colors; + assert!(matches!(grid[0], Color::Lab { .. }), "{grid:?}"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(super::preview_grid(&d.fields, &app.session.active().unwrap().doc.setup).1, grid); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.active().unwrap().doc.setup.grid_colors, grid); + } + + /// A hex field's edit replaces only its own entry of the pair Document Setup holds: the other + /// entry stays as it is, a Lab color in its own model. + #[test] + fn a_grid_color_hex_edit_keeps_the_other_entry_as_it_is() { + let (mut app, ctx) = transparency_tab(); + app.ui.dialog.as_mut().unwrap().fields.insert("gridColors".into(), json!(["lab 55 60 40", "#cccccc"])); + type_into_hex_field(&mut app, &ctx, "cccccc", "123456"); + // A click on the grid preview ends the edit. + let at = ctx.read_response(super::grid_preview_id()).expect("no grid preview").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)]); + dialog_frame(&mut app, &ctx, vec![button(false)]); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["gridColors"], json!(["lab 55 60 40", "#123456"])); + } + + /// The Grid Colors menu names a preset only when the pair is that preset's colors, as + /// `document.setup` names it: a color that rounds to the preset's hex code makes it Custom. + #[test] + fn the_grid_colors_menu_names_a_preset_only_for_its_own_colors() { + let (mut app, ctx) = transparency_tab(); + app.ui.dialog.as_mut().unwrap().fields.insert("gridColors".into(), json!(["#ffffff", [0.801, 0.8, 0.8]])); + 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 == "Custom") && !texts.iter().any(|t| t == "Light"), "{texts:?}"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.session.active().unwrap().doc.setup.grid_colors_name(), "Custom"); + } + + /// With a list in Grid Colors that is not two colors, Cancel in a grid color's Color Picker + /// goes back to that list as it was, and Document Setup's OK still refuses it. + #[test] + fn grid_color_picker_cancel_keeps_a_short_list() { + let (mut app, ctx) = transparency_tab(); + app.ui.dialog.as_mut().unwrap().fields.insert("gridColors".into(), json!(["#ff0000"])); + dialog_frame(&mut app, &ctx, vec![]); + click_grid_box(&mut app, &ctx, 1); + assert_picker_over_setup(&app, LIGHT[1], "short list"); + crate::dialogs::cancel(&mut app); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), &d.fields["gridColors"]), (super::KIND, &json!(["#ff0000"]))); + assert!(crate::dialogs::confirm(&mut app).is_err()); + assert_eq!(app.session.active().unwrap().doc.setup.grid_colors, LIGHT.map(hex)); + } + + /// 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/eps_options.rs b/crates/ui-egui/src/dialogs/eps_options.rs index 0eb1853065..40c5f728f9 100644 --- a/crates/ui-egui/src/dialogs/eps_options.rs +++ b/crates/ui-egui/src/dialogs/eps_options.rs @@ -202,7 +202,7 @@ fn custom_body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> 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); + super::flatten::fields_editor(ui, "eps-flattener", &mut d.fields, &mut o, &unread, &["preserveAlpha", "preserveOverprints"]); if let Err(e) = ¤t { ui.label(egui::RichText::new(e).color(Tokens::get(ui.ctx()).text_dim).size(11.5)); } 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/find_replace.rs b/crates/ui-egui/src/dialogs/find_replace.rs new file mode 100644 index 0000000000..8e229980e6 --- /dev/null +++ b/crates/ui-egui/src/dialogs/find_replace.rs @@ -0,0 +1,387 @@ +//! Edit › Find and Replace…: the Find and Replace With fields, Match Case, Find Whole Word, Search +//! Backwards, Check Hidden Layers and Check Locked Layers, and the Find, Replace, Replace & Find, +//! Replace All and Done buttons, as "Find and replace text" in the public +//! [reference](https://helpx.adobe.com/pdf/illustrator_reference.pdf) describes them. The dialog +//! stays open: Find goes to the next match (`edit.findNext`), Replace changes that match +//! (`edit.replaceMatch`), Replace & Find changes it and goes to the next, and Replace All changes +//! every match (`edit.findReplace`). Each Replace is one undo step, and so is Replace All. +//! +//! These rules are VectorCraft's own. A match is shown in the dialog in its line of text with its +//! place among the matches, and its type object is selected, unless it is on a hidden or locked +//! layer. Enter runs Find. Replace and Replace & Find wait for a match that Find reached with the +//! Find text and the options as they are now. Edit › Find Next goes on from the last search while +//! the dialog is closed, and opens the dialog when there has been none. +//! +//! Fields: `find`, `replace`, `matchCase`, `wholeWord`, `backwards`, `hiddenLayers`, +//! `lockedLayers` and `action` (what `ui.dialog.confirm` does: `find`, `replace`, `replaceFind`, +//! `replaceAll` or `done`; a button sets it and confirms). The dialog keeps the place the search +//! reached in `__at`, the `uid` of its document in `__doc` and the Find text and switches it was +//! reached with in `__atQuery`, the match found in `__found` and the line under the fields in +//! `__note`. A place in a document other than the active one, or reached with other Find text or +//! switches, is not used: the search starts again. + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; + +use super::{DialogAction, DialogSpec, form}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Find and Replace. +pub const KIND: &str = "findReplace"; + +/// The command of its menu item, which Replace All runs. +pub const COMMAND: &str = "edit.findReplace"; + +/// The command Find runs, and Edit › Find Next. +pub const NEXT: &str = "edit.findNext"; + +/// The command Replace runs. +const REPLACE: &str = "edit.replaceMatch"; + +/// The switches that decide what a match is and which type is searched. +const SWITCHES: [&str; 4] = ["matchCase", "wholeWord", "hiddenLayers", "lockedLayers"]; + +/// The place the search reached: `{id, start, end}`, a match or the text that replaced one. +const AT: &str = "__at"; +/// The match Find reached, which Replace changes: `{index, count, query}`, with `query` the Find +/// text and the switches it was found with. +const FOUND: &str = "__found"; +/// The line under the fields, in English: no matches, or how many Replace All replaced. +const NOTE: &str = "__note"; + +/// The characters of a match's line shown on either side of it. +const CONTEXT: usize = 24; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Find and Replace").into(), + body_with_actions: Some(body), + confirm, + ok: None, + min_width: 480.0, + ..DialogSpec::FORM +}; + +/// The document a place in [`AT`] or the last search's `from` belongs to: its `uid`. +const DOC: &str = "__doc"; +/// The Find text and switches the place in [`AT`] was reached with ([`query`]). +const AT_QUERY: &str = "__atQuery"; + +/// The params of the Edit menu's Find and Replace… item: a `find` of null, which gives the dialog +/// no field, so that it opens on the last search. +pub fn menu_params() -> Value { + json!({"find": null}) +} + +/// The `uid` of the active document. +fn active_uid(app: &VectorcraftApp) -> Option { + app.session.active().map(|d| d.uid) +} + +/// Open Find and Replace on the last search when there has been one, with the fields that +/// `params` gives in its place. A null value, such as the menu item's `find` ([`menu_params`]), +/// gives none. A field given a value of another type is an error, and the dialog does not open. +pub fn open(app: &mut VectorcraftApp, params: &Map) -> Result { + let mut fields = Map::new(); + fields.insert("find".into(), json!("")); + fields.insert("replace".into(), json!("")); + for key in SWITCHES.into_iter().chain(["backwards"]) { + fields.insert(key.into(), json!(false)); + } + check_types(params, true)?; + let last = app.ui.last_find.as_ref().and_then(Value::as_object).cloned().unwrap_or_default(); + for (k, v) in last.iter().chain(params) { + // Only the dialog's own fields, each of its own type. + if fields.get(k).is_some_and(|f| f.is_string() == v.is_string() && f.is_boolean() == v.is_boolean()) { + fields.insert(k.clone(), v.clone()); + } + } + // The place the last search reached, while its document is the active one. + let uid = active_uid(app); + if let Some(at) = last.get("from").filter(|v| v.is_object() && uid.is_some() && last.get("doc").and_then(Value::as_u64) == uid) { + fields.insert(AT.into(), at.clone()); + fields.insert(DOC.into(), json!(uid)); + fields.insert(AT_QUERY.into(), query_in(&last)); + } + fields.insert("action".into(), json!("find")); + fields.insert("__command".into(), json!(COMMAND)); + app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); + Ok(Value::Null) +} + +/// The first of the dialog's fields in `fields` that holds a value of another type than its own, +/// as an error: `find` and `replace` are strings, and `backwards` and the [`SWITCHES`] are true or +/// false. A null value is no error when `null_gives_none` is true. +fn check_types(fields: &Map, null_gives_none: bool) -> Result<(), String> { + for (k, v) in fields.iter().filter(|(_, v)| !(null_gives_none && v.is_null())) { + if matches!(k.as_str(), "find" | "replace") && !v.is_string() { + return Err(format!("`{k}` must be a string")); + } + if (k == "backwards" || SWITCHES.contains(&k.as_str())) && !v.is_boolean() { + return Err(format!("`{k}` must be true or false")); + } + } + Ok(()) +} + +/// Edit › Find Next with no text to find: the next match of the last search, from the place it +/// reached, with the options the dialog had. With no search yet, it opens the dialog. +pub fn find_next(app: &mut VectorcraftApp) -> Result { + let Some(mut last) = app.ui.last_find.clone().filter(|l| l.get("find").and_then(Value::as_str).is_some_and(|f| !f.is_empty())) else { + return open(app, &Map::new()); + }; + let uid = active_uid(app); + if let Some(o) = last.as_object_mut() { + o.remove("replace"); + // A place in another document is no place in this one. + if uid.is_none() || o.remove("doc").and_then(|d| d.as_u64()) != uid { + o.remove("from"); + } + } + let r = app.run(NEXT, last)?; + if r["id"].is_null() { + app.status("No matches found"); + return Ok(r); + } + if let Some(l) = app.ui.last_find.as_mut() { + l["from"] = json!({ "id": r["id"], "start": r["start"], "end": r["end"] }); + l["doc"] = json!(uid); + } + Ok(r) +} + +/// The Find text and the switches of [`SWITCHES`]: what a match is, as params. +fn query(d: &Dialog) -> Value { + query_in(&d.fields) +} + +/// [`query`] of the dialog fields, or of the last search, in `fields`. +fn query_in(fields: &Map) -> Value { + let mut q = json!({ "find": fields.get("find").and_then(Value::as_str).unwrap_or_default() }); + for key in SWITCHES { + q[key] = json!(fields.get(key).and_then(Value::as_bool).unwrap_or(false)); + } + q +} + +/// The place the search reached, `{id, start, end}`, while its document is the active one and +/// the Find text and the switches are those it was reached with. +fn place<'a>(app: &VectorcraftApp, d: &'a Dialog) -> Option<&'a Value> { + let uid = active_uid(app)?; + let same = d.fields.get(DOC).and_then(Value::as_u64) == Some(uid) && d.fields.get(AT_QUERY) == Some(&query(d)); + same.then(|| d.fields.get(AT)).flatten().filter(|at| at.is_object()) +} + +/// Keep `at`, a place in the active document, as the place the search reached. +fn set_place(app: &VectorcraftApp, d: &mut Dialog, at: Value) { + d.fields.insert(AT.into(), at); + d.fields.insert(DOC.into(), json!(active_uid(app))); + d.fields.insert(AT_QUERY.into(), query(d)); +} + +/// The match Replace changes, as `{id, start, end}`: the one Find reached in the active document, +/// while the Find text and the switches are as they were when it was found. +fn current_match<'a>(app: &VectorcraftApp, d: &'a Dialog) -> Option<&'a Value> { + let found = d.fields.get(FOUND)?; + (found.get("query") == Some(&query(d))).then(|| place(app, d)).flatten() +} + +/// Keep what the dialog searched for and the place it reached, for Edit › Find Next and for the +/// next time the dialog opens. +fn remember(app: &mut VectorcraftApp, d: &Dialog) { + let mut last = query(d); + last["replace"] = json!(d.str("replace")); + last["backwards"] = json!(d.bool("backwards")); + if let Some(at) = place(app, d) { + last["from"] = at.clone(); + last["doc"] = json!(active_uid(app)); + } + app.ui.last_find = Some(last); +} + +/// Find: the next match after the place the search reached, kept as that place and as the match +/// Replace changes. With no match, the note says so. +fn find(app: &mut VectorcraftApp, d: &mut Dialog) -> Result { + let mut p = query(d); + p["backwards"] = json!(d.bool("backwards")); + // With no place, the search starts at the first match, not after the selected type object. + p["from"] = place(app, d).cloned().unwrap_or(Value::Null); + d.fields.remove(FOUND); + d.fields.remove(NOTE); + let r = app.run(NEXT, p)?; + if r["id"].is_null() { + app.status("No matches found"); + d.fields.insert(NOTE.into(), json!(app.ui.status)); + return Ok(r); + } + set_place(app, d, json!({ "id": r["id"], "start": r["start"], "end": r["end"] })); + d.fields.insert(FOUND.into(), json!({ "index": r["index"], "count": r["count"], "query": query(d) })); + Ok(r) +} + +/// Replace: the match Find reached becomes the Replace With text, and the search goes on from +/// it. With no such match, it finds one. +fn replace(app: &mut VectorcraftApp, d: &mut Dialog) -> Result { + let Some(at) = current_match(app, d).cloned() else { return find(app, d) }; + let mut p = query(d); + for key in ["hiddenLayers", "lockedLayers"] { + if let Some(o) = p.as_object_mut() { + o.remove(key); + } + } + p["replace"] = json!(d.str("replace")); + for key in ["id", "start", "end"] { + p[key] = at[key].clone(); + } + d.fields.remove(FOUND); + d.fields.remove(NOTE); + let r = app.run(REPLACE, p)?; + set_place(app, d, json!({ "id": r["id"], "start": r["start"], "end": r["end"] })); + Ok(r) +} + +/// Replace All: every match becomes the Replace With text, and the note says how many. +fn replace_all(app: &mut VectorcraftApp, d: &mut Dialog) -> Result { + let mut p = query(d); + p["replace"] = json!(d.str("replace")); + d.fields.remove(FOUND); + d.fields.remove(NOTE); + let r = app.run(COMMAND, p)?; + // The matches that changed: those that already read as the Replace With text do not count. + match (r["count"].as_u64().unwrap_or(0), r["replaced"].as_u64().unwrap_or(0)) { + (0, _) => app.status("No matches found"), + (_, n) => app.status(format!("Matches replaced: {n}")), + } + d.fields.insert(NOTE.into(), json!(app.ui.status)); + Ok(r) +} + +/// A button or `ui.dialog.confirm`: run the `action` and keep the dialog open, or close it for +/// `done`. What a command refuses is the note, and the dialog stays open. A field set to a value +/// of another type than its own ([`check_types`]) runs no action: the error is the note, shown +/// under the match found, which Replace still changes once the field is set right. So does an +/// `action` that is not a string. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let mut d = d.clone(); + let action = d.fields.insert("action".into(), json!("find")); + let checked = match &action { + Some(a) if !a.is_string() => Err("`action` must be a string".to_string()), + _ => check_types(&d.fields, false), + }; + if let Err(e) = checked { + d.fields.insert(NOTE.into(), json!(e)); + app.ui.dialog = Some(d); + return Err(e); + } + let r = match action.as_ref().and_then(Value::as_str).unwrap_or_default() { + "done" => { + remember(app, &d); + app.ui.dialog = None; + return Ok(Value::Null); + } + "" | "find" => find(app, &mut d), + "replace" => replace(app, &mut d), + "replaceFind" => match current_match(app, &d) { + Some(_) => replace(app, &mut d).and_then(|_| find(app, &mut d)), + None => find(app, &mut d), + }, + "replaceAll" => replace_all(app, &mut d), + _ => Err("no such action".to_string()), + }; + if let Err(e) = &r { + d.fields.insert(NOTE.into(), json!(e)); + } + remember(app, &d); + app.ui.dialog = Some(d); + r +} + +/// The match Find reached as it reads in its text: (the text before it on its line, the match, +/// the text after it), each at most [`CONTEXT`] characters, and its place among the matches. +fn shown_match(app: &VectorcraftApp, d: &Dialog) -> Option<([String; 3], String)> { + let at = current_match(app, d)?; + let found = d.fields.get(FOUND)?; + let whole = |v: &Value| v.as_u64().and_then(|n| usize::try_from(n).ok()); + let (id, start, end) = (at["id"].as_u64()?, whole(&at["start"])?, whole(&at["end"])?); + let NodeKind::Text(t) = &app.session.active()?.doc.node(NodeId(id))?.kind else { return None }; + let text = t.plain_text(); + let (before, hit, after) = (text.get(..start)?, text.get(start..end)?, text.get(end..)?); + let before = before.rsplit(['\n', '\r']).next().unwrap_or_default(); + let after = after.split(['\n', '\r']).next().unwrap_or_default(); + let skip = before.chars().count().saturating_sub(CONTEXT); + let lead = if skip > 0 { "…" } else { "" }; + let tail = if after.chars().count() > CONTEXT { "…" } else { "" }; + let before = format!("{lead}{}", before.chars().skip(skip).collect::()); + let after = format!("{}{tail}", after.chars().take(CONTEXT).collect::()); + Some(([before, hit.to_string(), after], format!("{} / {}", found["index"], found["count"]))) +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { + let can_find = !d.str("find").is_empty(); + let found = current_match(app, d).is_some(); + let mut action = None; + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + widgets::dim_label(ui, tl!("Find:")); + form::text(ui, d, "find", 320.0); + ui.add_space(6.0); + widgets::dim_label(ui, tl!("Replace With:")); + form::text(ui, d, "replace", 320.0); + ui.add_space(10.0); + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + form::check(ui, d, "matchCase", "Match Case"); + form::check(ui, d, "wholeWord", "Find Whole Word"); + form::check(ui, d, "backwards", "Search Backwards"); + }); + ui.add_space(16.0); + ui.vertical(|ui| { + form::check(ui, d, "hiddenLayers", "Check Hidden Layers"); + form::check(ui, d, "lockedLayers", "Check Locked Layers"); + }); + }); + }); + ui.add_space(16.0); + ui.vertical(|ui| { + let mut button = |ui: &mut egui::Ui, label: &str, enabled: bool, name: &'static str| { + if ui.add_enabled_ui(enabled, |ui| widgets::flat_button(ui, label, 130.0).clicked()).inner { + action = Some(name); + } + ui.add_space(6.0); + }; + button(ui, if found { tl!("Find Next") } else { tl!("Find") }, can_find, "find"); + button(ui, tl!("Replace"), can_find && found, "replace"); + button(ui, tl!("Replace & Find"), can_find && found, "replaceFind"); + button(ui, tl!("Replace All"), can_find, "replaceAll"); + button(ui, tl!("Done"), true, "done"); + }); + }); + ui.add_space(8.0); + if let Some(([before, hit, after], place)) = shown_match(app, d) { + let t = crate::theme::Tokens::get(ui.ctx()); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + widgets::dim_name(ui, &format!("{place} {before}")); + ui.colored_label(t.text_strong, egui::RichText::new(hit).strong().underline()); + widgets::dim_name(ui, &after); + }); + } + // Find and Replace remove the note, so it shows under a match only when an action was refused. + if let Some(note) = d.fields.get(NOTE).and_then(Value::as_str) { + widgets::dim_name(ui, &crate::i18n::message(crate::i18n::current(), note)); + } + // Enter finds, as the Find button does. + if action.is_none() && can_find && crate::shortcuts::pressed_anew(ui.ctx(), egui::Key::Enter) { + action = Some("find"); + } + match action { + Some(name) => { + d.fields.insert("action".into(), json!(name)); + DialogAction::Confirm + } + None => DialogAction::None, + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/dialogs/find_replace/tests.rs b/crates/ui-egui/src/dialogs/find_replace/tests.rs new file mode 100644 index 0000000000..1f2bb756ab --- /dev/null +++ b/crates/ui-egui/src/dialogs/find_replace/tests.rs @@ -0,0 +1,458 @@ +use egui::{Event, PointerButton, Pos2, Rect, vec2}; +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; + +use crate::VectorcraftApp; + +/// An app on a document holding point type `texts`, bottom first, with nothing selected → the +/// app and the type objects' ids. +fn app_with(texts: &[&str]) -> (VectorcraftApp, Vec) { + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let ids = texts.iter().map(|t| s.execute("text.create", &json!({"x": 50, "y": 50, "text": t})).unwrap()["id"].as_u64().unwrap()).collect(); + s.execute("select.none", &json!({})).unwrap(); + (VectorcraftApp::new(s, crate::Services::default()), ids) +} + +/// Choose Edit › Find and Replace…, as a click on the menu item does. +fn choose(app: &mut VectorcraftApp) { + let (id, p) = crate::shortcut_editor::menu_target(super::COMMAND).expect("the menu item gives params"); + crate::menus::invoke(app, &id, p); +} + +/// Choose Edit › Find Next, as a click on the menu item does. +fn choose_find_next(app: &mut VectorcraftApp) { + let e = crate::menus::menu_entries(app).into_iter().find(|e| e.label == "Find Next").expect("in the Edit menu"); + assert_eq!((e.command.as_deref(), e.enabled), (Some(super::NEXT), true)); + crate::menus::invoke(app, super::NEXT, json!({"find": ""})); +} + +fn set(app: &mut VectorcraftApp, k: &str, v: Value) { + app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v); +} + +fn field(app: &VectorcraftApp, k: &str) -> Value { + app.ui.dialog.as_ref().expect("the dialog is open").fields.get(k).cloned().unwrap_or(Value::Null) +} + +/// The match Replace would change, as (object, start, end). +fn matched(app: &VectorcraftApp) -> Option<(u64, u64, u64)> { + let at = super::current_match(app, app.ui.dialog.as_ref()?)?; + Some((at["id"].as_u64()?, at["start"].as_u64()?, at["end"].as_u64()?)) +} + +fn plain(app: &VectorcraftApp, id: u64) -> String { + match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("not type"), + } +} + +fn undo_steps(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() +} + +fn selected(app: &VectorcraftApp) -> Vec { + app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect() +} + +/// One frame of the dialog on an 800 × 600 window → the text painted, with its rect. +fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec<(String, Rect)> { + // A window takes a sizing frame and fades in: each frame is a quarter second on. + let time = ctx.input(|i| i.time) + 0.25; + let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))); + let raw = egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| crate::dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + fn walk(s: &egui::Shape, v: &mut Vec<(String, Rect)>) { + match s { + egui::Shape::Text(t) => v.push((t.galley.text().to_string(), Rect::from_min_size(t.pos, t.galley.size()))), + egui::Shape::Vec(s) => s.iter().for_each(|s| walk(s, v)), + _ => {} + } + } + let mut v = vec![]; + out.shapes.iter().for_each(|c| walk(&c.shape, &mut v)); + v +} + +fn context() -> egui::Context { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx +} + +fn click(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) -> Vec<(String, Rect)> { + frame(app, ctx, vec![]); + let texts = frame(app, ctx, vec![]); + let at = texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, ctx, vec![Event::PointerMoved(at)]); + frame(app, ctx, vec![press(true)]); + frame(app, ctx, vec![press(false)]); + frame(app, ctx, vec![]) +} + +/// Edit › Find and Replace… opens the dialog of its own, with the fields and options of the +/// public reference's "Find and replace text", instead of the generic parameter dialog. +#[test] +fn the_edit_menu_opens_the_find_and_replace_dialog() { + let (mut app, _) = app_with(&["cat"]); + let e = crate::menus::menu_entries(&app).into_iter().find(|e| e.label == "Find and Replace…").expect("in the Edit menu"); + assert_eq!((e.path.as_slice(), e.command.as_deref(), e.enabled), (&["Edit".to_string()][..], Some(super::COMMAND), true)); + choose(&mut app); + let d = app.ui.dialog.as_ref().expect("Find and Replace opens"); + assert_eq!((d.kind.as_str(), d.fields["__command"].clone()), (super::KIND, json!(super::COMMAND))); + for (key, want) in [("find", json!("")), ("replace", json!("")), ("action", json!("find"))] { + assert_eq!(d.fields[key], want, "{key}"); + } + for key in ["matchCase", "wholeWord", "backwards", "hiddenLayers", "lockedLayers"] { + assert_eq!(d.fields[key], json!(false), "{key}"); + } + let ctx = context(); + frame(&mut app, &ctx, vec![]); + let texts: Vec = frame(&mut app, &ctx, vec![]).into_iter().map(|(t, _)| t).collect(); + for label in [ + "Find and Replace", + "Find:", + "Replace With:", + "Match Case", + "Find Whole Word", + "Search Backwards", + "Check Hidden Layers", + "Check Locked Layers", + "Find", + "Replace", + "Replace & Find", + "Replace All", + "Done", + ] { + assert!(texts.iter().any(|t| t == label), "no `{label}` in {texts:?}"); + } +} + +/// A field given a value of another type than its own is an error and the dialog does not open; a +/// null value gives no field. A field set to such a value once the dialog is open runs no action: +/// the error is the note, shown under the match found, and the text, the match and the last search +/// stay as they were. +#[test] +fn the_dialog_rejects_a_field_of_the_wrong_type() { + let (mut app, ids) = app_with(&["cat"]); + choose(&mut app); + set(&mut app, "find", json!("cat")); + crate::dialogs::confirm(&mut app).unwrap(); + let last = app.ui.last_find.clone(); + for (k, v, want) in [ + ("replace", json!(5), "`replace` must be a string"), + ("replace", Value::Null, "`replace` must be a string"), + ("matchCase", json!("yes"), "`matchCase` must be true or false"), + ] { + set(&mut app, k, v.clone()); + set(&mut app, "action", json!("replaceAll")); + assert_eq!(crate::dialogs::confirm(&mut app).unwrap_err(), want, "{k}: {v}"); + assert_eq!((plain(&app, ids[0]), field(&app, "__note"), app.ui.last_find.clone()), ("cat".to_string(), json!(want), last.clone())); + assert_eq!(matched(&app), Some((ids[0], 0, 3)), "Replace still changes the match found"); + let ctx = context(); + frame(&mut app, &ctx, vec![]); + let texts: Vec = frame(&mut app, &ctx, vec![]).into_iter().map(|(t, _)| t).collect(); + assert!(texts.iter().any(|t| t == want) && texts.iter().any(|t| t == "cat"), "the note shows under the match: {texts:?}"); + set(&mut app, k, if k == "replace" { json!("dog") } else { json!(false) }); + } + set(&mut app, "action", json!("done")); + crate::dialogs::confirm(&mut app).unwrap(); + let open = |app: &mut VectorcraftApp, params: Value| app.run("ui.paramDialog", json!({"command": super::COMMAND, "params": params})); + for (params, want) in [ + (json!({"find": 17}), "`find` must be a string"), + (json!({"replace": true}), "`replace` must be a string"), + (json!({"matchCase": "yes"}), "`matchCase` must be true or false"), + (json!({"backwards": 1}), "`backwards` must be true or false"), + ] { + assert_eq!(open(&mut app, params.clone()).unwrap_err(), want, "{params}"); + assert!(app.ui.dialog.is_none(), "{params}"); + } + open(&mut app, json!({"find": null, "replace": "dog", "wholeWord": true})).unwrap(); + assert_eq!((field(&app, "find"), field(&app, "replace"), field(&app, "wholeWord")), (json!("cat"), json!("dog"), json!(true))); +} + +/// An `action` that is not a string runs no action, Find included: the error is the note, and the +/// match found, the selection and the last search stay as they were. +#[test] +fn an_action_of_the_wrong_type_runs_no_action() { + let (mut app, _) = app_with(&["cat", "cat"]); + choose(&mut app); + set(&mut app, "find", json!("cat")); + crate::dialogs::confirm(&mut app).unwrap(); + let (at, sel, last) = (matched(&app), selected(&app), app.ui.last_find.clone()); + assert!(at.is_some()); + for v in [json!(5), Value::Null, json!(["find"])] { + set(&mut app, "action", v.clone()); + assert_eq!(crate::dialogs::confirm(&mut app).unwrap_err(), "`action` must be a string", "{v}"); + assert_eq!((matched(&app), selected(&app), app.ui.last_find.clone()), (at, sel.clone(), last.clone()), "{v}"); + assert_eq!(field(&app, "__note"), json!("`action` must be a string"), "{v}"); + } + set(&mut app, "action", json!("find")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_ne!(matched(&app), at, "a string action still runs"); +} + +/// Find with other Find text starts again at the first match, the matches in the type object the +/// last Find selected included. +#[test] +fn find_with_other_text_starts_at_the_first_match() { + let (mut app, ids) = app_with(&["dog", "cat dog"]); + let (bottom, top) = (ids[0], ids[1]); + choose(&mut app); + set(&mut app, "find", json!("cat")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((matched(&app), selected(&app)), (Some((top, 0, 3)), vec![top])); + set(&mut app, "find", json!("dog")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((matched(&app), selected(&app)), (Some((top, 4, 7)), vec![top])); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((bottom, 0, 3))); +} + +/// The dialog stays open from match to match: Find goes to the next match and selects its +/// object, Replace changes that match, Replace & Find changes it and goes on, Replace All changes +/// the rest, and Done closes. Each Replace is one undo step, and so is Replace All; finding and a +/// Replace All with nothing to replace record none. +#[test] +fn the_buttons_step_through_the_matches() { + let (mut app, ids) = app_with(&["cat cat", "a cat"]); + let (bottom, top) = (ids[0], ids[1]); + choose(&mut app); + let ctx = context(); + set(&mut app, "find", json!("cat")); + set(&mut app, "replace", json!("dog")); + let steps = undo_steps(&app); + // Find: the first match, in the top object, shown with its place and its line of text. + let texts = click(&mut app, &ctx, "Find"); + assert_eq!((matched(&app), selected(&app), undo_steps(&app)), (Some((top, 2, 5)), vec![top], steps)); + assert!(texts.iter().any(|(t, _)| t.starts_with("1 / 3")) && texts.iter().any(|(t, _)| t == "cat"), "{texts:?}"); + assert!(texts.iter().any(|(t, _)| t == "Find Next"), "Find reads Find Next once a match is found: {texts:?}"); + // Replace: that match only, and the search stays where it was. + click(&mut app, &ctx, "Replace"); + assert_eq!((plain(&app, top), plain(&app, bottom), undo_steps(&app)), ("a dog".to_string(), "cat cat".to_string(), steps + 1)); + assert_eq!((matched(&app), field(&app, "__at")), (None, json!({"id": top, "start": 2, "end": 5}))); + // Find goes on from there, to the bottom object. + click(&mut app, &ctx, "Find"); + assert_eq!((matched(&app), selected(&app), field(&app, "__found")["count"].clone()), (Some((bottom, 0, 3)), vec![bottom], json!(2))); + // Replace & Find: one undo step, and the next match is the one left. + click(&mut app, &ctx, "Replace & Find"); + assert_eq!((plain(&app, bottom), undo_steps(&app), matched(&app)), ("dog cat".to_string(), steps + 2, Some((bottom, 4, 7)))); + // Replace All: the rest as one undo step, with the count under the fields. + let texts = click(&mut app, &ctx, "Replace All"); + assert_eq!((plain(&app, bottom), undo_steps(&app), matched(&app)), ("dog dog".to_string(), steps + 3, None)); + assert!(texts.iter().any(|(t, _)| t == "Matches replaced: 1"), "{texts:?}"); + // Nothing left: no undo step, and the dialog says so, for Replace All and for Find. + for button in ["Replace All", "Find"] { + let texts = click(&mut app, &ctx, button); + assert_eq!((undo_steps(&app), matched(&app)), (steps + 3, None), "{button}"); + assert!(texts.iter().any(|(t, _)| t == "No matches found"), "{button}: {texts:?}"); + } + assert!(app.ui.dialog.is_some(), "the dialog stays open until Done"); + click(&mut app, &ctx, "Done"); + assert!(app.ui.dialog.is_none(), "Done closes it"); + assert_eq!(undo_steps(&app), steps + 3); +} + +/// Replace and Replace & Find wait for a match found with the Find text and the options as they +/// are: before the first Find, and after the Find text changes, a click on them changes nothing. +/// With no Find text, no button but Done acts. Enter runs Find. +#[test] +fn replace_waits_for_a_match_of_the_text_as_it_is() { + let (mut app, ids) = app_with(&["cat cart"]); + choose(&mut app); + let ctx = context(); + let steps = undo_steps(&app); + set(&mut app, "replace", json!("x")); + for button in ["Find", "Replace", "Replace & Find", "Replace All"] { + click(&mut app, &ctx, button); + assert_eq!((plain(&app, ids[0]), undo_steps(&app), matched(&app)), ("cat cart".to_string(), steps, None), "{button} with no Find text"); + } + set(&mut app, "find", json!("cat")); + for button in ["Replace", "Replace & Find"] { + click(&mut app, &ctx, button); + assert_eq!((plain(&app, ids[0]), undo_steps(&app), matched(&app)), ("cat cart".to_string(), steps, None), "{button} before Find"); + } + // Enter finds. + frame(&mut app, &ctx, vec![]); + let enter = |pressed| Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![enter(true)]); + frame(&mut app, &ctx, vec![enter(false)]); + assert_eq!(matched(&app), Some((ids[0], 0, 3))); + // The Find text changes: the match found is no longer the one to replace. + set(&mut app, "find", json!("ca")); + assert_eq!(matched(&app), None); + for button in ["Replace", "Replace & Find"] { + click(&mut app, &ctx, button); + assert_eq!((plain(&app, ids[0]), undo_steps(&app)), ("cat cart".to_string(), steps), "{button} after the Find text changed"); + } + // An option changes: the same. + set(&mut app, "find", json!("cat")); + assert_eq!(matched(&app), Some((ids[0], 0, 3))); + set(&mut app, "matchCase", json!(true)); + assert_eq!(matched(&app), None); + // Search Backwards is a direction, not what a match is. + set(&mut app, "matchCase", json!(false)); + set(&mut app, "backwards", json!(true)); + assert_eq!(matched(&app), Some((ids[0], 0, 3))); + click(&mut app, &ctx, "Replace"); + assert_eq!((plain(&app, ids[0]), undo_steps(&app)), ("x cart".to_string(), steps + 1)); +} + +/// `ui.dialog.confirm` runs the dialog's `action`, keeps it open and puts `action` back to find; +/// done closes it. An action it does not know is refused, and so is an empty Find text. +#[test] +fn confirm_runs_the_action() { + let (mut app, ids) = app_with(&["cat cat cat"]); + choose(&mut app); + set(&mut app, "find", json!("cat")); + set(&mut app, "replace", json!("dog")); + let steps = undo_steps(&app); + let r = crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((r["start"].clone(), r["index"].clone(), r["count"].clone(), matched(&app)), (json!(0), json!(1), json!(3), Some((ids[0], 0, 3)))); + set(&mut app, "action", json!("replaceFind")); + let r = crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((plain(&app, ids[0]), r["start"].clone(), field(&app, "action")), ("dog cat cat".to_string(), json!(4), json!("find"))); + set(&mut app, "action", json!("replace")); + let r = crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((plain(&app, ids[0]), r["replaced"].clone(), matched(&app)), ("dog dog cat".to_string(), json!(true), None)); + // Replace with no match found: it finds one. + set(&mut app, "action", json!("replace")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((plain(&app, ids[0]), matched(&app), undo_steps(&app)), ("dog dog cat".to_string(), Some((ids[0], 8, 11)), steps + 2)); + set(&mut app, "action", json!("replaceAll")); + assert_eq!(crate::dialogs::confirm(&mut app).unwrap(), json!({"count": 1, "replaced": 1})); + assert_eq!((plain(&app, ids[0]), undo_steps(&app)), ("dog dog dog".to_string(), steps + 3)); + // Matches that already read as the Replace With text are found and not counted as replaced. + set(&mut app, "find", json!("DOG")); + set(&mut app, "action", json!("replaceAll")); + assert_eq!(crate::dialogs::confirm(&mut app).unwrap(), json!({"count": 3, "replaced": 0})); + assert_eq!((undo_steps(&app), field(&app, "__note")), (steps + 3, json!("Matches replaced: 0"))); + set(&mut app, "find", json!("dog")); + for (action, find) in [("erase", "dog"), ("find", ""), ("replaceAll", "")] { + set(&mut app, "action", json!(action)); + set(&mut app, "find", json!(find)); + assert!(crate::dialogs::confirm(&mut app).is_err(), "{action} {find:?}"); + assert_eq!((plain(&app, ids[0]), undo_steps(&app), field(&app, "action")), ("dog dog dog".to_string(), steps + 3, json!("find"))); + assert!(field(&app, "__note").is_string(), "{action} {find:?}: the dialog shows why"); + } + set(&mut app, "action", json!("done")); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); +} + +/// Edit › Find Next goes on from the dialog's last search while the dialog is closed, with its +/// options, and says when nothing matches. With no search yet, it opens the dialog, and the +/// dialog opens again on the last search. +#[test] +fn find_next_goes_on_from_the_last_search() { + let (mut app, ids) = app_with(&["Cat", "cat", "cat"]); + choose_find_next(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(super::KIND), "no search yet: the dialog opens"); + set(&mut app, "find", json!("cat")); + set(&mut app, "replace", json!("dog")); + set(&mut app, "matchCase", json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((ids[2], 0, 3))); + set(&mut app, "action", json!("done")); + crate::dialogs::confirm(&mut app).unwrap(); + let steps = undo_steps(&app); + // On from the match the dialog found; Match Case still leaves out "Cat". + for want in [ids[1], ids[2], ids[1]] { + choose_find_next(&mut app); + assert_eq!((selected(&app), app.ui.dialog.is_none(), undo_steps(&app)), (vec![want], true, steps)); + } + // The dialog opens on the last search and the place it reached. + choose(&mut app); + assert_eq!((field(&app, "find"), field(&app, "replace"), field(&app, "matchCase")), (json!("cat"), json!("dog"), json!(true))); + assert_eq!(field(&app, "__at"), json!({"id": ids[1], "start": 0, "end": 3})); + set(&mut app, "find", json!("zebra")); + assert!(crate::dialogs::confirm(&mut app).unwrap()["id"].is_null()); + set(&mut app, "action", json!("done")); + crate::dialogs::confirm(&mut app).unwrap(); + app.ui.status.clear(); + choose_find_next(&mut app); + assert_eq!((app.ui.status.as_str(), selected(&app)), ("No matches found", vec![ids[1]])); +} + +/// The place a search reached goes with the Find text and the switches it was reached with: a +/// search for other text starts again, in the dialog and when `ui.paramDialog` gives other text, +/// and the same search goes on from that place. +#[test] +fn a_changed_search_starts_again() { + let (mut app, ids) = app_with(&["cat dog cat", "dog"]); + let (bottom, top) = (ids[0], ids[1]); + choose(&mut app); + set(&mut app, "find", json!("cat")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((bottom, 0, 3))); + set(&mut app, "find", json!("dog")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((top, 0, 3)), "not the dog after the cat found"); + set(&mut app, "find", json!("cat")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((bottom, 0, 3))); + set(&mut app, "action", json!("done")); + crate::dialogs::confirm(&mut app).unwrap(); + crate::menus::invoke(&mut app, "ui.paramDialog", json!({"command": super::COMMAND, "params": {"find": "dog"}})); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((top, 0, 3))); + app.ui.dialog = None; + choose(&mut app); + assert_eq!(field(&app, "find"), json!("dog")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((bottom, 4, 7)), "the same search goes on"); +} + +/// The place a search reached belongs to its document: in another document, Edit › Find Next and +/// the dialog start at that document's first match, even where an object there has the same id. +/// The params of a `ui.paramDialog` call take the place of the last search's, a switch that is off +/// included, while the menu item's own params leave the last search as it was. +#[test] +fn a_search_place_stays_in_its_document_and_given_params_win() { + let (mut app, ids) = app_with(&["cat cat"]); + choose(&mut app); + set(&mut app, "find", json!("cat")); + set(&mut app, "matchCase", json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((ids[0], 0, 3))); + set(&mut app, "action", json!("done")); + crate::dialogs::confirm(&mut app).unwrap(); + // A second document, whose type object has the id of the first one's. + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + let other = app.run("text.create", json!({"x": 50, "y": 50, "text": "cat cat"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.none", json!({})).unwrap(); + assert_eq!(other, ids[0]); + choose_find_next(&mut app); + assert_eq!( + (selected(&app), app.ui.last_find.as_ref().map(|l| l["from"].clone())), + (vec![other], Some(json!({"id": other, "start": 0, "end": 3}))) + ); + // The dialog opens on the last search; Find goes on in this document. + choose(&mut app); + assert_eq!(field(&app, "matchCase"), json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(matched(&app), Some((other, 4, 7))); + // Back in the first document, the dialog's place is not used: Replace finds first and changes + // nothing. + assert!(app.session.set_active(0)); + assert_eq!(matched(&app), None); + set(&mut app, "replace", json!("dog")); + set(&mut app, "action", json!("replace")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!((plain(&app, ids[0]), matched(&app)), ("cat cat".to_string(), Some((ids[0], 0, 3)))); + set(&mut app, "action", json!("done")); + crate::dialogs::confirm(&mut app).unwrap(); + // Given params win over the last search; the menu item's own do not. + crate::menus::invoke(&mut app, "ui.paramDialog", json!({"command": super::COMMAND, "params": {"matchCase": false, "replace": "dog"}})); + assert_eq!((field(&app, "find"), field(&app, "matchCase"), field(&app, "replace")), (json!("cat"), json!(false), json!("dog"))); + app.ui.dialog = None; + let empty = json!({"find": "", "replace": "", "matchCase": false, "wholeWord": false}); + crate::menus::invoke(&mut app, "ui.paramDialog", json!({"command": super::COMMAND, "params": empty})); + assert_eq!((field(&app, "find"), field(&app, "matchCase")), (json!(""), json!(false))); + app.ui.dialog = None; + choose(&mut app); + assert_eq!((field(&app, "find"), field(&app, "matchCase")), (json!("cat"), json!(true))); +} diff --git a/crates/ui-egui/src/dialogs/flare_options.rs b/crates/ui-egui/src/dialogs/flare_options.rs index 5b6834d46e..8c5cbcf5fc 100644 --- a/crates/ui-egui/src/dialogs/flare_options.rs +++ b/crates/ui-egui/src/dialogs/flare_options.rs @@ -5,18 +5,22 @@ //! grid shows). While Alt (Option on macOS) is held, Cancel reads Reset, which puts every option //! back to the tool's default and leaves the dialog open (`ui.dialogReset`). A click-opened //! dialog previews its settings live; Reset refreshes that preview and Cancel rolls it back. +//! Opened from the toolbar with flares selected, it shows the first one's settings, and OK draws +//! the selected flares again with the settings changed in the dialog (`shape.editFlare`); the tool +//! keeps its options. //! //! Fields: the options (`vectorcraft_tools::extra::FLARE_OPTIONS`): `diameter` and `pathLength` //! (points), `opacity`, `brightness`, `growth`, `fuzziness`, `longest`, `rayFuzziness` and -//! `largest` (%), `rays` and `rings` (counts), `direction` (degrees); `raysOn` and `ringsOn`; and -//! `x`, `y` where a click opened it, with `preview` on initially for that click. +//! `largest` (%), `rays` and `rings` (counts), `direction` (degrees); `raysOn` and `ringsOn`; +//! `x`, `y` where a click opened it, with `preview` on initially for that click; and `flares` +//! (ids) with `shown` (the settings the dialog opened with) for the selected flares. use serde_json::{Map, Value, json}; use vectorcraft_geom::Point; use vectorcraft_tools::extra::{FLARE_OPTIONS, flare_params}; use super::document_setup::check; -use super::{DialogResult, DialogSpec, form, set_tool_options_and_close}; +use super::{DialogResult, DialogSpec, form, run_and_close, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -38,7 +42,8 @@ const LABEL_W: f32 = 78.0; const FIELD_W: f32 = 90.0; /// Open the Flare Tool Options with the tool's values; `at`: where a click opened them, to draw a -/// flare there on OK. +/// flare there on OK. Opened without a click while flares are selected, they show the first one's +/// settings, to change the selected flares on OK. pub fn open(app: &mut VectorcraftApp, at: Option) -> Value { let mut fields = match app.session.tool_options_of("flare") { Value::Object(o) => o, @@ -48,11 +53,79 @@ pub fn open(app: &mut VectorcraftApp, at: Option) -> Value { fields.insert("preview".into(), json!(true)); fields.insert("x".into(), json!(p.x)); fields.insert("y".into(), json!(p.y)); + } else if let Some((ids, settings)) = selected_flares(app) { + // A flare without rays or rings shows that checkbox off, with the tool's count. + for (key, on) in [("rays", "raysOn"), ("rings", "ringsOn")] { + let n = settings.get(key).and_then(Value::as_f64).unwrap_or(0.0); + fields.insert(on.into(), json!(n > 0.0)); + if n > 0.0 { + fields.insert(key.into(), json!(n)); + } + } + for (key, ..) in FLARE_OPTIONS.iter().filter(|(k, ..)| !matches!(*k, "rays" | "rings")) { + if let Some(v) = settings.get(*key) { + fields.insert(key.to_string(), v.clone()); + } + } + fields.insert("shown".into(), Value::Object(shown(&fields))); + fields.insert("flares".into(), json!(ids)); } app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); json!({ "dialog": KIND }) } +/// The selected flares that can be edited (ids) and the first one's settings as the dialog shows +/// them: its rings' path length and direction from its center to its end point, where the flare is +/// drawn now. +fn selected_flares(app: &VectorcraftApp) -> Option<(Vec, Map)> { + let st = app.session.doc().ok()?; + let flares: Vec<_> = st + .selection + .objects + .iter() + .filter(|id| st.doc.is_editable(**id)) + .filter_map(|id| vectorcraft_engine::flare_settings(&st.doc, *id).map(|spec| (id.0, spec))) + .collect(); + let (_, first) = flares.first()?; + let Value::Object(mut settings) = first.params.clone() else { return None }; + let d = first.end()? - first.center()?; + settings.insert("pathLength".into(), json!(d.hypot())); + // Counter-clockwise from 3 o'clock, 0° to 360°, as `shape.flare` takes it. + settings.insert("direction".into(), json!((-d.y).atan2(d.x).to_degrees().rem_euclid(360.0))); + Some((flares.iter().map(|(id, _)| *id).collect(), settings)) +} + +/// The settings `fields` give a flare: each option, with a count of 0 when its checkbox is off. +fn shown(fields: &Map) -> Map { + let get = |key: &str, default: f64| fields.get(key).and_then(Value::as_f64).unwrap_or(default); + let on = |key: &str| fields.get(key).and_then(Value::as_bool) != Some(false); + FLARE_OPTIONS + .iter() + .map(|&(key, default, ..)| { + let v = match key { + "rays" if !on("raysOn") => 0.0, + "rings" if !on("ringsOn") => 0.0, + "rays" | "rings" => get(key, default).round(), + _ => get(key, default), + }; + (key.to_string(), json!(v)) + }) + .collect() +} + +/// `shape.editFlare`'s params for the selected flares: the settings changed since the dialog opened. +fn edit_params(d: &Dialog) -> Option { + let ids = d.fields.get("flares")?.clone(); + let start = d.fields.get("shown").and_then(Value::as_object).cloned().unwrap_or_default(); + let mut params = json!({ "ids": ids }); + for (key, v) in shown(&d.fields) { + if start.get(&key) != Some(&v) { + params[key.as_str()] = if matches!(key.as_str(), "rays" | "rings") { json!(v.as_f64().unwrap_or(0.0) as u64) } else { v }; + } + } + Some(params) +} + /// A row for option `key`, kept within its range: a distance in `unit`, else a number. fn field(ui: &mut egui::Ui, d: &mut Dialog, unit: vectorcraft_doc::Unit, (key, label): (&str, &str)) { let Some(&(_, default, lo, hi)) = FLARE_OPTIONS.iter().find(|(k, ..)| *k == key) else { return }; @@ -119,8 +192,12 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// A click-created flare previews at that original click; toolbar options draw no artwork. +/// A click-created flare previews at that original click, and the selected flares preview with the +/// settings changed; toolbar options draw no artwork. fn preview_command(app: &VectorcraftApp, d: &Dialog) -> Option<(String, Value)> { + if let Some(params) = edit_params(d) { + return Some(("shape.editFlare".into(), params)); + } let at = Point::new(d.fields.get("x")?.as_f64().filter(|v| v.is_finite())?, d.fields.get("y")?.as_f64().filter(|v| v.is_finite())?); // Use the same clamping and whole-count conversion as accepted tool settings. let mut tool = vectorcraft_tools::create("flare"); @@ -143,8 +220,16 @@ fn reset(_: &VectorcraftApp, d: &mut Dialog) -> Result<(), String> { Ok(()) } -/// OK: set the tool's options; opened by a click, draw a flare there with them. +/// OK: set the tool's options; opened by a click, draw a flare there with them. Opened for the +/// selected flares, draw them again with the settings changed, leaving the tool's options. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { + if let Some(params) = edit_params(d) { + return if d.fields.contains_key(form::PREVIEWED) { + form::commit_preview(app, "shape.editFlare", params) + } else { + run_and_close(app, "shape.editFlare", params) + }; + } let command = preview_command(app, d); if command.is_none() && (d.fields.contains_key("x") || d.fields.contains_key("y") || d.fields.contains_key(form::PREVIEWED)) { return Err("Flare click coordinates must be finite numbers".into()); @@ -321,6 +406,41 @@ mod tests { assert_eq!(app.session.tool_options_of("flare"), before); } + /// With a flare selected, the toolbar's Flare Tool Options show its settings, and OK draws it + /// again with the settings changed, as one undo step, leaving the tool's options. + #[test] + fn with_a_flare_selected_the_options_show_its_settings_and_ok_draws_it_again() { + let mut app = app(); + let flare = json!({"cx": 200, "cy": 200, "diameter": 60, "rays": 0, "rings": 4, "x2": 200, "y2": 0, "largest": 80, "seed": 5}); + app.run("shape.flare", flare).unwrap(); + app.run("object.move", json!({"dx": 30, "dy": 0})).unwrap(); + let options = app.session.tool_options_of("flare"); + app.run("tool.options", json!({"tool": "flare"})).unwrap(); + painted(&mut app); + let d = app.ui.dialog.as_mut().unwrap(); + let shown = (d.f64("diameter", 0.0), d.bool("raysOn"), d.f64("rays", 0.0), d.f64("rings", 0.0), d.f64("largest", 0.0)); + assert_eq!(shown, (60.0, false, 15.0, 4.0, 80.0)); + assert!((d.f64("pathLength", 0.0) - 200.0).abs() < 1e-9 && (d.f64("direction", 0.0) - 90.0).abs() < 1e-9); + d.fields.insert("rings".into(), json!(7)); + d.fields.insert("raysOn".into(), json!(true)); + let depth = app.session.doc().unwrap().history.undo.len(); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), depth + 1); + let parts = flare_parts(&app); + assert_eq!((parts.iter().filter(|p| *p == "Ring").count(), parts.iter().any(|p| p == "Rays")), (7, true), "{parts:?}"); + // Still where it was moved to. + let doc = &app.session.doc().unwrap().doc; + let id = app.session.doc().unwrap().selection.objects[0]; + assert!(vectorcraft_engine::flare_settings(doc, id).unwrap().center().unwrap().distance(Point::new(230.0, 200.0)) < 1e-9); + assert_eq!(app.session.tool_options_of("flare"), options); + // With nothing selected, the dialog shows the tool's options again. + app.run("select.none", json!({})).unwrap(); + app.run("tool.options", json!({"tool": "flare"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.f64("diameter", 0.0), d.fields.contains_key("flares")), (100.0, false)); + } + #[test] fn ui_dialog_reset_puts_the_defaults_back_and_keeps_where_a_click_opened_it() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/flatten.rs b/crates/ui-egui/src/dialogs/flatten.rs index a22631c8e2..456145bfc6 100644 --- a/crates/ui-egui/src/dialogs/flatten.rs +++ b/crates/ui-egui/src/dialogs/flatten.rs @@ -76,17 +76,10 @@ pub(crate) fn shown_options(fields: &Map, current: &Result, - o: &mut FlattenOptions, - unread: &[String], - fixed_preserve: bool, -) { - let set = editor(ui, id, o, true, fixed_preserve, unread); +/// so that it replaces a value of the wrong type; the other fields stay as they were entered. The +/// switches of the options named in `fixed` 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: &[&str]) { + let set = editor(ui, id, o, true, fixed, unread); let Ok(Value::Object(m)) = serde_json::to_value(&*o) else { return }; for k in set { if let Some(v) = m.get(k) { @@ -150,7 +143,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.add_space(10.0); // 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); + fields_editor(ui, "flatten-dialog", &mut d.fields, &mut o, &unread, &[]); if let Err(e) = ¤t { ui.label(egui::RichText::new(e).color(Tokens::get(ui.ctx()).text_dim).size(11.5)); } @@ -227,15 +220,15 @@ const FIELD: f32 = 56.0; /// when one changed. pub(crate) fn options_editor(ui: &mut egui::Ui, id: &str, o: &mut FlattenOptions, enabled: bool) -> bool { let before = o.clone(); - editor(ui, id, o, enabled, false, &[]); + editor(ui, id, o, enabled, &[], &[]); *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> { +/// The option controls, with the value fields of the options named in `unread` blank. The +/// switches of the options named in `fixed` 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: &[&str], 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); @@ -289,16 +282,16 @@ fn editor(ui: &mut egui::Ui, id: &str, o: &mut FlattenOptions, enabled: bool, fi } }); ui.add_space(4.0); - 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"), + let switches: [(&str, &mut bool, &'static str); 6] = [ + (tl!("Convert All Text to Outlines"), &mut o.text_to_outlines, "textToOutlines"), + (tl!("Convert All Strokes to Outlines"), &mut o.strokes_to_outlines, "strokesToOutlines"), + (tl!("Clip Complex Regions"), &mut o.clip_complex_regions, "clipComplexRegions"), + (tl!("Anti-alias Rasters"), &mut o.anti_alias, "antiAlias"), + (tl!("Preserve Alpha Transparency"), &mut o.preserve_alpha, "preserveAlpha"), + (tl!("Preserve Overprints and Spot Colors"), &mut o.preserve_overprints, "preserveOverprints"), ]; - for (label, v, fixed, key) in switches { - if widgets::check(ui, label, *v, enabled && !fixed) { + for (label, v, key) in switches { + if widgets::check(ui, label, *v, enabled && !fixed.contains(&key)) { *v = !*v; set.push(key); } diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index b46f35a79f..f19cd18cda 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -847,6 +847,7 @@ pub(crate) fn humanize(k: &str) -> String { "Traps With Process Color" => "Traps with Process Color:".into(), "Cols" => "Columns:".into(), "Flip Cols" => "Flip Columns:".into(), + "Each" => "One per Object:".into(), _ => format!("{s}:"), } } diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index 78fdd8bdd1..aa793afef2 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -280,6 +280,7 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { variation: (0.0, 100.0), }; varied(ui, d, &roundness, &Variation::ALL); + tip_preview(ui, d, roundness.range.0); size_rows(ui, d, &Variation::ALL); } else { if d.fields.contains_key("angle") { @@ -291,7 +292,7 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } } if d.str("tool") == "blobBrush" { - blob_tip_preview(ui, d); + tip_preview(ui, d, 0.0); } // The Eraser's Size rows are above. if !eraser && d.fields.contains_key("sizeMode") { @@ -331,26 +332,26 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// Side of the Blob Brush tip preview's square, in points. +/// Side of the Blob Brush's and the Eraser's tip preview square, in points. const TIP_PREVIEW: f32 = 64.0; -/// Half the length of the Blob Brush tip in its preview, in points. +/// Half the length of the tip in its preview, in points. const TIP_LONG: f32 = 18.0; /// How far from a Roundness dot of the tip preview a press still takes the dot, in points. const TIP_DOT_REACH: f32 = 8.0; -/// The Blob Brush's tip preview: a square with the tip at its Angle and Roundness, a line with an -/// arrowhead along its long axis and a black dot at each end of its short axis, and beside it three -/// dabs of the tip, the middle one darker. A click or a drag that starts on a dot sets the -/// Roundness from the pointer's distance from the center along the short axis -/// ([`blob_tip_roundness_at`]) until the release, inside the square or out of it, and gives the +/// The Blob Brush's and the Eraser's tip preview: a square with the tip at its Angle and +/// Roundness, a line with an arrowhead along its long axis and a black dot at each end of its short +/// axis, and beside it three dabs of the tip, the middle one darker. A click or a drag that starts +/// on a dot sets the Roundness from the pointer's distance from the center along the short axis +/// ([`tip_roundness_at`]) until the release, inside the square or out of it, and gives the /// Roundness slider the keyboard focus. A click or a drag that starts anywhere else in the square /// points the Angle at the pointer and gives the Angle slider the focus. Screen readers get the /// square as the Angle slider and then the Roundness slider, and their keys step the Angle within -/// -180° to 180° and the Roundness within 0% to 100% as a dialog slider's do +/// -180° to 180° and the Roundness within `min_roundness` to 100% as a dialog slider's do /// ([`widgets::stepped_area`]). -fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { +fn tip_preview(ui: &mut egui::Ui, d: &mut Dialog, min_roundness: f64) { let t = Tokens::get(ui.ctx()); let (rect, _) = ui.allocate_exact_size(egui::vec2(CONTENT_W, TIP_PREVIEW), egui::Sense::hover()); let square = egui::Rect::from_min_size(rect.min, egui::vec2(TIP_PREVIEW, TIP_PREVIEW)); @@ -359,7 +360,7 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { // Whether the press that started this click or drag was on a dot: it is kept until the release. let on_dot = response.id.with("on-dot"); let near_dot = |p: egui::Pos2, d: &Dialog| { - blob_tip_dots(center, d.f64("angle", 0.0), d.f64("roundness", 100.0)).iter().any(|dot| dot.distance(p) <= TIP_DOT_REACH) + tip_dots(center, d.f64("angle", 0.0), d.f64("roundness", 100.0)).iter().any(|dot| dot.distance(p) <= TIP_DOT_REACH) }; let mut started = ui.data(|m| m.get_temp::(on_dot)); if started.is_none() && response.is_pointer_button_down_on() { @@ -383,7 +384,7 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { if let Some((p, _)) = widgets::pointer_phase(&response) { let delta = p - center; if dot_drag { - d.fields.insert("roundness".into(), json!(blob_tip_roundness_at(delta, d.f64("angle", 0.0)))); + d.fields.insert("roundness".into(), json!(tip_roundness_at(delta, d.f64("angle", 0.0), min_roundness))); } else if delta.length_sq() > 1.0 { d.fields.insert("angle".into(), json!(f64::from((-delta.y).atan2(delta.x)).to_degrees().round())); } @@ -406,13 +407,13 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { if dot_drag && (response.drag_started() || response.clicked()) { widgets::focus_by_pointer(ui, roundness.id); } - let shown = widgets::SliderValue::field(d.f64("roundness", 100.0), 0.0..=100.0, "%", 0); + let shown = widgets::SliderValue::field(d.f64("roundness", 100.0), min_roundness..=100.0, "%", 0); if let Some(r) = widgets::stepped_area(ui, &roundness, tl!("Roundness"), Some(shown)) { d.fields.insert("roundness".into(), json!(r)); } - let (u, v) = blob_tip_axes(d.f64("angle", 0.0)); + let (u, v) = tip_axes(d.f64("angle", 0.0)); let long = TIP_LONG; - let short = long * blob_tip_short_ratio(d.f64("roundness", 100.0)); + let short = long * tip_short_ratio(d.f64("roundness", 100.0)); let dab = |center: egui::Pos2, color: egui::Color32| { let points = (0..32) .map(|i| { @@ -427,7 +428,7 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { let arrowhead = vec![center + u * 28.0, center + u * 22.0 + v * 3.0, center + u * 22.0 - v * 3.0]; painter.add(egui::Shape::convex_polygon(arrowhead, t.accent, egui::Stroke::NONE)); // Black with a white rim, so a dot shows on the tip and on the square in either theme. - for dot in blob_tip_dots(center, d.f64("angle", 0.0), d.f64("roundness", 100.0)) { + for dot in tip_dots(center, d.f64("angle", 0.0), d.f64("roundness", 100.0)) { painter.circle(dot, 3.0, egui::Color32::BLACK, egui::Stroke::new(1.0, egui::Color32::WHITE)); } let strip = square.right() + 2.5 * long; @@ -438,7 +439,7 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { /// The tip preview's long axis on screen at Angle `angle` (degrees, y down: a positive angle tilts /// it up to the right), and its short axis. -fn blob_tip_axes(angle: f64) -> (egui::Vec2, egui::Vec2) { +fn tip_axes(angle: f64) -> (egui::Vec2, egui::Vec2) { let a = angle.clamp(-180.0, 180.0).to_radians(); let u = egui::vec2(a.cos() as f32, -a.sin() as f32); (u, egui::vec2(-u.y, u.x)) @@ -446,23 +447,23 @@ fn blob_tip_axes(angle: f64) -> (egui::Vec2, egui::Vec2) { /// The two Roundness dots of the tip preview centered on `center`: the ends of the tip's short /// axis at Angle `angle` and Roundness `roundness`. -fn blob_tip_dots(center: egui::Pos2, angle: f64, roundness: f64) -> [egui::Pos2; 2] { - let (_, v) = blob_tip_axes(angle); - let short = v * (TIP_LONG * blob_tip_short_ratio(roundness)); +fn tip_dots(center: egui::Pos2, angle: f64, roundness: f64) -> [egui::Pos2; 2] { + let (_, v) = tip_axes(angle); + let short = v * (TIP_LONG * tip_short_ratio(roundness)); [center + short, center - short] } -/// The Roundness, in whole percent from 0 to 100, that a dot of the tip preview dragged to `offset` -/// from the preview's center gives at Angle `angle`: the distance along the tip's short axis, on -/// either side of the center, as a percentage of half the tip's length. -fn blob_tip_roundness_at(offset: egui::Vec2, angle: f64) -> f64 { - let (_, v) = blob_tip_axes(angle); - (f64::from(offset.dot(v).abs() / TIP_LONG) * 100.0).round().clamp(0.0, 100.0) +/// The Roundness, in whole percent from `min` to 100, that a dot of the tip preview dragged to +/// `offset` from the preview's center gives at Angle `angle`: the distance along the tip's short +/// axis, on either side of the center, as a percentage of half the tip's length. +fn tip_roundness_at(offset: egui::Vec2, angle: f64, min: f64) -> f64 { + let (_, v) = tip_axes(angle); + (f64::from(offset.dot(v).abs() / TIP_LONG) * 100.0).round().clamp(min, 100.0) } /// The preview tip's short axis as a fraction of its long axis: Roundness in percent, with 0 -/// percent drawn as 0.1 percent, the minimum the brush draws with. -fn blob_tip_short_ratio(roundness: f64) -> f32 { +/// percent drawn as 0.1 percent, the minimum the Blob Brush draws with. +fn tip_short_ratio(roundness: f64) -> f32 { (roundness.clamp(0.0, 100.0) as f32 / 100.0).max(0.001) } diff --git a/crates/ui-egui/src/dialogs/freehand/tests.rs b/crates/ui-egui/src/dialogs/freehand/tests.rs index 6ec010a8bd..e324bbbd45 100644 --- a/crates/ui-egui/src/dialogs/freehand/tests.rs +++ b/crates/ui-egui/src/dialogs/freehand/tests.rs @@ -50,7 +50,12 @@ fn a_refused_fidelity_keeps_the_dialog_open() { fn the_tip_preview_is_as_flat_as_the_tip_the_brush_draws() { for roundness in [-5.0, 0.0, 0.05, 0.1, 1.0, 50.0, 100.0, 120.0] { let drawn = vectorcraft_tools::draw2::blob_tip(0.0, roundness).as_coeffs()[3] as f32; - assert!((blob_tip_short_ratio(roundness) - drawn).abs() < 1e-6, "roundness {roundness}: drawn {drawn}"); + assert!((tip_short_ratio(roundness) - drawn).abs() < 1e-6, "roundness {roundness}: drawn {drawn}"); + } + // The Eraser's Roundness runs from 1% to 100%, where its tip and the Blob Brush's are the same. + for roundness in [1.0, 2.0, 50.0, 100.0] { + let drawn = vectorcraft_tools::draw2::eraser_tip(0.0, roundness).as_coeffs()[3] as f32; + assert!((tip_short_ratio(roundness) - drawn).abs() < 1e-6, "Eraser roundness {roundness}: drawn {drawn}"); } } @@ -61,23 +66,35 @@ fn the_tip_preview_is_as_flat_as_the_tip_the_brush_draws() { #[test] fn a_roundness_dot_sets_its_distance_along_the_short_axis() { for angle in [0.0, 30.0, 90.0, -135.0, 180.0] { - let (u, v) = blob_tip_axes(angle); + let (u, v) = tip_axes(angle); for (along, want) in [(0.0, 0.0), (4.5, 25.0), (-9.0, 50.0), (18.0, 100.0), (-18.0, 100.0), (40.0, 100.0), (-400.0, 100.0)] { for sideways in [0.0, 7.0, -30.0] { - assert_eq!(blob_tip_roundness_at(v * along + u * sideways, angle), want, "angle {angle}, {along} along, {sideways} sideways"); + assert_eq!(tip_roundness_at(v * along + u * sideways, angle, 0.0), want, "angle {angle}, {along} along, {sideways} sideways"); } } let center = egui::pos2(32.0, 32.0); for roundness in [0.0, 1.0, 37.0, 50.0, 99.0, 100.0] { - let [a, b] = blob_tip_dots(center, angle, roundness); + let [a, b] = tip_dots(center, angle, roundness); assert!(((a - center) + (b - center)).length() < 1e-4, "the dots face each other across the center"); for dot in [a, b] { - assert_eq!(blob_tip_roundness_at(dot - center, angle), roundness, "angle {angle}"); + assert_eq!(tip_roundness_at(dot - center, angle, 0.0), roundness, "angle {angle}"); } } } } +/// With the Eraser's 1% minimum, a Roundness dot dragged to the center or near it gives 1%, and +/// any farther distance gives the same Roundness as with no minimum. +#[test] +fn a_roundness_dot_keeps_the_eraser_at_one_percent_or_more() { + for angle in [0.0, 45.0, -90.0] { + let (u, v) = tip_axes(angle); + for (along, want) in [(0.0, 1.0), (0.05, 1.0), (-0.1, 1.0), (0.18, 1.0), (0.36, 2.0), (-9.0, 50.0), (30.0, 100.0)] { + assert_eq!(tip_roundness_at(v * along + u * 5.0, angle, 1.0), want, "angle {angle}, {along} along"); + } + } +} + /// The labels the open dialog paints. fn painted(app: &mut VectorcraftApp) -> String { crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) diff --git a/crates/ui-egui/src/dialogs/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 bedd3387c2..5be31baebd 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -297,7 +297,11 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { }; match r { Ok(()) => { - app.ui.dialog = None; + // Opening may have asked something else (the profile of the document); only this + // dialog closes. + if app.ui.dialog.as_ref().is_some_and(|x| x.kind == KIND) { + app.ui.dialog = None; + } Ok(Value::Null) } Err(e) => { diff --git a/crates/ui-egui/src/dialogs/kinsoku_sets.rs b/crates/ui-egui/src/dialogs/kinsoku_sets.rs new file mode 100644 index 0000000000..2f67d199ab --- /dev/null +++ b/crates/ui-egui/src/dialogs/kinsoku_sets.rs @@ -0,0 +1,361 @@ +//! Type › Kinsoku Shori Settings… (with Show East Asian Options): the active document's custom +//! Kinsoku Shori sets, the one picked in Kinsoku shown with its four categories: Cannot Start Line, +//! Cannot End Line, Hanging Punctuation and Inseparable Characters. New adds a set based on Hard, +//! Soft, None or a set of the dialog, Delete takes the one picked out, and Add puts the character +//! of a Unicode code point into a category. Nothing changes in the document until OK, +//! which runs `type.kinsokuSets.set` with every set as one undo step; Cancel leaves them as they were. +//! +//! Fields: `__doc` (the uid of the document the dialog opened on, which OK sets the sets of), +//! `__opened` (the names of that document's sets when the dialog opened; OK keeps the sets the +//! document gained since, after the dialog's own), `sets` (the sets as `type.kinsokuSets.set` takes them, each with the name it had in the +//! document as `from`), `selected` (the index of the one picked), `name`, `cannotStart`, +//! `cannotEnd`, `hanging` and `inseparable` (its name and categories as typed, the inseparable +//! sequences separated by spaces), `base` (what New starts from), `code` (the code point Add +//! adds), `into` (the category it adds to) and `shown` (the set the name and category fields +//! were filled from). When `sets` or `selected` is changed so the picked set is no longer `shown`, +//! the fields are filled from the picked set again and what was typed in them is dropped. +//! +//! Behavior reference: the help page +//! . + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::KinsokuSet; + +use super::{DialogSpec, form}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Kinsoku Shori Settings. +pub const KIND: &str = "kinsokuSets"; + +/// The command OK runs, and the menu item's. +pub const COMMAND: &str = vectorcraft_engine::cmd::kinsokusets::SET; + +/// The field that holds the uid of the document whose sets the dialog shows (`ui.dialog.set` +/// refuses `__` fields). +const DOC: &str = "__doc"; + +/// The field that holds the names of the document's sets when the dialog opened: OK keeps the +/// sets the document gained since, which the dialog does not list. +const OPENED: &str = "__opened"; + +/// The categories, as the command's keys, in the order the dialog shows them. +const CATEGORIES: [&str; 4] = ["cannotStart", "cannotEnd", "hanging", "inseparable"]; + +pub(super) const SPEC: DialogSpec = + DialogSpec { heading: |_| tl!("Kinsoku Shori Settings").into(), body, confirm, min_width: 560.0, ..DialogSpec::FORM }; + +/// Open Kinsoku Shori Settings on the active document's custom sets, the first one picked. +pub fn open(app: &mut VectorcraftApp) -> Result { + let st = app.session.active().ok_or("no document open")?; + let uid = st.uid; + let sets: Vec = st.doc.kinsoku_sets.iter().map(listed).collect(); + let opened: Vec<&str> = st.doc.kinsoku_sets.iter().map(|k| k.name.as_str()).collect(); + let mut d = + Dialog::new(KIND, json!({ DOC: uid, OPENED: opened, "sets": sets, "selected": 0, "base": "hard", "into": "cannotStart", "code": "" })); + show_selected(&mut d); + app.ui.dialog = Some(d); + Ok(Value::Null) +} + +/// A set of the document as the dialog lists it: as `type.kinsokuSets.set` takes it, with its name +/// in the document as `from`. +fn listed(k: &KinsokuSet) -> Value { + let mut v = json!(k); + if let Some(o) = v.as_object_mut() { + o.insert("from".into(), json!(k.name)); + } + v +} + +/// The sets the dialog holds, as the command takes them. +fn sets(d: &Dialog) -> Vec> { + d.fields.get("sets").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_object().cloned()).collect()).unwrap_or_default() +} + +/// Is the `sets` field a list of sets? One that is not (set with `ui.dialog.set`) is kept as it is: +/// no frame or button replaces it, and OK sends it to the command, which refuses it. +fn holds_sets(d: &Dialog) -> bool { + d.fields.get("sets").and_then(Value::as_array).is_some_and(|a| a.iter().all(Value::is_object)) +} + +fn put_sets(d: &mut Dialog, sets: &[Map]) { + d.fields.insert("sets".into(), json!(sets)); +} + +fn name_of(set: &Map) -> &str { + set.get("name").and_then(Value::as_str).unwrap_or_default() +} + +/// The index of the set picked, within the sets (0 when there are none). +fn selected(d: &Dialog, count: usize) -> usize { + d.fields.get("selected").and_then(Value::as_u64).map_or(0, |i| i as usize).min(count.saturating_sub(1)) +} + +/// Pick set `i`: its name and categories go into the fields. +fn select(d: &mut Dialog, i: usize) { + d.fields.insert("selected".into(), json!(i)); + show_selected(d); +} + +fn show_selected(d: &mut Dialog) { + let list = sets(d); + let set = list.get(selected(d, list.len())).cloned().unwrap_or_default(); + d.fields.insert("name".into(), json!(name_of(&set))); + for key in CATEGORIES { + let text = match set.get(key) { + Some(Value::Array(seqs)) => seqs.iter().filter_map(Value::as_str).collect::>().join(" "), + Some(Value::String(s)) => s.clone(), + _ => String::new(), + }; + d.fields.insert(key.into(), json!(text)); + } + d.fields.insert("shown".into(), Value::Object(set)); +} + +/// Do the name and category fields describe the set picked, `set`? +fn shows(d: &Dialog, set: &Map) -> bool { + d.fields.get("shown").and_then(Value::as_object) == Some(set) +} + +/// The set picked with the name and categories as typed: space characters are left out of the +/// single-character categories, and the inseparable sequences are the words of their field. +fn take_fields(d: &Dialog, set: &mut Map) { + set.insert("name".into(), json!(d.str("name"))); + for key in CATEGORIES { + let text = d.str(key); + let v = if key == "inseparable" { + json!(text.split_whitespace().collect::>()) + } else { + json!(text.chars().filter(|c| !c.is_whitespace()).collect::()) + }; + set.insert(key.into(), v); + } +} + +/// "Kinsoku Set N", the first N that no set in `sets` and no set of the document (`doc`) is named. +/// A set Delete took out keeps its name out of New's, so OK gives its paragraphs Hard instead of +/// the new set's characters. +fn new_name(sets: &[Map], doc: &[KinsokuSet]) -> String { + let taken = |n: &str| sets.iter().any(|s| KinsokuSet::same_name(name_of(s), n)) || doc.iter().any(|k| KinsokuSet::same_name(&k.name, n)); + (1..).map(|n| format!("Kinsoku Set {n}")).find(|n| !taken(n)).unwrap_or_default() +} + +/// The character `code` names: `U+3001`, `u+3001` or `3001`, in hexadecimal. +fn code_char(code: &str) -> Option { + let t = code.trim(); + let hex = t.strip_prefix("U+").or_else(|| t.strip_prefix("u+")).unwrap_or(t); + u32::from_str_radix(hex, 16).ok().and_then(char::from_u32).filter(|c| !c.is_control() && !c.is_whitespace()) +} + +/// What a button asked for, done once the fields are drawn. +enum Action { + New, + Delete, + Add, +} + +/// New's starting points: the built-in sets, then the dialog's own. +fn bases(list: &[Map]) -> Vec<(String, String)> { + let mut v = vec![ + (tl!("Hard").to_string(), "hard".to_string()), + (tl!("Soft").to_string(), "soft".to_string()), + (tl!("None").to_string(), "none".to_string()), + ]; + v.extend(list.iter().map(|s| (name_of(s).to_string(), name_of(s).to_string()))); + v +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let mut list = sets(d); + let i = selected(d, list.len()); + if list.get(i).is_some_and(|set| !shows(d, set)) { + show_selected(d); + } + let mut act = None; + let mut picked = None; + let names: Vec = list.iter().map(|s| name_of(s).to_string()).collect(); + let names: Vec<&str> = names.iter().map(String::as_str).collect(); + let bases = bases(&list); + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Kinsoku Set")); + if names.is_empty() { + widgets::dim_label(ui, tl!("None")); + } else if let Some(k) = widgets::dropdown_names(ui, "kinsoku-sets-set", names.get(i).copied().unwrap_or_default(), &names, 200.0) { + picked = Some(k); + } + ui.add_space(8.0); + ui.spacing_mut().item_spacing.x = 4.0; + if widgets::flat_button(ui, tl!("New"), 48.0).clicked() { + act = Some(Action::New); + } + widgets::dim_label(ui, tl!("Based on:")); + let base = d.str("base"); + let shown = bases.iter().find(|b| b.1 == base).map_or(base.as_str(), |b| b.0.as_str()); + let base_names: Vec<&str> = bases.iter().map(|b| b.0.as_str()).collect(); + if let Some(k) = widgets::dropdown_names(ui, "kinsoku-sets-base", shown, &base_names, 120.0) + && let Some(b) = bases.get(k) + { + d.fields.insert("base".into(), json!(b.1)); + } + if ui.add_enabled_ui(!list.is_empty(), |ui| widgets::flat_button(ui, tl!("Delete"), 56.0)).inner.clicked() { + act = Some(Action::Delete); + } + }); + if let Some(k) = picked { + select(d, k); + return false; + } + ui.add_space(8.0); + if let Some(set) = list.get_mut(i) { + egui::Grid::new("kinsoku-sets-fields").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| { + widgets::dim_label(ui, tl!("Name:")); + form::text(ui, d, "name", 260.0); + ui.end_row(); + for (key, label) in [ + ("cannotStart", tl!("Cannot Start Line")), + ("cannotEnd", tl!("Cannot End Line")), + ("hanging", tl!("Hanging Punctuation")), + ("inseparable", tl!("Inseparable Characters")), + ] { + widgets::dim_label(ui, label); + form::text_area(ui, d, key, 380.0, 2); + ui.end_row(); + } + }); + ui.add_space(8.0); + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Unicode")); + form::text(ui, d, "code", 80.0); + let into = d.str("into"); + let targets = [("cannotStart", tl!("Cannot Start Line")), ("cannotEnd", tl!("Cannot End Line")), ("hanging", tl!("Hanging Punctuation"))]; + let shown = targets.iter().find(|t| t.0 == into).map_or("", |t| t.1); + if let Some(k) = widgets::dropdown_names(ui, "kinsoku-sets-into", shown, &targets.map(|t| t.1), 160.0) + && let Some(t) = targets.get(k) + { + d.fields.insert("into".into(), json!(t.0)); + } + if ui.add_enabled_ui(code_char(&d.str("code")).is_some(), |ui| widgets::flat_button(ui, tl!("Add"), 48.0)).inner.clicked() { + act = Some(Action::Add); + } + }); + let was = name_of(set).to_string(); + take_fields(d, set); + // Based on follows the set it names through a rename. + if d.str("base") == was && name_of(set) != was { + let now = name_of(set).to_string(); + d.fields.insert("base".into(), json!(now)); + } + d.fields.insert("shown".into(), Value::Object(set.clone())); + } + if holds_sets(d) { + put_sets(d, &list); + } + if let Some(a) = act + && let Err(e) = run(app, d, a) + { + app.status(e); + } + false +} + +/// Do what button `act` asks for on the dialog's sets. +fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action) -> Result<(), String> { + if !holds_sets(d) { + return Err("the sets must be a list of Kinsoku sets".into()); + } + let mut list = sets(d); + let i = selected(d, list.len()); + match act { + Action::New => { + let base = d.str("base"); + let mut set = match list.iter().find(|s| name_of(s) == base) { + Some(s) => s.clone(), + None => { + let r = app.run("type.kinsokuSets.base", json!({ "base": base }))?; + r["set"].as_object().cloned().ok_or("no Kinsoku set to base the new one on")? + } + }; + set.remove("from"); + let uid = d.fields.get(DOC).and_then(Value::as_u64); + let doc = app.session.documents().iter().find(|t| Some(t.uid) == uid).map(|t| t.doc.kinsoku_sets.to_vec()).unwrap_or_default(); + set.insert("name".into(), json!(new_name(&list, &doc))); + list.push(set); + put_sets(d, &list); + select(d, list.len() - 1); + } + Action::Delete => { + if i < list.len() { + let gone = name_of(&list[i]).to_string(); + list.remove(i); + if d.str("base") == gone { + d.fields.insert("base".into(), json!("hard")); + } + } + put_sets(d, &list); + select(d, i.min(list.len().saturating_sub(1))); + } + Action::Add => { + let c = code_char(&d.str("code")).ok_or("give a character's Unicode code point, as U+3001")?; + let into = d.str("into"); + let key = if CATEGORIES.contains(&into.as_str()) && into != "inseparable" { into } else { "cannotStart".into() }; + let mut text = d.str(&key); + if !text.contains(c) { + text.push(c); + } + d.fields.insert(key, json!(text)); + d.fields.insert("code".into(), json!("")); + if let Some(set) = list.get_mut(i) { + take_fields(d, set); + d.fields.insert("shown".into(), Value::Object(set.clone())); + } + put_sets(d, &list); + } + } + Ok(()) +} + +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + // The fields as typed, also when they were set (`ui.dialog.set`) with no frame drawn since, + // while they still describe the set picked. + let mut list = sets(d); + let i = selected(d, list.len()); + if let Some(set) = list.get_mut(i) + && shows(d, set) + { + take_fields(d, set); + } + // The sets go to the document the dialog opened on, also when another tab is active by now; a + // document closed since closes the dialog and changes nothing. + let uid = d.fields.get(DOC).and_then(Value::as_u64); + if app.session.active().map(|st| st.uid) != uid { + let Some(index) = app.session.documents().iter().position(|doc| Some(doc.uid) == uid) else { + app.ui.dialog = None; + return Err("that document is no longer open".into()); + }; + app.run("document.activate", json!({ "index": index }))?; + } + // A `sets` field that is not a list of sets goes to the command as it is, which refuses it. + let sets = if holds_sets(d) { + // A set the document gained while the dialog was open (a script, another command) is + // kept, after the dialog's sets. + let opened: Vec<&str> = + d.fields.get(OPENED).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); + if let Some(st) = app.session.active() { + list.extend(st.doc.kinsoku_sets.iter().filter(|k| !opened.contains(&k.name.as_str())).filter_map(|k| listed(k).as_object().cloned())); + } + json!(list) + } else { + d.fields.get("sets").cloned().unwrap_or(Value::Null) + }; + let r = app.run(COMMAND, json!({ "sets": sets })); + // A name two sets share, a reserved name or a category too long keeps the dialog open to be + // changed, with its document active. + if r.is_ok() { + app.ui.dialog = None; + } + r +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs b/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs new file mode 100644 index 0000000000..1b3ddd9520 --- /dev/null +++ b/crates/ui-egui/src/dialogs/kinsoku_sets/tests.rs @@ -0,0 +1,308 @@ +use serde_json::json; +use vectorcraft_engine::Session; + +use super::*; + +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app +} + +fn frame(app: &mut VectorcraftApp) { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); +} + +fn dialog(app: &mut VectorcraftApp) -> &mut Dialog { + app.ui.dialog.as_mut().expect("Kinsoku Shori Settings open") +} + +fn doc_sets(app: &VectorcraftApp) -> Vec { + app.session.active().unwrap().doc.kinsoku_sets.to_vec() +} + +fn steps(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() +} + +/// Do `act` with the dialog as it is, as its button does. +fn press(app: &mut VectorcraftApp, act: Action) { + let mut d = app.ui.dialog.clone().unwrap(); + run(app, &mut d, act).unwrap(); + app.ui.dialog = Some(d); +} + +/// Type › Kinsoku Shori Settings… opens on the document's sets; New adds one based on Hard, its +/// categories edited in their fields and Add putting in a character by its code point; nothing +/// changes until OK, which sets them as one undo step; Cancel leaves them. +#[test] +fn kinsoku_sets_change_on_ok_as_one_undo_step() { + let mut app = app(); + crate::menus::invoke(&mut app, COMMAND, json!({})); + assert_eq!(dialog(&mut app).kind, KIND); + frame(&mut app); + press(&mut app, Action::New); + frame(&mut app); + let d = dialog(&mut app); + assert_eq!(d.str("name"), "Kinsoku Set 1"); + assert!(d.str("cannotStart").contains('ー'), "based on Hard"); + d.fields.insert("name".into(), json!("UI Tight")); + d.fields.insert("cannotEnd".into(), json!("「 (")); + d.fields.insert("inseparable".into(), json!("あい ——")); + d.fields.insert("code".into(), json!("U+FF5D")); + d.fields.insert("into".into(), json!("cannotEnd")); + frame(&mut app); + press(&mut app, Action::Add); + assert_eq!(dialog(&mut app).str("cannotEnd"), "「 (}"); + frame(&mut app); + assert!(doc_sets(&app).is_empty()); + let before = steps(&app); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + let sets = doc_sets(&app); + assert_eq!(sets.len(), 1); + assert_eq!((sets[0].name.as_str(), sets[0].cannot_end.clone()), ("UI Tight", vec!['「', '(', '}'])); + assert_eq!(sets[0].inseparable, ["——", "あい"]); + assert_eq!(steps(&app), before + 1); + // OK with nothing changed adds no step; Cancel leaves the sets. + open(&mut app).unwrap(); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + assert_eq!(steps(&app), before + 1); + open(&mut app).unwrap(); + press(&mut app, Action::Delete); + super::super::cancel(&mut app); + assert_eq!(doc_sets(&app).len(), 1); + // Renamed in the dialog, the set keeps its paragraphs; Delete and OK takes it out. + let id = app.run("text.create", json!({"x": 10, "y": 50, "text": "あいう"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("text.setFormat", json!({"kinsoku": "UI Tight"})).unwrap(); + open(&mut app).unwrap(); + dialog(&mut app).fields.insert("name".into(), json!("UI Strict")); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + let para = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.para_at(0).clone(), + _ => panic!("not text"), + }; + assert_eq!(para(&app).kinsoku_name(), "UI Strict"); + open(&mut app).unwrap(); + press(&mut app, Action::Delete); + assert_eq!(dialog(&mut app).str("name"), ""); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + assert!(doc_sets(&app).is_empty()); + assert_eq!(para(&app).kinsoku_name(), "Hard"); +} + +/// New is based on the choice in Based on, the dialog's own sets included, and takes the next free +/// name; a name two sets share, a built-in name or one left empty keeps the dialog open and changes +/// nothing. +#[test] +fn shared_reserved_or_empty_names_keep_the_dialog_open() { + let mut app = app(); + open(&mut app).unwrap(); + dialog(&mut app).fields.insert("base".into(), json!("none")); + press(&mut app, Action::New); + assert_eq!(dialog(&mut app).str("cannotStart"), ""); + dialog(&mut app).fields.insert("cannotStart".into(), json!("ゝ")); + frame(&mut app); + dialog(&mut app).fields.insert("base".into(), json!("Kinsoku Set 1")); + press(&mut app, Action::New); + let d = dialog(&mut app); + assert_eq!((d.str("name"), d.str("cannotStart")), ("Kinsoku Set 2".to_string(), "ゝ".to_string())); + for bad in ["kinsoku set 1", " ", "Soft"] { + dialog(&mut app).fields.insert("name".into(), json!(bad)); + frame(&mut app); + assert!(super::super::confirm(&mut app).is_err(), "{bad:?}"); + assert!(app.ui.dialog.is_some()); + assert!(doc_sets(&app).is_empty()); + } + dialog(&mut app).fields.insert("name".into(), json!("UI Loose")); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + assert_eq!(doc_sets(&app).iter().map(|k| k.name.as_str()).collect::>(), ["Kinsoku Set 1", "UI Loose"]); +} + +/// Based on follows a set of the dialog through a rename, so New starts from that set's +/// characters as edited, not from the document's copy under its old name. +#[test] +fn based_on_follows_a_renamed_set() { + let mut app = app(); + app.run("type.kinsokuSets.set", json!({"sets": [{"name": "Doc Set", "cannotStart": "ゝ"}]})).unwrap(); + open(&mut app).unwrap(); + dialog(&mut app).fields.insert("base".into(), json!("Doc Set")); + frame(&mut app); + let d = dialog(&mut app); + d.fields.insert("cannotStart".into(), json!("ゞ")); + d.fields.insert("name".into(), json!("Renamed")); + frame(&mut app); + assert_eq!(dialog(&mut app).str("base"), "Renamed"); + press(&mut app, Action::New); + let d = dialog(&mut app); + assert_eq!((d.str("name"), d.str("cannotStart")), ("Kinsoku Set 1".to_string(), "ゞ".to_string())); +} + +/// Delete then New does not give the new set the deleted set's name, so on OK the deleted set's +/// paragraphs take Hard rather than the new set's characters. +#[test] +fn new_after_delete_does_not_take_the_deleted_name() { + let mut app = app(); + app.run("type.kinsokuSets.set", json!({"sets": [{"name": "Kinsoku Set 1", "cannotStart": "ゝ"}]})).unwrap(); + let id = app.run("text.create", json!({"x": 10, "y": 50, "text": "あいう"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("text.setFormat", json!({"kinsoku": "Kinsoku Set 1"})).unwrap(); + open(&mut app).unwrap(); + frame(&mut app); + press(&mut app, Action::Delete); + dialog(&mut app).fields.insert("base".into(), json!("none")); + frame(&mut app); + press(&mut app, Action::New); + assert_eq!(dialog(&mut app).str("name"), "Kinsoku Set 2"); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + assert_eq!(doc_sets(&app).iter().map(|k| k.name.as_str()).collect::>(), ["Kinsoku Set 2"]); + let para = match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.para_at(0).clone(), + _ => panic!("not text"), + }; + assert_eq!(para.kinsoku_name(), "Hard"); +} + +/// OK takes the fields as they are set (`ui.dialog.set`) even when no frame was drawn since. Once +/// `selected` picks another set, the fields no longer describe it: OK leaves that set as it is, +/// and the next frame fills the fields from it. +#[test] +fn ok_takes_fields_set_without_a_frame() { + let mut app = app(); + let doc = json!([{"name": "Doc Set", "cannotStart": "ゝ"}, {"name": "Other", "cannotStart": "ー"}]); + app.run("type.kinsokuSets.set", json!({ "sets": doc })).unwrap(); + open(&mut app).unwrap(); + let d = dialog(&mut app); + d.fields.insert("name".into(), json!("Scripted")); + d.fields.insert("cannotStart".into(), json!("ゞ")); + super::super::confirm(&mut app).unwrap(); + let sets = doc_sets(&app); + assert_eq!((sets[0].name.as_str(), sets[0].cannot_start.clone()), ("Scripted", vec!['ゞ'])); + + let before = steps(&app); + open(&mut app).unwrap(); + let d = dialog(&mut app); + d.fields.insert("selected".into(), json!(1)); + d.fields.insert("cannotStart".into(), json!("ゝ")); + let pending = app.ui.dialog.clone().unwrap(); + super::super::confirm(&mut app).unwrap(); + assert_eq!(steps(&app), before, "the fields of the set shown before do not go into the one picked"); + assert_eq!(doc_sets(&app)[1].name, "Other"); + app.ui.dialog = Some(pending); + frame(&mut app); + let d = dialog(&mut app); + assert_eq!((d.str("name"), d.str("cannotStart")), ("Other".to_string(), "ー".to_string())); +} + +/// OK sets the sets of the document the dialog opened on, also when another document became the +/// active one while it was open; with that document closed, OK closes the dialog and changes no +/// document's sets. +#[test] +fn ok_sets_the_document_the_dialog_opened_on() { + let mut app = app(); + let first = app.session.active().unwrap().uid; + app.run("type.kinsokuSets.set", json!({ "sets": [{"name": "First", "cannotStart": "ゝ"}] })).unwrap(); + open(&mut app).unwrap(); + assert!(!super::super::accepts_field(dialog(&mut app), DOC), "`ui.dialog.set` cannot change the document"); + dialog(&mut app).fields.insert("name".into(), json!("Soft")); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let other = app.session.active().unwrap().uid; + assert_ne!(other, first); + // A name OK refuses keeps the dialog open on its document, now the active one. + assert!(super::super::confirm(&mut app).is_err()); + assert!(app.ui.dialog.is_some()); + assert_eq!(app.session.active().unwrap().uid, first); + assert_eq!(doc_sets(&app)[0].name, "First"); + app.run("document.activate", json!({ "index": app.session.documents().iter().position(|d| d.uid == other).unwrap() })).unwrap(); + dialog(&mut app).fields.insert("name".into(), json!("Kinsoku Set 1")); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.active().unwrap().uid, first); + assert_eq!(doc_sets(&app)[0].name, "Kinsoku Set 1"); + let second = app.session.documents().iter().find(|d| d.uid != first).unwrap(); + assert!(second.doc.kinsoku_sets.is_empty(), "the other document keeps its sets"); + + // New skips the names of the dialog's document's sets, not of the active document's. + open(&mut app).unwrap(); + press(&mut app, Action::Delete); + app.run("document.activate", json!({ "index": app.session.documents().iter().position(|d| d.uid == other).unwrap() })).unwrap(); + press(&mut app, Action::New); + assert_eq!(dialog(&mut app).str("name"), "Kinsoku Set 2"); + let i = app.session.documents().iter().position(|d| d.uid == first).unwrap(); + app.session.execute("file.close", &json!({ "index": i })).unwrap(); + assert!(super::super::confirm(&mut app).is_err()); + assert!(app.ui.dialog.is_none()); + assert!(app.session.documents().iter().all(|d| d.doc.kinsoku_sets.is_empty())); +} + +/// OK keeps a set the document gained while the dialog was open, after the dialog's sets, and a +/// set deleted in the dialog stays deleted. A `sets` field that is not a list of sets keeps the +/// dialog open and leaves the document's sets as they are, also when a frame is drawn before OK, +/// and New refuses to start from it. +#[test] +fn ok_keeps_sets_added_while_open_and_refuses_malformed_sets() { + let mut app = app(); + app.run("type.kinsokuSets.set", json!({ "sets": [{"name": "First", "cannotStart": "ゝ"}] })).unwrap(); + open(&mut app).unwrap(); + let both = json!([{"name": "First", "cannotStart": "ゝ"}, {"name": "Later", "cannotStart": "ー"}]); + app.run("type.kinsokuSets.set", json!({ "sets": both })).unwrap(); + dialog(&mut app).fields.insert("cannotStart".into(), json!("ゞ")); + super::super::confirm(&mut app).unwrap(); + let sets = doc_sets(&app); + let named = sets.iter().map(|k| (k.name.as_str(), k.cannot_start.clone())).collect::>(); + assert_eq!(named, [("First", vec!['ゞ']), ("Later", vec!['ー'])]); + open(&mut app).unwrap(); + press(&mut app, Action::Delete); + super::super::confirm(&mut app).unwrap(); + let names = |app: &VectorcraftApp| doc_sets(app).iter().map(|k| k.name.clone()).collect::>(); + assert_eq!(names(&app), ["Later"]); + for bad in [Value::Null, json!({}), json!("Later"), json!([1]), json!([{"name": "Later", "cannotStart": "ー"}, 1])] { + for drawn in [false, true] { + open(&mut app).unwrap(); + dialog(&mut app).fields.insert("sets".into(), bad.clone()); + if drawn { + frame(&mut app); + assert_eq!(dialog(&mut app).fields.get("sets"), Some(&bad), "a frame keeps {bad} as it is"); + let mut d = app.ui.dialog.clone().unwrap(); + assert!(run(&mut app, &mut d, Action::New).is_err(), "{bad}"); + assert_eq!(d.fields.get("sets"), Some(&bad), "New keeps {bad} as it is"); + } + assert!(super::super::confirm(&mut app).is_err(), "{bad} drawn: {drawn}"); + assert!(app.ui.dialog.is_some(), "{bad} drawn: {drawn}"); + assert_eq!(names(&app), ["Later"], "{bad} drawn: {drawn}"); + } + } +} + +/// Add takes a code point as U+XXXX, u+xxxx or bare hexadecimal, and never a control or space +/// character or a value that is no character. +#[test] +fn add_reads_unicode_code_points() { + assert_eq!(code_char("U+3001"), Some('、')); + assert_eq!(code_char(" u+ff5d "), Some('}')); + assert_eq!(code_char("300c"), Some('「')); + for bad in ["", "U+", "U+0007", "U+0020", "U+D800", "U+110000", "zz"] { + assert_eq!(code_char(bad), None, "{bad:?}"); + } +} + +/// The menu item shows only with Show East Asian Options on, and needs a document. +#[test] +fn the_menu_item_shows_with_east_asian_options() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.prefs.show_east_asian_options = true; + assert_eq!(crate::menus::shown_state(&app, COMMAND, &json!({})).map(|s| s.0), Some(false)); + app.run("file.new", json!({})).unwrap(); + assert_eq!(crate::menus::shown_state(&app, COMMAND, &json!({})).map(|s| s.0), Some(true)); + app.session.prefs.show_east_asian_options = false; + assert_eq!(crate::menus::shown_state(&app, COMMAND, &json!({})), None); +} diff --git a/crates/ui-egui/src/dialogs/layer_options.rs b/crates/ui-egui/src/dialogs/layer_options.rs index d40d61c6f5..ce954a32cd 100644 --- a/crates/ui-egui/src/dialogs/layer_options.rs +++ b/crates/ui-egui/src/dialogs/layer_options.rs @@ -157,9 +157,14 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { } /// `ui.newLayer {sublayer?}`: Layer Options for a new layer (or sublayer), with the name and -/// colour it would get. +/// colour it would get. In isolation mode a layer that would be outside the isolated art, where the +/// Layers panel does not list it, is an error. pub fn open_new(app: &mut VectorcraftApp, p: &Value) -> Result { let st = app.session.active().ok_or("no document open")?; + let sublayer = crate::menus::opt_bool(p, "sublayer")?.unwrap_or(false); + if crate::panels::layers::new_layer_unlisted(st, sublayer, false) { + return Err("exit isolation mode first".into()); + } let mut layers = vec![]; st.doc.walk(|n| { if n.is_layer() { @@ -170,7 +175,6 @@ pub fn open_new(app: &mut VectorcraftApp, p: &Value) -> Result { while layers.contains(&format!("Layer {i}")) { i += 1; } - let sublayer = p.get("sublayer").and_then(Value::as_bool).unwrap_or(false); let color = LayerColor::Preset((layers.len() % LAYER_COLORS.len()) as u8); let name = format!("Layer {i}"); let name = if app.session.prefs.identify_objects_by == "xmlId" { vectorcraft_doc::xml_id::from_object_name(&name) } else { name }; @@ -325,6 +329,17 @@ pub(crate) fn params(d: &Dialog) -> (&'static str, Value) { fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let (cmd, p) = params(d); + // Isolation mode can start while the dialog is open. + let sublayer = match cmd { + "layer.new" => Some(false), + "layer.newSublayer" => Some(true), + _ => None, + }; + if let Some(sublayer) = sublayer + && app.session.active().is_some_and(|st| crate::panels::layers::new_layer_unlisted(st, sublayer, false)) + { + return Err("exit isolation mode first".into()); + } run_and_close(app, cmd, p) } @@ -611,6 +626,23 @@ mod tests { } } + /// OK in New Layer Options makes no layer outside the isolated art when isolation mode started + /// while the dialog was open. + #[test] + fn new_layer_options_ok_checks_isolation_again() { + let mut app = app(); + let id = |v: Value| v["id"].as_u64().unwrap(); + let rect = id(app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()); + app.session.execute("select.set", &json!({"ids": [rect]})).unwrap(); + let group = id(app.session.execute("object.group", &json!({})).unwrap()); + app.run("ui.newLayer", json!({})).unwrap(); + app.session.execute("object.isolate", &json!({"id": group})).unwrap(); + draw(&mut app); + let err = super::super::confirm(&mut app).unwrap_err(); + assert!(err.contains("exit isolation mode first"), "{err}"); + assert_eq!(app.session.doc().unwrap().doc.layers.len(), 1); + } + #[test] fn new_layer_options_make_a_layer_and_objects_get_name_show_and_lock() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/modal.rs b/crates/ui-egui/src/dialogs/modal.rs index c5acd64e18..580f985c8d 100644 --- a/crates/ui-egui/src/dialogs/modal.rs +++ b/crates/ui-egui/src/dialogs/modal.rs @@ -14,20 +14,45 @@ use crate::theme::{self, Tokens}; /// screen's centre until it is moved, with `margin` inside its frame. `add` draws the contents and /// should start with [`heading`] (or [`drag_band`]) so the window can be moved. pub(crate) fn show(ctx: &egui::Context, title: &str, id: Id, nudge: f32, margin: i8, add: impl FnOnce(&mut egui::Ui) -> R) -> Option { - show_at(ctx, title, id, egui::vec2(0.0, nudge), margin, add) + show_at(ctx, title, id, egui::vec2(0.0, nudge), margin, None, add) } /// A modal that starts at a chosen offset, then keeps the user's dragged position. -pub(crate) fn show_at(ctx: &egui::Context, title: &str, id: Id, initial: Vec2, margin: i8, add: impl FnOnce(&mut egui::Ui) -> R) -> Option { +pub(crate) fn show_at( + ctx: &egui::Context, + title: &str, + id: Id, + initial: Vec2, + margin: i8, + canvas_pick: Option, + add: impl FnOnce(&mut egui::Ui) -> R, +) -> Option { let t = Tokens::get(ctx); let dim = backdrop(); - egui::Area::new(dim.id).order(dim.order).fixed_pos(egui::Pos2::ZERO).show(ctx, |ui| { - // Modal, but the canvas isn't dimmed so previews stay readable (as in the reference app). - // Not focusable (`Sense::click()` is): Tab goes through the dialog's controls, not the backdrop. - ui.allocate_rect(ctx.content_rect(), egui::Sense::CLICK); - }); - let pass = ctx.cumulative_pass_nr(); - ctx.data_mut(|d| d.insert_temp(drawn_pass_id(), pass)); + if let Some(canvas) = canvas_pick { + let screen = ctx.content_rect(); + let canvas = canvas.intersect(screen); + // Separate areas keep their hit rectangles outside the canvas. One area around a hole + // would still cover the canvas with its enclosing rectangle. + let regions = [ + Rect::from_min_max(screen.min, egui::pos2(screen.right(), canvas.top())), + Rect::from_min_max(egui::pos2(screen.left(), canvas.top()), egui::pos2(canvas.left(), canvas.bottom())), + Rect::from_min_max(egui::pos2(canvas.right(), canvas.top()), egui::pos2(screen.right(), canvas.bottom())), + Rect::from_min_max(egui::pos2(screen.left(), canvas.bottom()), screen.max), + ]; + for (index, region) in regions.into_iter().enumerate().filter(|(_, region)| region.width() > 0.0 && region.height() > 0.0) { + egui::Area::new(dim.id.with(index)).order(dim.order).fixed_pos(region.min).show(ctx, |ui| { + ui.allocate_rect(region, egui::Sense::CLICK); + }); + } + } else { + egui::Area::new(dim.id).order(dim.order).fixed_pos(egui::Pos2::ZERO).show(ctx, |ui| { + // Modal, but the canvas isn't dimmed so previews stay readable (as in the reference app). + // 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) @@ -39,7 +64,7 @@ pub(crate) fn show_at(ctx: &egui::Context, title: &str, id: Id, initial: Vec2 .show(ctx, |ui| { // Just opened: what scrolls in the window starts at its top, wherever it was left when // the window last closed. - if opened(ctx, id) { + if opened { ctx.data_mut(|m| { m.insert_temp(id.with(TOP_ROWS_KEY), true); m.insert_temp(id.with(TOP_WHOLE_KEY), true); @@ -76,16 +101,18 @@ pub(crate) fn show_at(ctx: &egui::Context, title: &str, id: Id, initial: Vec2 shown.inner } -/// Mark the modal window drawn next in this pass as opened over the one drawn in the pass before, -/// which it hides until it closes and shows that one again (Import Shortcut Set over Keyboard -/// Shortcuts). The window under it keeps where it was scrolled to. +/// Mark the modal window drawn next in this pass as opened over the windows drawn in the pass +/// before (a dialog and any alert of its own), which it hides until it closes and shows them again +/// (Import Shortcut Set over Keyboard Shortcuts). The windows under it keep where they were +/// scrolled to. pub(crate) fn over_parent(ctx: &egui::Context) { let pass = ctx.cumulative_pass_nr(); ctx.data_mut(|m| m.insert_temp(Id::unique(OVER_KEY), pass)); } -/// Whether modal window `id`, drawn in this pass, opened in it: it was not drawn in the pass before, -/// and none of the windows drawn in the pass before was one opened over it ([`over_parent`]). +/// Record that modal window `id` is drawn in this pass, and return whether it opened in it: it was +/// not drawn in the pass before, and none of the windows drawn in the pass before was one opened +/// over it ([`over_parent`]). fn opened(ctx: &egui::Context, id: Id) -> bool { let pass = ctx.cumulative_pass_nr(); ctx.data_mut(|m| { @@ -101,27 +128,32 @@ fn opened(ctx: &egui::Context, id: Id) -> bool { let before: Vec = prev.iter().copied().filter(|&other| other != id).collect(); now.push(id); m.insert_temp(Id::unique(LAST_KEY), (pass, now, prev)); + // Only the window drawn next after `over_parent` is opened over the others. + let over = m.remove_temp::(Id::unique(OVER_KEY)) == Some(pass); let last = std::mem::replace(m.get_temp_mut_or(id.with(SHOWN_KEY), u64::MAX), pass); if last != u64::MAX && last.saturating_add(1) >= pass { return false; } // Shown again as the window opened over it closed. - if before.iter().any(|over| m.get_temp::(over.with(HOLDS_KEY)) == Some(id)) { + if before.iter().any(|under| m.get_temp::>(under.with(HOLDS_KEY)).is_some_and(|held| held.contains(&id))) { return false; } - // Opened over the window drawn last in the pass before, it holds that one; otherwise none. - match before.last().copied().filter(|_| m.get_temp::(Id::unique(OVER_KEY)) == Some(pass)) { - Some(under) => { - m.insert_temp(id.with(HOLDS_KEY), under); - } - None => { - m.remove::(id.with(HOLDS_KEY)); - } + // Opened over the windows drawn in the pass before, it holds them; otherwise none. + if over && !before.is_empty() { + m.insert_temp(id.with(HOLDS_KEY), before); + } else { + m.remove::>(id.with(HOLDS_KEY)); } true }) } +/// The windows modal window `id` was opened over and hides ([`over_parent`]). +#[cfg(test)] +fn holds(ctx: &egui::Context, id: Id) -> Vec { + ctx.data(|m| m.get_temp::>(id.with(HOLDS_KEY))).unwrap_or_default() +} + /// The room for the contents of a modal window with `margin` inside its frame. fn whole_room(ctx: &egui::Context, margin: i8) -> Vec2 { (ctx.content_rect().size() - Vec2::splat(2.0 * (super::EDGE_GAP + f32::from(margin)))).max(Vec2::ZERO) @@ -133,15 +165,11 @@ pub(crate) fn backdrop() -> egui::LayerId { egui::LayerId::new(egui::Order::Middle, Id::unique("modal-dim")) } -/// The key of the pass in which [`show_at`] last drew a modal window. -fn drawn_pass_id() -> Id { - Id::unique("modal-drawn-pass") -} - /// Whether [`show_at`] drew a modal window in this pass. Unlike the backdrop's visibility, which /// also counts the last pass, it is false in the pass after the window closes. pub(crate) fn drawn_this_pass(ctx: &egui::Context) -> bool { - ctx.data(|d| d.get_temp::(drawn_pass_id())) == Some(ctx.cumulative_pass_nr()) + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|d| d.get_temp_mut_or::<(u64, Vec, Vec)>(Id::unique(LAST_KEY), (u64::MAX, vec![], vec![])).0 == pass) } /// The dialog's heading, which also moves the window ([`drag_band`]). @@ -197,9 +225,10 @@ const SHOWN_KEY: &str = "modal-shown"; const TOP_ROWS_KEY: &str = "modal-top-rows"; const TOP_WHOLE_KEY: &str = "modal-top-whole"; /// For all modal windows: the pass the last one was drawn in, the ids of those drawn in that pass -/// and of those drawn in the pass before it (`LAST_KEY`), and the pass -/// in which the window drawn next was marked as opened over another ([`over_parent`], `OVER_KEY`). -/// Under a modal window's id: the window it was opened over and hides (`HOLDS_KEY`). +/// and of those drawn in the pass before it (`LAST_KEY`, which [`drawn_this_pass`] also reads), and +/// the pass in which the window drawn next was marked as opened over others ([`over_parent`], +/// `OVER_KEY`, taken by that window). Under a modal window's id: the windows it was opened over and +/// hides (`HOLDS_KEY`). const LAST_KEY: &str = "modal-last"; const OVER_KEY: &str = "modal-over"; const HOLDS_KEY: &str = "modal-holds"; @@ -446,24 +475,36 @@ mod tests { #[test] fn a_window_hidden_under_one_opened_over_it_keeps_its_scroll() { // As Keyboard Shortcuts is while Import Shortcut Set is open over it: it is not drawn, but it - // did not close. A window that another replaced did close. Either may have shown an alert - // of its own, drawn after it in the same passes. + // did not close. A window that another replaced did close. Any of them may have shown an + // alert of its own, drawn after it in the same passes: A before B or C opens, or B or C. let others: [(&[&str], bool); 4] = [(&["over B"], true), (&["over B", "Alert"], true), (&["C"], false), (&["C", "Alert"], false)]; + let id = |name: &str| Id::unique(("modal-reopen-test", name)); let mut wrong = vec![]; for in_rows in [false, true] { - for (other, kept) in others { - let ctx = egui::Context::default(); - crate::theme::apply(&ctx, Default::default()); - let mut time = 0.0; - first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4); - if first_row_seen(&ctx, &["A"], in_rows, wheel_down(), &mut time, 60) { - wrong.push(format!("rows {in_rows}: the wheel does not scroll A")); - } - if !first_row_seen(&ctx, other, in_rows, vec![], &mut time, 4) { - wrong.push(format!("rows {in_rows}: {other:?} does not open at its top")); - } - if first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4) == kept { - wrong.push(format!("rows {in_rows}: after {other:?}, A {} where it was scrolled to", if kept { "is not" } else { "is still" })); + for lead in [&["A"][..], &["A", "Alert"][..]] { + for (other, kept) in others { + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, Default::default()); + let mut time = 0.0; + first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4); + if first_row_seen(&ctx, &["A"], in_rows, wheel_down(), &mut time, 60) { + wrong.push(format!("rows {in_rows}: the wheel does not scroll A")); + } + first_row_seen(&ctx, lead, in_rows, vec![], &mut time, 4); + if !first_row_seen(&ctx, other, in_rows, vec![], &mut time, 4) { + wrong.push(format!("rows {in_rows}: after {lead:?}, {other:?} does not open at its top")); + } + // Only the window opened over A holds it; an alert drawn after that window holds none. + let held: Vec> = other.iter().map(|&name| holds(&ctx, id(name))).collect(); + let want: Vec> = + other.iter().map(|&name| if name.starts_with("over ") { lead.iter().map(|&l| id(l)).collect() } else { vec![] }).collect(); + if held != want { + wrong.push(format!("rows {in_rows}: after {lead:?}, {other:?} hold {held:?}, not {want:?}")); + } + if first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4) == kept { + let state = if kept { "is not" } else { "is still" }; + wrong.push(format!("rows {in_rows}: after {lead:?} and {other:?}, A {state} where it was scrolled to")); + } } } } diff --git a/crates/ui-egui/src/dialogs/object_mosaic.rs b/crates/ui-egui/src/dialogs/object_mosaic.rs new file mode 100644 index 0000000000..0ee49a194a --- /dev/null +++ b/crates/ui-egui/src/dialogs/object_mosaic.rs @@ -0,0 +1,896 @@ +//! Object › Create Object Mosaic…: the selected image's Current Size, the mosaic's New Size, Tile +//! Spacing and Number of Tiles, Constrain Ratio (Width or Height), Result (Color or Grayscale), +//! Resize Using Percentages, Delete Raster and Use Ratio. OK runs `object.createObjectMosaic` as one +//! undo step. +//! +//! Fields: `width`, `height` (pt, or percentages of the image's size with `percentages`), +//! `spacingX`, `spacingY` (pt), `columns`, `rows`, `lock` (Constrain Ratio on), `constrain` +//! (`width` | `height`: the side Constrain Ratio and Use Ratio keep), `gray`, `percentages` and +//! `deleteRaster`. `__imageW` and `__imageH` hold the image's size (pt), read again from the +//! selected image each frame, before `ui.dialog.set` sets fields and on OK; `__noImage` is true +//! while no image is selected. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeKind; + +use super::{DialogSpec, form}; +use crate::state::Dialog; +use crate::theme::Tokens; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Create Object Mosaic. +pub const KIND: &str = "objectMosaic"; + +/// The command the dialog runs. +pub const COMMAND: &str = "object.createObjectMosaic"; + +/// Width of the label column. +const LABEL_W: f32 = 112.0; + +/// Width of a size or count field. +const FIELD_W: f32 = 76.0; + +pub(super) const SPEC: DialogSpec = + DialogSpec { heading: |_| tl!("Create Object Mosaic").into(), body, confirm, min_width: 360.0, ..DialogSpec::FORM }; + +/// The size (pt) of the first selected image, which the mosaic is made from. +fn image_size(app: &VectorcraftApp) -> Option<(f64, f64)> { + let st = app.session.active()?; + let node = st.selection.objects.iter().filter_map(|id| st.doc.node(*id)).find(|n| matches!(n.kind, NodeKind::Image(_)))?; + let b = node.geometric_bounds()?; + Some((b.width(), b.height())) +} + +/// Open the dialog on the selected image, with the values `given` holds (the menu item's params, or +/// a caller's `object.createObjectMosaic` params, its Use Ratio applied to the counts) and the +/// command's defaults for the rest. With no image selected, or with params the command refuses, +/// nothing opens and the error says why. +pub fn open(app: &mut VectorcraftApp, given: &Value) -> Result { + let Some((w, h)) = image_size(app) else { return Err("select an image".into()) }; + let none = json!({}); + let given = if given.is_null() { &none } else { given }; + app.session.check_params(COMMAND, given).map_err(|e| e.to_string())?; + let (cols, rows) = vectorcraft_engine::cmd::mosaic_counts(&app.session, given).map_err(|e| e.to_string())?; + let n = |key: &str, d: f64| given.get(key).and_then(Value::as_f64).unwrap_or(d); + let b = |key: &str| given.get(key).and_then(Value::as_bool).unwrap_or(false); + let pct = b("percentages"); + // The new size starts at the image's, within the sizes the command takes (0.1 to 1,000,000 pt). + let (base_w, base_h) = if pct { (100.0, 100.0) } else { (w.clamp(0.1, 1.0e6), h.clamp(0.1, 1.0e6)) }; + let named = |key: &str| given.get(key).and_then(Value::as_str).filter(|s| matches!(*s, "width" | "height")); + let constrain = named("constrain"); + // The side the dialog keeps: Constrain Ratio's, else the one Use Ratio names. + let side = constrain.or(named("useRatio")).unwrap_or("width"); + let fields = json!({ + "width": n("width", base_w), "height": n("height", base_h), "spacingX": n("spacingX", 0.0), "spacingY": n("spacingY", 0.0), + "columns": cols, "rows": rows, + "lock": constrain.is_some(), "constrain": side, "gray": b("gray"), "percentages": pct, + "deleteRaster": b("deleteRaster"), "__imageW": w, "__imageH": h, + }); + app.ui.dialog = Some(Dialog::new(KIND, fields)); + Ok(json!({ "dialog": KIND })) +} + +/// The field that is true while no image is selected. +const NO_IMAGE: &str = "__noImage"; + +/// What the dialog shows when Resize Using Percentages is switched with no image selected. +const NO_IMAGE_WHY: &str = "select an image"; + +/// The selected image's size `size` (from [`image_size`]) read into the dialog, so New Size is +/// converted and constrained against the image as it is now, also after it was scaled while the +/// dialog was open. With no image selected the last size read stays and `__noImage` is set. +fn read_image(size: Option<(f64, f64)>, d: &mut Dialog) { + let Some((w, h)) = size else { + d.fields.insert(NO_IMAGE.into(), json!(true)); + return; + }; + if d.fields.remove(NO_IMAGE).is_some() && d.str(form::REFUSED) == NO_IMAGE_WHY { + d.fields.remove(form::REFUSED); + } + d.fields.insert("__imageW".into(), json!(w)); + d.fields.insert("__imageH".into(), json!(h)); +} + +/// [`read_image`] on the open dialog when it is this one. `ui.dialog.set` runs it before it sets +/// any field. +pub(crate) fn refresh(app: &mut VectorcraftApp) { + let size = image_size(app); + if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == KIND) { + read_image(size, d); + } +} + +/// The image's size (pt) the dialog holds. +fn image(d: &Dialog) -> (f64, f64) { + (d.f64("__imageW", 1.0).max(1e-9), d.f64("__imageH", 1.0).max(1e-9)) +} + +/// Whether Constrain Ratio and Use Ratio keep the width (else the height). +fn keeps_width(d: &Dialog) -> bool { + d.str("constrain") != "height" +} + +/// With Constrain Ratio on, the size field that follows the kept side. +fn follower(d: &Dialog) -> Option<&'static str> { + d.bool("lock").then(|| if keeps_width(d) { "height" } else { "width" }) +} + +/// The new sizes the command takes, in points or percentages (`object.createObjectMosaic`). +const SIZE_RANGE: std::ops::RangeInclusive = 0.1..=1.0e6; + +/// With Constrain Ratio on, the side that follows set from the side that leads, in the image's +/// proportions. A size `ui.dialog.set` gave the following side that the command refuses stays, +/// for OK to report. +fn follow_ratio(d: &mut Dialog) { + let Some((key, v)) = derived(d) else { return }; + if d.bool(&kept(key)) { + if !takes(d, key) { + return; + } + d.fields.remove(&kept(key)); + } + d.fields.insert(key.into(), json!(v)); +} + +/// The field that is true while size field `key` holds a value `ui.dialog.set` gave and the +/// command refuses. +fn kept(key: &str) -> String { + format!("__kept.{key}") +} + +/// Whether the command takes size field `key` as it is: a number from 0.1 to 1,000,000. +fn takes(d: &Dialog, key: &str) -> bool { + number(d, key, 0.0).as_f64().is_some_and(|x| SIZE_RANGE.contains(&x)) +} + +/// `ui.dialog.set` of `field`: a new size the command refuses (not a number, or outside 0.1 to +/// 1,000,000) stays in its field while it is refused, also on the side Constrain Ratio sets, instead +/// of being replaced by the size worked out from the kept side. +pub(super) fn note_set(d: &mut Dialog, field: &str) { + if !matches!(field, "width" | "height") { + return; + } + if takes(d, field) { + d.fields.remove(&kept(field)); + } else { + d.fields.insert(kept(field), json!(true)); + } +} + +/// With Constrain Ratio on, the side that follows and the size it gets from the side that leads. +fn derived(d: &Dialog) -> Option<(&'static str, f64)> { + let key = follower(d)?; + let (iw, ih) = image(d); + let pct = in_percentages(d); + Some(if key == "height" { + let w = d.f64("width", 0.0); + (key, if pct { w } else { w * ih / iw }) + } else { + let h = d.f64("height", 0.0); + (key, if pct { h } else { h * iw / ih }) + }) +} + +/// Resize Using Percentages turned on or off: the new size shown the other way, so it stays the +/// same size. When a size field does not hold a number, or a size the command takes (all but the +/// side Constrain Ratio sets) falls outside what the command accepts either as it is or the other +/// way, the fields and the mode stay as they are and the dialog shows why. With no image selected, nothing changes and +/// the dialog asks for one. +fn switch_percentages(d: &mut Dialog, on: bool) { + if d.bool(NO_IMAGE) { + d.fields.insert(form::REFUSED.into(), json!(NO_IMAGE_WHY)); + return; + } + let (iw, ih) = image(d); + let size = |key: &str| number(d, key, 100.0).as_f64().ok_or_else(|| format!("`{key}` must be a number (got {})", d.str(key))); + let (w, h) = match (size("width"), size("height")) { + (Ok(w), Ok(h)) => (w, h), + (Err(why), _) | (_, Err(why)) => { + d.fields.insert(form::REFUSED.into(), json!(why)); + return; + } + }; + let skip = follower(d); + let checked = |key: &str| skip != Some(key) || d.bool(&kept(key)); + let refused = |w: f64, h: f64| { + let (key, v) = [("width", w), ("height", h)].into_iter().find(|(k, v)| checked(k) && !SIZE_RANGE.contains(v))?; + Some(format!("`{key}` must be between {} and {} (got {v})", SIZE_RANGE.start(), SIZE_RANGE.end())) + }; + // A size the command refuses as it is stays refused, even when it falls in range the other way. + let converted = if on { (w / iw * 100.0, h / ih * 100.0) } else { (iw * w / 100.0, ih * h / 100.0) }; + if let Some(why) = refused(w, h).or_else(|| refused(converted.0, converted.1)) { + d.fields.insert(form::REFUSED.into(), json!(why)); + return; + } + let (w, h) = converted; + d.fields.remove(form::REFUSED); + d.fields.remove(&kept("percentages")); + d.fields.insert("width".into(), json!(w)); + d.fields.insert("height".into(), json!(h)); + d.fields.insert("percentages".into(), json!(on)); +} + +/// Whether the new size fields hold percentages: Resize Using Percentages, or while that field holds +/// a value that is not true or false, the mode it held before that value was set. +fn in_percentages(d: &Dialog) -> bool { + match d.fields.get("percentages") { + Some(Value::Bool(on)) => *on, + Some(_) => d.bool(&kept("percentages")), + None => false, + } +} + +/// `ui.dialog.set` of `percentages`: true or false switches the new size as the checkbox does, and +/// replaces a value that is not true or false; null is false. Another value is kept as it is, and +/// the command refuses it on OK. +pub(super) fn set_percentages(d: &mut Dialog, value: &Value) { + let mode = in_percentages(d); + // The command reads null as the field left out, which is off. + match if value.is_null() { Some(false) } else { value.as_bool() } { + Some(on) if on != mode => switch_percentages(d, on), + Some(on) => { + d.fields.remove(&kept("percentages")); + d.fields.insert("percentages".into(), json!(on)); + } + None => { + d.fields.insert(kept("percentages"), json!(mode)); + d.fields.insert("percentages".into(), value.clone()); + } + } +} + +/// Use Ratio: the count on the kept side stays and the other makes the tiles square, as the +/// command counts them for the fields as they are (Constrain Ratio's side, the new size and the +/// spacing). +fn use_ratio(app: &VectorcraftApp, d: &mut Dialog) { + let mut p = params(d); + p["useRatio"] = json!(if keeps_width(d) { "width" } else { "height" }); + match vectorcraft_engine::cmd::mosaic_counts(&app.session, &p) { + Ok((cols, rows)) => { + d.fields.remove(form::REFUSED); + d.fields.insert("columns".into(), json!(cols)); + d.fields.insert("rows".into(), json!(rows)); + } + Err(e) => form::note_refusal(d, &e), + } +} + +/// Field `key` as `object.createObjectMosaic` takes it: a number (text with a unit, as +/// `ui.dialog.set` may give it, read in points), `default` when the field is missing, and any other +/// value as it is, for the command to refuse. +fn number(d: &Dialog, key: &str, default: f64) -> Value { + match d.fields.get(key) { + None => json!(default), + Some(Value::String(s)) => vectorcraft_doc::Unit::Points.parse(s).map_or_else(|| json!(s), |v| json!(v)), + Some(v) => v.clone(), + } +} + +/// Field `key` as the command takes an on/off value: false when the field is missing, and any +/// other value as it is, for the command to refuse one that is not true or false. +fn switch(d: &Dialog, key: &str) -> Value { + d.fields.get(key).cloned().unwrap_or(json!(false)) +} + +/// `constrain` as the command takes it: null with Constrain Ratio off, else the side the field +/// holds (the width when it holds none), and any other value as it is, for the command to refuse. +fn constrained_side(d: &Dialog) -> Value { + if !d.bool("lock") { + return Value::Null; + } + match d.fields.get("constrain") { + None | Some(Value::Null) => json!("width"), + Some(v) => v.clone(), + } +} + +/// `object.createObjectMosaic` parameters from the fields. With Constrain Ratio on, the side it +/// sets is left out while it holds the size Constrain Ratio gives it: the command works it out from +/// the kept side and grows both in proportion to its 0.1 pt minimum. Any other value set on that +/// side, and a refused value `ui.dialog.set` gave it even when it equals that size, is passed on for +/// the command to check. +fn params(d: &Dialog) -> Value { + let mut p = json!({ + "columns": number(d, "columns", 10.0), "rows": number(d, "rows", 10.0), + "width": number(d, "width", 100.0), "height": number(d, "height", 100.0), "percentages": switch(d, "percentages"), + "constrain": constrained_side(d), + "spacingX": number(d, "spacingX", 0.0), "spacingY": number(d, "spacingY", 0.0), + "gray": switch(d, "gray"), "deleteRaster": switch(d, "deleteRaster"), + }); + if let (Some((key, v)), Some(o)) = (derived(d), p.as_object_mut()) + && !d.bool(&kept(key)) + && o.get(key).and_then(Value::as_f64).is_some_and(|x| x == v) + { + o.remove(key); + } + p +} + +/// A Width and a Height field for `keys`: lengths in `unit` of at least `least` points, or +/// percentages with `pct`, up to 1,000,000. With `follows`, the field of that key is grayed (Constrain Ratio sets it). +fn pair(ui: &mut egui::Ui, d: &mut Dialog, keys: [&str; 2], unit: vectorcraft_doc::Unit, (pct, least): (bool, f64), follows: Option<&str>) { + for (key, label) in keys.into_iter().zip([tl!("Width:"), tl!("Height:")]) { + widgets::dim_label(ui, label); + ui.add_enabled_ui(follows != Some(key), |ui| { + if pct { + if let Some(v) = widgets::spin_plain(ui, ("mosaic", key), d.f64(key, 100.0), "%", 2, FIELD_W, 1.0, 0.1, &[]) { + d.fields.insert(key.into(), json!(v.min(*SIZE_RANGE.end()))); + } + } else { + form::length_within(ui, d, key, unit, FIELD_W, Some(least..=1.0e6)); + } + }); + } +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let unit = app.session.general_unit(); + read_image(image_size(app), d); + let (iw, ih) = image(d); + widgets::label_row(ui, tl!("Current Size:"), LABEL_W, |ui| { + widgets::dim_label(ui, tl!("Width:")); + widgets::dim_name(ui, &unit.format(iw)); + widgets::dim_label(ui, tl!("Height:")); + widgets::dim_name(ui, &unit.format(ih)); + }); + ui.add_space(4.0); + let follows = follower(d); + let pct = in_percentages(d); + widgets::label_row(ui, tl!("New Size:"), LABEL_W, |ui| pair(ui, d, ["width", "height"], unit, (pct, 0.1), follows)); + follow_ratio(d); + ui.add_space(4.0); + widgets::label_row(ui, tl!("Tile Spacing:"), LABEL_W, |ui| pair(ui, d, ["spacingX", "spacingY"], unit, (false, 0.0), None)); + ui.add_space(4.0); + widgets::label_row(ui, tl!("Number of Tiles:"), LABEL_W, |ui| { + for (key, label) in [("columns", tl!("Width:")), ("rows", tl!("Height:"))] { + widgets::dim_label(ui, label); + if let Some(v) = widgets::spin_plain(ui, ("mosaic", key), d.f64(key, 10.0), "", 0, FIELD_W, 1.0, 1.0, &[]) { + d.fields.insert(key.into(), json!(v.round().clamp(1.0, 1000.0))); + } + } + }); + ui.add_space(4.0); + widgets::label_row(ui, tl!("Constrain Ratio:"), LABEL_W, |ui| { + form::check(ui, d, "lock", tl!("Constrain Width and Height Proportions")); + let width = keeps_width(d); + if widgets::radio(ui, tl!("Width"), width, true) { + d.fields.insert("constrain".into(), json!("width")); + } + if widgets::radio(ui, tl!("Height"), !width, true) { + d.fields.insert("constrain".into(), json!("height")); + } + }); + follow_ratio(d); + ui.add_space(4.0); + widgets::label_row(ui, tl!("Result:"), LABEL_W, |ui| { + let gray = d.bool("gray"); + if widgets::radio(ui, tl!("Color"), !gray, true) { + d.fields.insert("gray".into(), json!(false)); + } + if widgets::radio(ui, tl!("Grayscale"), gray, true) { + d.fields.insert("gray".into(), json!(true)); + } + }); + ui.add_space(4.0); + widgets::label_row(ui, tl!("Options:"), LABEL_W, |ui| { + ui.vertical(|ui| { + if widgets::check(ui, tl!("Resize Using Percentages"), pct, true) { + switch_percentages(d, !pct); + } + form::check(ui, d, "deleteRaster", tl!("Delete Raster")); + }); + }); + if let Some(why) = d.fields.get(form::REFUSED).and_then(Value::as_str) { + ui.add_space(4.0); + ui.add(egui::Label::new(egui::RichText::new(why).color(Tokens::get(ui.ctx()).warning)).wrap()); + } + ui.add_space(6.0); + if widgets::flat_button(ui, tl!("Use Ratio"), 96.0).clicked() { + use_ratio(app, d); + } + false +} + +/// OK: the new size worked out against the image's size as it is now, as a frame would show it. +/// A Constrain Ratio (`lock`) that is not true or false is refused, and the dialog stays open. The +/// dialog also stays open with its fields when the command refuses them, as [`form::commit_preview`] +/// does. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if d.fields.get("lock").is_some_and(|v| !v.is_boolean() && !v.is_null()) { + return Err("`lock` must be true or false".into()); + } + let mut d = d.clone(); + read_image(image_size(app), &mut d); + follow_ratio(&mut d); + let r = app.run(COMMAND, params(&d)); + if r.is_ok() { + app.ui.dialog = None; + } + r +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + /// A frame of the open dialog → the texts painted. The dialog measures itself on its first + /// frame, so a fresh context needs two. + fn frame(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + out.shapes.iter().filter_map(|s| if let egui::epaint::Shape::Text(t) = &s.shape { Some(t.galley.text().to_string()) } else { None }).collect() + } + + fn context() -> egui::Context { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx + } + + /// A tile count the dialog holds. + fn count(d: &Dialog, key: &str) -> u32 { + d.f64(key, 0.0) as u32 + } + + /// An app with a 100 × 50 pt embedded image selected. + fn app_with_image() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 50})).unwrap(); + app.run("paint.setStroke", json!({"none": true})).unwrap(); + app.run("object.rasterize", json!({"ppi": 72})).unwrap(); + app + } + + /// The mosaic group's size and tile count. + fn mosaic(app: &VectorcraftApp) -> Option<(f64, f64, usize)> { + let mut found = None; + app.session.active()?.doc.walk(|n| { + if n.name.as_deref() == Some("Object Mosaic") { + let b = n.geometric_bounds().unwrap(); + found = Some(((b.width() * 1e6).round() / 1e6, (b.height() * 1e6).round() / 1e6, n.children().map_or(0, |c| c.len()))); + } + }); + found + } + + fn open_from_menu(app: &mut VectorcraftApp) { + let entry = crate::menus::menu_entries(app).into_iter().find(|e| e.label == "Create Object Mosaic…").expect("menu item"); + let (cmd, params) = crate::menus::click_target(&entry.label, entry.command.as_deref().unwrap(), &entry.params); + crate::menus::invoke(app, &cmd, params); + } + + /// The menu item opens this dialog, not the generic one, on the image's size, with every documented row; OK + /// makes the mosaic as one undo step. + #[test] + fn the_menu_item_opens_the_dialog_with_its_rows() { + let mut app = app_with_image(); + open_from_menu(&mut app); + let d = app.ui.dialog.as_ref().expect("a dialog"); + assert_eq!(d.kind, KIND); + assert_eq!((d.f64("width", 0.0), d.f64("height", 0.0), d.f64("columns", 0.0), d.f64("rows", 0.0)), (100.0, 50.0, 10.0, 10.0)); + let ctx = context(); + frame(&mut app, &ctx); + let texts = frame(&mut app, &ctx); + for want in [ + "Create Object Mosaic", + "Current Size:", + "New Size:", + "Tile Spacing:", + "Number of Tiles:", + "Constrain Ratio:", + "Constrain Width and Height Proportions", + "Result:", + "Color", + "Grayscale", + "Resize Using Percentages", + "Delete Raster", + "Use Ratio", + "100 pt", + "50 pt", + ] { + assert!(texts.iter().any(|t| t == want), "{want:?} in {texts:?}"); + } + let undo = app.session.doc().unwrap().history.undo.len(); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(mosaic(&app), Some((100.0, 50.0, 100))); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + } + + /// An image narrower than 0.1 pt opens with a new width of 0.1 pt, which OK makes. + #[test] + fn a_tiny_image_opens_with_a_size_the_command_takes() { + let mut app = app_with_image(); + app.run("object.scale", json!({"sx": 0.05, "sy": 100})).unwrap(); + open(&mut app, &json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("width", 0.0), 0.1); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app).map(|m| m.0), Some(0.1)); + } + + /// With no image selected the dialog does not open and the error says why. + #[test] + fn without_an_image_nothing_opens() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 50})).unwrap(); + let e = open(&mut app, &json!({})).unwrap_err(); + assert!(app.ui.dialog.is_none()); + assert!(e.contains("select an image"), "{e}"); + } + + /// Constrain Ratio keeps the new size in the image's proportions from the side it names; Resize Using + /// Percentages shows the same size as percentages; Use Ratio makes the tiles square from the kept side's count. + #[test] + fn constrain_ratio_percentages_and_use_ratio_set_the_fields() { + let mut app = app_with_image(); + open(&mut app, &json!({"columns": 10, "rows": 10})).unwrap(); + let ctx = context(); + frame(&mut app, &ctx); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("lock".into(), json!(true)); + d.fields.insert("width".into(), json!(300)); + frame(&mut app, &ctx); + let mut d = app.ui.dialog.take().unwrap(); + assert_eq!(d.f64("height", 0.0), 150.0, "height follows the width"); + // Percentages: 300 × 150 pt of a 100 × 50 pt image is 300%. + switch_percentages(&mut d, true); + assert_eq!((d.f64("width", 0.0), d.f64("height", 0.0)), (300.0, 300.0)); + // Use Ratio: 10 columns across 300 pt are 30 pt tiles, so 5 rows down 150 pt. + use_ratio(&app, &mut d); + assert_eq!((count(&d, "columns"), count(&d, "rows")), (10, 5)); + // Kept by height: 4 rows of 37.5 pt over 300 pt are 8 columns. + d.fields.insert("constrain".into(), json!("height")); + d.fields.insert("rows".into(), json!(4)); + use_ratio(&app, &mut d); + assert_eq!((count(&d, "columns"), count(&d, "rows")), (8, 4)); + switch_percentages(&mut d, false); + assert_eq!((d.f64("width", 0.0), d.f64("height", 0.0)), (300.0, 150.0)); + d.fields.insert("gray".into(), json!(true)); + app.ui.dialog = Some(d); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app), Some((300.0, 150.0, 32))); + } + + /// With Constrain Ratio on, a kept width of 0.1 pt over a 100 × 50 pt image sets a height of + /// 0.05 pt, under the command's minimum: OK makes the 0.2 × 0.1 pt mosaic the command grows it to. + #[test] + fn a_constrained_size_under_the_minimum_grows_in_proportion() { + let mut app = app_with_image(); + open(&mut app, &json!({})).unwrap(); + let ctx = context(); + frame(&mut app, &ctx); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("lock".into(), json!(true)); + d.fields.insert("width".into(), json!(0.1)); + frame(&mut app, &ctx); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("height", 0.0), 0.05, "height follows the width"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app).map(|m| (m.0, m.1)), Some((0.2, 0.1))); + } + + /// A caller's params open the dialog with their values, and OK makes the mosaic they ask for. + #[test] + fn a_callers_params_open_the_dialog_with_their_values() { + let mut app = app_with_image(); + let params = json!({"columns": 4, "rows": 2, "width": 200, "percentages": true, "constrain": "width", "gray": true}); + app.run("ui.paramDialog", json!({"command": COMMAND, "label": "Create Object Mosaic", "params": params})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.kind, KIND); + assert_eq!( + (d.f64("width", 0.0), d.bool("percentages"), d.bool("lock"), d.str("constrain"), d.bool("gray")), + (200.0, true, true, "width".into(), true) + ); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app), Some((200.0, 100.0, 8))); + // Use Ratio given applies to the counts shown: 10 columns over 100 × 50 pt are 5 rows. + app.run("select.set", json!({"ids": [image_id(&app)]})).unwrap(); + let params = json!({"columns": 10, "rows": 3, "useRatio": true}); + app.run("ui.paramDialog", json!({"command": COMMAND, "params": params})).unwrap(); + assert_eq!(count(app.ui.dialog.as_ref().unwrap(), "rows"), 5); + // A side Use Ratio names is the side the dialog keeps: 4 rows over 100 × 50 pt are 8 columns. + let params = json!({"columns": 3, "rows": 4, "useRatio": "height"}); + app.run("ui.paramDialog", json!({"command": COMMAND, "params": params})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((count(d, "columns"), count(d, "rows"), d.str("constrain"), d.bool("lock")), (8, 4, "height".into(), false)); + app.ui.dialog = None; + // Params the command refuses open nothing and say why. + for (bad, key) in [(json!({"width": "abc"}), "width"), (json!({"constrain": "both"}), "constrain"), (json!({"widht": 200}), "widht")] { + let e = app.run("ui.paramDialog", json!({"command": COMMAND, "params": bad})).unwrap_err(); + assert!(app.ui.dialog.is_none(), "{e}"); + assert!(e.contains(key), "{e}"); + } + } + + /// `ui.dialog.set` of Resize Using Percentages shows the new size the other way, as the checkbox + /// does, so OK makes the same mosaic. Values the command refuses, set that way, are refused on OK + /// and make no mosaic. + #[test] + fn setting_fields_from_outside_keeps_the_size_or_is_refused() { + let mut app = app_with_image(); + open(&mut app, &json!({"width": 200, "height": 100})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "percentages".into(), json!(true)); + assert_eq!((d.f64("width", 0.0), d.f64("height", 0.0), d.bool("percentages")), (200.0, 200.0, true)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app).map(|m| (m.0, m.1)), Some((200.0, 100.0))); + app.run("edit.undo", json!({})).unwrap(); + // 0.1 × 0.1 pt of a 1000 × 500 pt image are 0.01% × 0.02%, under the command's 0.1%: the + // points stay, with the limit shown, and OK makes that size. + app.run("select.set", json!({"ids": [image_id(&app)]})).unwrap(); + app.run("object.scale", json!({"sx": 1000, "sy": 1000})).unwrap(); + open(&mut app, &json!({"width": 0.1, "height": 0.1})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "percentages".into(), json!(true)); + assert_eq!((d.f64("width", 0.0), d.f64("height", 0.0), d.bool("percentages")), (0.1, 0.1, false)); + assert!(d.str(form::REFUSED).contains("`width` must be between 0.1"), "{}", d.str(form::REFUSED)); + let ctx = context(); + frame(&mut app, &ctx); + let texts = frame(&mut app, &ctx); + assert!(texts.iter().any(|t| t.contains("must be between")), "the limit is shown: {texts:?}"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app).map(|m| (m.0, m.1)), Some((0.1, 0.1))); + app.run("edit.undo", json!({})).unwrap(); + app.run("edit.undo", json!({})).unwrap(); + for (field, value) in [("percentages", json!("yes")), ("width", json!("abc")), ("gray", json!(1))] { + app.run("select.set", json!({"ids": [image_id(&app)]})).unwrap(); + open(&mut app, &json!({})).unwrap(); + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), field.into(), value); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains(field), "{field}: {e}"); + assert_eq!(mosaic(&app), None, "{field}"); + } + // With Constrain Ratio on, a value the command refuses, set on the side it sets, is refused + // too, also after a frame. + for value in [json!("abc"), json!(0)] { + app.run("select.set", json!({"ids": [image_id(&app)]})).unwrap(); + open(&mut app, &json!({"constrain": "width"})).unwrap(); + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "height".into(), value.clone()); + frame(&mut app, &ctx); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("height"), "{value}: {e}"); + assert_eq!(mosaic(&app), None, "{value}"); + } + // Once that side holds a size the command takes, Constrain Ratio sets it again. + app.run("select.set", json!({"ids": [image_id(&app)]})).unwrap(); + open(&mut app, &json!({"constrain": "width"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + for (field, value) in [("height", json!(0)), ("lock", json!(false)), ("height", json!(80)), ("lock", json!(true))] { + crate::dialogs::set_field(d, field.into(), value); + } + frame(&mut app, &ctx); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("height", 0.0), 50.0); + // A refused height stays while a refused width is set and then corrected. + let d = app.ui.dialog.as_mut().unwrap(); + for (field, value) in [("height", json!(0)), ("width", json!(0)), ("width", json!(100))] { + crate::dialogs::set_field(d, field.into(), value); + } + frame(&mut app, &ctx); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("height"), "{e}"); + assert_eq!(mosaic(&app), None); + } + + /// A width `ui.dialog.set` gave that is not a number stays when Resize Using Percentages is set, + /// with the mode unchanged and the reason shown, and OK refuses it. + #[test] + fn a_size_that_is_not_a_number_stays_when_percentages_switch() { + let mut app = app_with_image(); + open(&mut app, &json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "width".into(), json!("abc")); + crate::dialogs::set_field(d, "percentages".into(), json!(true)); + assert_eq!((d.str("width"), d.bool("percentages")), ("abc".into(), false)); + assert!(d.str(form::REFUSED).contains("`width` must be a number"), "{}", d.str(form::REFUSED)); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("width"), "{e}"); + assert_eq!(mosaic(&app), None); + } + + /// A size `ui.dialog.set` gave that the command refuses stays when Resize Using Percentages + /// switches, even when it is in range the other way (0.05 pt of a 10 pt wide image is 0.5%, and + /// 0.05% of a 1,000 pt wide image is 0.5 pt), with the mode unchanged and the reason shown, and + /// OK refuses it. + #[test] + fn a_size_out_of_range_stays_when_percentages_switch() { + for (scale, given, on) in [(10, json!({}), true), (1000, json!({"percentages": true}), false)] { + let mut app = app_with_image(); + app.run("object.scale", json!({"sx": scale, "sy": scale})).unwrap(); + open(&mut app, &given).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "width".into(), json!(0.05)); + crate::dialogs::set_field(d, "percentages".into(), json!(on)); + assert_eq!((d.f64("width", 0.0), d.bool("percentages")), (0.05, !on), "{given}"); + assert!(d.str(form::REFUSED).contains("`width` must be between 0.1"), "{given}: {}", d.str(form::REFUSED)); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("width"), "{given}: {e}"); + assert_eq!(mosaic(&app), None, "{given}"); + } + } + + /// The image scaled from 100 × 50 pt to 200 × 100 pt while the dialog is open: Current Size shows + /// the new size, and Resize Using Percentages, by `ui.dialog.set` or by its checkbox, converts + /// New Size against it, so OK makes the size shown. With no image selected, switching is refused. + #[test] + fn percentages_convert_against_the_image_scaled_while_the_dialog_is_open() { + let set = |app: &mut VectorcraftApp, field: &str, value: Value| { + let (req, _) = crate::control::ControlRequest::new("ui.dialog.set", json!({"field": field, "value": value})); + let crate::control::Outcome::Done(r) = crate::control::handle(app, &egui::Context::default(), &req) else { + panic!("expected an immediate reply") + }; + r + }; + let mut app = app_with_image(); + open(&mut app, &json!({"width": 200, "height": 100})).unwrap(); + app.run("object.scale", json!({"sx": 200, "sy": 200})).unwrap(); + let ctx = context(); + frame(&mut app, &ctx); + let texts = frame(&mut app, &ctx); + assert!(texts.iter().any(|t| t == "200 pt"), "Current Size shows the scaled image: {texts:?}"); + let r = set(&mut app, "percentages", json!(true)); + assert_eq!(r["ok"], json!(true), "{r}"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.f64("width", 0.0), d.f64("height", 0.0), d.bool("percentages")), (100.0, 100.0, true)); + app.run("object.scale", json!({"sx": 50, "sy": 50})).unwrap(); + // The checkbox, after the image went back to 100 × 50 pt: 100% of it is 100 × 50 pt. + let size = image_size(&app); + let d = app.ui.dialog.as_mut().unwrap(); + read_image(size, d); + switch_percentages(d, false); + assert_eq!((d.f64("width", 0.0), d.f64("height", 0.0)), (100.0, 50.0)); + crate::dialogs::set_field(d, "percentages".into(), json!(true)); + app.run("object.scale", json!({"sx": 200, "sy": 200})).unwrap(); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app).map(|m| (m.0, m.1)), Some((200.0, 100.0)), "100% of the image as it is on OK"); + app.run("edit.undo", json!({})).unwrap(); + // No image selected: the mode and sizes stay and the dialog asks for an image. + app.run("select.set", json!({"ids": [image_id(&app)]})).unwrap(); + open(&mut app, &json!({})).unwrap(); + app.run("select.set", json!({"ids": []})).unwrap(); + set(&mut app, "percentages", json!(true)); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.f64("width", 0.0), d.bool("percentages")), (200.0, false)); + assert_eq!(d.str(form::REFUSED), NO_IMAGE_WHY); + app.run("select.set", json!({"ids": [image_id(&app)]})).unwrap(); + set(&mut app, "percentages", json!(true)); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.f64("width", 0.0), d.bool("percentages"), d.str(form::REFUSED)), (100.0, true, String::new())); + } + + /// A Constrain Ratio side other than width or height, or a Constrain Ratio that is not true or + /// false, set by `ui.dialog.set`, is refused on OK and makes no mosaic. + #[test] + fn a_constrain_ratio_value_the_command_refuses_is_refused() { + for (field, value, also) in [("constrain", json!("both"), Some(("lock", json!(true)))), ("lock", json!("yes"), None)] { + let mut app = app_with_image(); + open(&mut app, &json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + if let Some((k, v)) = also { + crate::dialogs::set_field(d, k.into(), v); + } + crate::dialogs::set_field(d, field.into(), value.clone()); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains(field), "{value}: {e}"); + assert_eq!(mosaic(&app), None, "{value}"); + } + } + + /// When the command refuses the dialog's fields, OK leaves the dialog open with them, so they can + /// be corrected; OK then makes the mosaic and closes it. + #[test] + fn a_refused_field_keeps_the_dialog_open() { + let mut app = app_with_image(); + open(&mut app, &json!({"width": 80})).unwrap(); + crate::dialogs::set_field(app.ui.dialog.as_mut().unwrap(), "gray".into(), json!(1)); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("gray"), "{e}"); + assert_eq!(mosaic(&app), None); + let d = app.ui.dialog.as_mut().expect("the dialog stays open"); + assert_eq!((d.f64("width", 0.0), d.fields.get("gray")), (80.0, Some(&json!(1)))); + crate::dialogs::set_field(d, "gray".into(), json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(mosaic(&app).map(|m| m.0), Some(80.0)); + } + + /// True or false set after a Resize Using Percentages value the command refuses replaces it: the + /// same mode as before keeps the sizes, and the other mode shows them the other way. Null is + /// false, as the command reads it. OK then makes the mosaic. + #[test] + fn true_or_false_replaces_a_refused_percentages_value() { + let pct = json!({"percentages": true, "width": 50, "height": 50}); + for (given, sets, size) in [ + (json!({}), vec![json!("yes"), json!(false)], (100.0, 50.0)), + (pct.clone(), vec![json!("yes"), json!(false)], (50.0, 25.0)), + (pct.clone(), vec![Value::Null], (50.0, 25.0)), + (pct, vec![json!("yes"), Value::Null], (50.0, 25.0)), + ] { + let mut app = app_with_image(); + open(&mut app, &given).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + for value in sets { + crate::dialogs::set_field(d, "percentages".into(), value); + } + assert_eq!(d.fields.get("percentages"), Some(&json!(false)), "{given}"); + assert_eq!((d.f64("width", 0.0), d.f64("height", 0.0)), size, "{given}"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app).map(|m| (m.0, m.1)), Some(size), "{given}"); + } + } + + /// With Constrain Ratio on, a refused height `ui.dialog.set` gave is refused on OK even when it + /// equals the size Constrain Ratio works out from the width (0.05 pt from 0.1 pt over 100 × 50 pt). + #[test] + fn a_refused_height_equal_to_the_constrained_size_is_refused() { + let mut app = app_with_image(); + open(&mut app, &json!({"constrain": "width"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + crate::dialogs::set_field(d, "width".into(), json!(0.1)); + crate::dialogs::set_field(d, "height".into(), json!(0.05)); + let e = crate::dialogs::confirm(&mut app).unwrap_err(); + assert!(e.contains("height"), "{e}"); + assert_eq!(mosaic(&app), None); + } + + /// A percentage typed in New Size above 1,000,000 is kept at 1,000,000, the most the command + /// takes, so Enter makes the mosaic: 1,000,000% of the 100 pt width is 1,000,000 pt. + #[test] + fn a_typed_percentage_stays_within_what_the_command_takes() { + let mut app = app_with_image(); + open(&mut app, &json!({"percentages": true})).unwrap(); + let ctx = context(); + let run = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + out.shapes + .iter() + .filter_map(|s| { + if let egui::epaint::Shape::Text(t) = &s.shape { + Some((t.galley.text().to_string(), t.visual_bounding_rect().center())) + } else { + None + } + }) + .collect::>() + }; + run(&mut app, vec![]); + let texts = run(&mut app, vec![]); + // New Size's Width field comes right after the row's Width caption. + let row = texts.iter().position(|(t, _)| t == "New Size:").expect("the New Size row"); + let width = texts[row..].iter().position(|(t, _)| t == "Width:").and_then(|i| texts.get(row + i + 1)); + assert_eq!(width.map(|(t, _)| t.as_str()), Some("100%"), "{texts:?}"); + let at = width.map(|(_, p)| *p).unwrap(); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(&mut app, vec![egui::Event::PointerMoved(at), press(true)]); + run(&mut app, vec![press(false)]); + run(&mut app, vec![]); + run(&mut app, vec![egui::Event::Text("2000000".into())]); + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + run(&mut app, vec![enter]); + assert!(app.ui.dialog.is_none(), "Enter makes the mosaic: {:?}", app.ui.dialog.as_ref().map(|d| d.str(form::REFUSED))); + assert_eq!(mosaic(&app).map(|m| (m.0, m.1)), Some((1e6, 50.0))); + } + + /// The id of the image in the document. + fn image_id(app: &VectorcraftApp) -> u64 { + let mut id = None; + app.session.active().unwrap().doc.walk(|n| { + if matches!(n.kind, NodeKind::Image(_)) { + id = Some(n.id.0); + } + }); + id.unwrap() + } + + /// #1000: the count the dialog holds reaches the command, so a count of 3.0 makes three columns. + #[test] + fn a_count_reaches_the_command() { + let mut app = app_with_image(); + open_from_menu(&mut app); + app.ui.dialog.as_mut().unwrap().fields.insert("columns".into(), json!(3.0)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(mosaic(&app).map(|m| m.2), Some(30)); + } +} diff --git a/crates/ui-egui/src/dialogs/package.rs b/crates/ui-egui/src/dialogs/package.rs index 25d17d3902..3e69af017c 100644 --- a/crates/ui-egui/src/dialogs/package.rs +++ b/crates/ui-egui/src/dialogs/package.rs @@ -173,10 +173,10 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { Ok(r) } -/// Did a save whose applied result is `r` write the document (no error, and no question asked -/// before writing)? +/// Did a save whose applied result is `r` write the document (no error, no question asked before +/// writing, and not canceled by Cancel Save)? fn saved(r: &Result) -> bool { - r.as_ref().is_ok_and(|r| r.get("pending").is_none()) + r.as_ref().is_ok_and(|r| r.get("pending").is_none() && r.get("cancelled").and_then(Value::as_bool) != Some(true)) } /// Report the package `r` (`file.package`'s reply): the status bar, the web's download, and the diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index dd8db94418..de04998800 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -96,6 +96,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { fields.insert("printer".into(), json!(default)); fields.insert("toFile".into(), json!(!printers["service"].as_bool().unwrap_or(false))); fields.insert("__printers".into(), printers); + app.ui.print_direct_pdf = false; fields.insert("__section".into(), json!(SECTIONS[0])); fields.insert("__sheet".into(), json!(0)); // The saved preset these settings are, if any (else [Default], shown as [Custom] if they differ). @@ -217,7 +218,16 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { app.ui.dialog = None; return Ok(json!({ "settings": settings })); } - let r = crate::print::run(app, &json!({ "settings": settings, "printer": d.str("printer"), "toFile": d.bool("toFile") }))?; + let direct_pdf = app.ui.print_direct_pdf; + let r = crate::print::run( + app, + &json!({ + "settings": settings, + "printer": d.str("printer"), + "toFile": d.bool("toFile"), + "directPdf": direct_pdf, + }), + )?; app.ui.dialog = None; Ok(r) } @@ -372,6 +382,11 @@ fn printer_row(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { app.status(e); } }); + if service && cfg!(windows) { + let to_file = d.bool("toFile"); + ui.add_enabled(!to_file, egui::Checkbox::new(&mut app.ui.print_direct_pdf, "Send PDF directly (bypass driver)")); + note(ui, "Writes the print-ready PDF to the printer's TCP/IP RAW port, for PCL-only drivers that change the custom page size."); + } } /// `print.preview` of `settings` (an error when they can't print), cached until they or the diff --git a/crates/ui-egui/src/dialogs/profile_mismatch.rs b/crates/ui-egui/src/dialogs/profile_mismatch.rs new file mode 100644 index 0000000000..a0f447277e --- /dev/null +++ b/crates/ui-egui/src/dialogs/profile_mismatch.rs @@ -0,0 +1,427 @@ +//! The questions Edit › Color Settings' Ask boxes add (Profile Mismatches: Ask When Opening and +//! Ask When Pasting, Missing Profiles: Ask When Opening), one dialog kind each for opening and for +//! pasting. +//! +//! Opening ([`OPEN_KIND`]): a document whose color mode's profile is not the working space asks +//! whether to use that profile, convert the colors to the working space or discard the profile; one +//! with no profile asks whether to leave it, assign the working space or assign a profile. The +//! choice the policy makes is chosen first. OK opens the document as chosen; Cancel doesn't open +//! it. The file read waits in [`VectorcraftApp::pending_profile_open`]. Fields: `issue` (`mismatch` +//! | `missing`), `name` (the file's), `model` (`RGB` | `CMYK`), `profile` (the one it is tagged +//! with), `working`, `choice` (a `profileChoice` of `document.open`) and `assignProfile`. +//! +//! Pasting ([`PASTE_KIND`]): colors copied, or dragged ([`DROP`]), from a document whose profile is +//! not this document's ask whether to keep their numbers or convert them. OK runs the paste or the +//! drop with `profileMismatch`; Cancel pastes or drops nothing. Fields: `mismatches` (as +//! `clipboard.profileMismatch` lists them), `choice` (`preserveNumbers` | `convert`, or with both +//! models `{rgb, cmyk}` of those, one for each), `__command` +//! and `__params` (the paste or drop to run), and `__doc` (the uid of the document it was asked in). + +use serde_json::{Value, json}; +use vectorcraft_color::cms::{self, ProfileKind}; +use vectorcraft_engine::cmd::colormgmt::{ProfileChoice, ProfileQuestion}; +use vectorcraft_engine::cmd::fileio::{self, ReadFile}; +use vectorcraft_engine::file_access::ScopeHandle; + +use super::swatch_options::{grid, label}; +use super::{DialogResult, DialogSpec}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of the question opening asks. +pub const OPEN_KIND: &str = "profileMismatchOpen"; +/// The dialog kind of the question pasting asks. +pub const PASTE_KIND: &str = "profileMismatchPaste"; +/// The command a drag of artwork from another document runs, which asks as a paste does. +pub const DROP: &str = "edit.dropSelection"; + +pub(super) const OPEN_SPEC: DialogSpec = DialogSpec { + heading: |d| if d.str("issue") == "missing" { tl!("Missing Profile") } else { tl!("Embedded Profile Mismatch") }.into(), + body: open_body, + confirm: open_confirm, + min_width: 400.0, + max_width: Some(480.0), + ..DialogSpec::FORM +}; + +pub(super) const PASTE_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Paste Profile Mismatch").into(), + body: paste_body, + confirm: paste_confirm, + min_width: 400.0, + max_width: Some(480.0), + ..DialogSpec::FORM +}; + +/// A file read for File › Open that waits for the answer to its profile question. +pub(crate) struct PendingOpen { + file: ReadFile, + /// Where it was read from: it goes on the recent files once it opens. + path: Option, + /// The automation roots in force where the open was asked for: its linked files are read, and + /// the document is installed, under them and those of the caller that confirms. + scope: ScopeHandle, + /// It was read off the UI thread ([`crate::opening`]): the rest of its read is done there too + /// once the question is answered. An open that answers at once (a path a caller asked for) + /// finishes before OK returns. + background: bool, +} + +/// The choices of a mismatch (`missing`: of a missing profile), as (`choice`, label). +fn open_choices(missing: bool) -> [(&'static str, &'static str); 3] { + if missing { + [("leave", tl!("Leave as is")), ("assignWorking", tl!("Assign the working space")), ("assign", tl!("Assign profile:"))] + } else { + [ + ("useEmbedded", tl!("Use the embedded profile")), + ("convert", tl!("Convert the colors to the working space")), + ("discard", tl!("Discard the embedded profile")), + ] + } +} + +/// The choices pasting offers, as (`choice`, label). +fn paste_choices() -> [(&'static str, &'static str); 2] { + [("preserveNumbers", tl!("Preserve the color numbers")), ("convert", tl!("Convert to keep the colors' appearance"))] +} + +/// Open `file`, read for File › Open from `path`, as `document.open` does, unless Edit › Color +/// Settings asks about its profile ([`ReadFile::ask`]): then the dialog asks first, and the result +/// is `{dialog}`. A file read while another one's question is open waits for its own question +/// until that one is answered (`{dialog, queued: true}`). Opened, the views follow and the file +/// goes on the recent files ([`crate::io::opened`]). `background`: the file was read off the UI +/// thread, and the rest of its read after an answer is done there too. +pub fn open_or_ask(app: &mut VectorcraftApp, file: ReadFile, path: Option, background: bool) -> Result { + ask_or_open(app, PendingOpen { file, path, scope: ScopeHandle::capture(), background }) +} + +/// [`open_or_ask`] for a file that has its scope already. +fn ask_or_open(app: &mut VectorcraftApp, mut pending: PendingOpen) -> Result { + let Some(q) = pending.file.ask() else { + let PendingOpen { file, path, scope, .. } = pending; + return scope.run(|| { + let r = fileio::open_read(&mut app.session, file).map_err(|e| e.to_string())?; + crate::io::opened(app, &r); + if let Some(p) = &path { + crate::io::note_recent(app, p); + } + Ok(r) + }); + }; + if app.pending_profile_open.is_some() { + app.queued_profile_opens.push_back(pending); + return Ok(json!({ "dialog": OPEN_KIND, "queued": true })); + } + app.ui.dialog = Some(Dialog::new(OPEN_KIND, question_fields(&q, &pending.file.name()))); + app.pending_profile_open = Some(pending); + Ok(json!({ "dialog": OPEN_KIND })) +} + +/// The open dialog's fields for question `q` about the file named `name`. +fn question_fields(q: &ProfileQuestion, name: &str) -> Value { + json!({ + "issue": q.issue.id(), + "name": name, + "model": q.model_label(), + "profile": q.profile, + "working": q.working, + "choice": q.default.id(), + "assignProfile": q.working, + }) +} + +/// With no dialog open, the next file waiting for its profile question asks it, or opens as its +/// policy says when the question is gone (Color Settings changed meanwhile). A file that fails to +/// open is reported, and the next one comes. +pub(crate) fn ask_next(app: &mut VectorcraftApp) { + while app.pending_profile_open.is_none() && app.ui.dialog.is_none() { + let Some(next) = app.queued_profile_opens.pop_front() else { return }; + let name = next.file.name(); + if let Err(e) = ask_or_open(app, next) { + crate::io::report_open_error(app, &name, &e); + } + } +} + +/// The `profileChoice` the open dialog's fields give. +fn open_choice(d: &Dialog) -> Result { + let choice = d.str("choice"); + let profile = d.str("assignProfile"); + let profile = (choice == "assign").then_some(profile.as_str()); + ProfileChoice::parse(&choice, profile, "ui.dialog.confirm").map_err(|e| e.to_string()) +} + +fn open_body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let missing = d.str("issue") == "missing"; + let (name, model, profile, working) = (d.str("name"), d.str("model"), d.str("profile"), d.str("working")); + let vars = [("name", name.as_str()), ("model", model.as_str()), ("profile", profile.as_str()), ("working", working.as_str())]; + let text = if missing { + tl!("“{name}” is not tagged with a {model} profile.") + } else { + tl!("“{name}” is tagged with the {model} profile “{profile}”, which is not the {model} working space “{working}”.") + }; + ui.label(crate::i18n::fmt(text, &vars)); + ui.add_space(10.0); + let choice = d.str("choice"); + for (value, text) in open_choices(missing) { + ui.horizontal(|ui| { + if widgets::radio(ui, text, choice == value, true) { + d.fields.insert("choice".into(), json!(value)); + } + if value == "assign" { + let kind = if model == "CMYK" { ProfileKind::Cmyk } else { ProfileKind::Rgb }; + let current = d.str("assignProfile"); + ui.add_enabled_ui(choice == "assign", |ui| { + if let Some(n) = crate::panels::separations::profile_dropdown(ui, "profile-mismatch-assign", ¤t, kind, None) { + d.fields.insert("assignProfile".into(), json!(n)); + } + }); + } + }); + } + false +} + +/// OK: open the waiting file as chosen, under the automation roots of the open and those of the +/// caller that confirms both. A choice the file refuses keeps the dialog open. When Color Settings +/// changed the question since it was asked, the dialog asks the question as it stands now instead, +/// or the file opens as its policy says when there is no question any more. The next file waiting +/// for its question asks it once no dialog is open ([`settle`]). +fn open_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { + let choice = open_choice(d)?; + let Some(mut pending) = app.pending_profile_open.take() else { + app.ui.dialog = None; + return Ok(Value::Null); + }; + let scope = pending.scope.clone().within_current(); + if let Err(e) = scope.clone().run(|| pending.file.answer(choice)) { + // The question changed: ask it as it is now (or open by the policy when it is gone). + let now = |q: &ProfileQuestion| question_fields(q, ""); + let asked = |q: &ProfileQuestion| ["issue", "model", "profile", "working"].iter().all(|k| now(q).get(*k) == d.fields.get(*k)); + return match pending.file.ask() { + Some(q) if asked(&q) => { + app.pending_profile_open = Some(pending); + Err(e.to_string()) + } + Some(q) => { + app.ui.dialog = Some(Dialog::new(OPEN_KIND, question_fields(&q, &pending.file.name()))); + app.pending_profile_open = Some(pending); + Ok(json!({ "dialog": OPEN_KIND })) + } + None => { + app.ui.dialog = None; + open_pending(app, pending, scope) + } + }; + } + app.ui.dialog = None; + open_pending(app, pending, scope) +} + +/// Open `pending`, answered or without a question, under `scope`; a failure is reported. A file read +/// off the UI thread does the rest of its read (its linked files and type) there too +/// ([`crate::opening::finish_answered`]). +fn open_pending(app: &mut VectorcraftApp, pending: PendingOpen, scope: ScopeHandle) -> DialogResult { + let PendingOpen { file, path, background, .. } = pending; + let name = file.name(); + let file = match &path { + Some(p) if background && crate::opening::available() => match crate::opening::finish_answered(app, p, file, scope.clone()) { + Ok(r) => return Ok(r), + Err(Some(file)) => *file, + Err(None) => { + let e = "the file stopped being read (please report this bug)".to_string(); + crate::io::report_open_error(app, &name, &e); + return Err(e); + } + }, + _ => file, + }; + scope.run(|| match fileio::open_read(&mut app.session, file) { + Ok(r) => { + crate::io::opened(app, &r); + if let Some(p) = &path { + crate::io::note_recent(app, p); + } + Ok(r) + } + Err(e) => { + let e = e.to_string(); + crate::io::report_open_error(app, &name, &e); + Err(e) + } + }) +} + +/// Cancel, or the dialog closed some other way: the waiting file doesn't open. The next file waiting +/// for its question asks it once no dialog is open ([`settle`]). +pub(crate) fn cancel_open(app: &mut VectorcraftApp) { + app.pending_profile_open = None; +} + +/// A file still waiting once its dialog is gone (another dialog took its place) doesn't open; with +/// no dialog open, the next file waiting for its question asks it. +pub(crate) fn settle(app: &mut VectorcraftApp) { + if app.pending_profile_open.is_some() && !app.ui.dialog.as_ref().is_some_and(|d| d.kind == OPEN_KIND) { + app.pending_profile_open = None; + } + ask_next(app); +} + +/// Before running paste `command` (or `edit.dropSelection`, a drag from another document) with +/// `params`: when Ask When Pasting is on, `params` don't say what to do (`profileMismatch`) and the +/// pasted or dropped colors come from another profile, open the dialog instead and answer +/// `{dialog}`. +pub fn ask_paste(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option { + // A null choice is no choice, as the paste commands read it. + if params.get("profileMismatch").is_some_and(|v| !v.is_null()) || !cms::working_settings().ask_mismatch_paste { + return None; + } + let mismatches = paste_mismatches(app, command, params).filter(|a| !a.is_empty())?; + let choice = first_choice(&mismatches); + let doc = app.session.active().map(|st| st.uid); + let fields = json!({ "mismatches": mismatches, "choice": choice, "__command": command, "__params": params, DOC: doc }); + // A deferred paste this dialog asked about gives way to the new one. + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == PASTE_KIND) { + crate::placing::cancel_swatch_paste(app); + } + app.ui.dialog = Some(Dialog::new(PASTE_KIND, fields)); + Some(Ok(json!({ "dialog": PASTE_KIND }))) +} + +/// The models whose profiles differ for paste `command` with `params` (`clipboard.profileMismatch`): +/// a drop brings the objects it names, a paste the clipboard's, and Paste on All Artboards leaves the +/// backgrounds of copied artboards behind. `None` when they can't be listed. +fn paste_mismatches(app: &mut VectorcraftApp, command: &str, params: &Value) -> Option> { + let query = match command { + DROP => json!({ "sourceDocument": params.get("sourceDocument"), "ids": params.get("ids") }), + ALL_ARTBOARDS => json!({ "allArtboards": true }), + _ => json!({}), + }; + let found = app.session.execute("clipboard.profileMismatch", &query).ok()?; + found["mismatches"].as_array().cloned() +} + +/// Paste on All Artboards, which leaves copied artboards behind. +const ALL_ARTBOARDS: &str = "edit.pasteOnAllArtboards"; + +/// Can the colors of mismatch `m` convert (both profiles are available)? +fn convertible(m: &Value) -> bool { + m["convertible"].as_bool().unwrap_or(true) +} + +/// May the colors of mismatch `m` take `value`? Preserve Numbers always; Convert only when they can +/// convert. +fn allowed(m: &Value, value: &str) -> bool { + value != "convert" || convertible(m) +} + +/// The choice the paste question starts on: the model's policy for one model, and for both a +/// choice for each (`{rgb, cmyk}`), each starting on its model's policy. +fn first_choice(mismatches: &[Value]) -> Value { + let default = |m: &Value| m["default"].as_str().unwrap_or("preserveNumbers").to_string(); + match mismatches { + [m] => json!(default(m)), + _ => Value::Object(mismatches.iter().filter_map(|m| Some((m["model"].as_str()?.to_string(), json!(default(m))))).collect()), + } +} + +/// What `choice` (one choice for every model, or `{rgb?, cmyk?}`) picks for the colors of `model`. +fn picked<'a>(choice: &'a Value, model: &str) -> &'a str { + choice.as_str().or_else(|| choice.get(model).and_then(Value::as_str)).unwrap_or_default() +} + +/// `choice` with `value` picked for the colors of `model`: with one model the value alone, with +/// both a choice for each in which the other model's stays as `choice` has it. +fn pick(choice: &Value, mismatches: &[Value], model: &str, value: &str) -> Value { + if mismatches.len() < 2 { + return json!(value); + } + let each = + mismatches.iter().filter_map(|m| m["model"].as_str()).map(|m| (m.to_string(), json!(if m == model { value } else { picked(choice, m) }))); + Value::Object(each.collect()) +} + +/// Is `choice` one choice for every model, or a choice for each of `mismatches`' models? (Convert +/// for a model whose colors can't convert keeps their numbers, as the paste commands do.) +fn valid_choice(choice: &Value, mismatches: &[Value]) -> bool { + let known = |v: &str| paste_choices().iter().any(|(c, _)| *c == v); + match choice { + Value::String(s) => known(s), + Value::Object(o) => { + let models: Vec<&str> = mismatches.iter().filter_map(|m| m["model"].as_str()).collect(); + o.len() == models.len() && models.iter().all(|m| o.get(*m).and_then(Value::as_str).is_some_and(known)) + } + _ => false, + } +} + +fn paste_body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let mismatches = d.fields.get("mismatches").and_then(Value::as_array).cloned().unwrap_or_default(); + let choice = d.fields.get("choice").cloned().unwrap_or(Value::Null); + // With both models, each has its own choice under its line; with one, the choice follows it. + for m in &mismatches { + let id = m["model"].as_str().unwrap_or_default(); + let model = id.to_ascii_uppercase(); + let (from, to) = (m["clipboard"].as_str().unwrap_or_default(), m["document"].as_str().unwrap_or_default()); + let text = tl!("The pasted colors come from a document whose {model} profile is “{from}”; this document's is “{to}”."); + ui.label(crate::i18n::fmt(text, &[("model", model.as_str()), ("from", from), ("to", to)])); + ui.add_space(6.0); + let now = picked(&choice, id); + let clicked = ui.push_id(id, |ui| { + grid(ui, |ui| { + let mut clicked = None; + for (value, text) in paste_choices() { + label(ui, ""); + // Colors whose profile is not available can only keep their numbers. + if widgets::radio(ui, text, now == value, allowed(m, value)) { + clicked = Some(value); + } + ui.end_row(); + } + clicked + }) + }); + if let Some(value) = clicked.inner { + d.fields.insert("choice".into(), pick(&choice, &mismatches, id, value)); + } + ui.add_space(10.0); + } + false +} + +/// The field that holds the uid of the document the paste question is about. +const DOC: &str = "__doc"; + +/// OK: run the paste with the choice; any Swatch Conflict question comes next. When another +/// document has become the active one since a paste that runs at once asked, it closes as Cancel +/// does and pastes nothing. When the profiles that paste or drop would bring have changed since it +/// asked (the clipboard, the dragged objects' document or the destination's profile changed), it +/// asks again about the new ones; a paste that waited for its clipboard is checked in the document +/// and with the clipboard it runs with. +fn paste_confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { + let choice = d.fields.get("choice").cloned().unwrap_or(Value::Null); + let asked = d.fields.get("mismatches").and_then(Value::as_array).cloned().unwrap_or_default(); + if !valid_choice(&choice, &asked) { + let key = "choice"; + return Err(format!("`{key}` must be one of {}", "preserveNumbers, convert, {rgb, cmyk} of those")); + } + let deferred = d.fields.get("__deferredPaste").and_then(Value::as_u64); + if deferred.is_none() && d.fields.get(DOC).and_then(Value::as_u64) != app.session.active().map(|st| st.uid) { + app.ui.dialog = None; + return Ok(json!({})); + } + let command = d.str("__command"); + let mut params = d.fields.get("__params").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); + params["profileMismatch"] = choice; + app.ui.dialog = None; + // Without the answer, the paste asks again about what it brings now. + let changed = |app: &mut VectorcraftApp, command: &str, params: &Value| { + paste_mismatches(app, command, params).is_some_and(|now| !now.is_empty() && now != asked) + }; + let recheck = crate::placing::Recheck { key: "profileMismatch", changed: &changed }; + // A paste that waited for its clipboard runs in the context it was given in. + crate::placing::confirm_swatch_paste(app, &command, params, deferred, Some(&recheck)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs new file mode 100644 index 0000000000..358c6f428e --- /dev/null +++ b/crates/ui-egui/src/dialogs/profile_mismatch/tests.rs @@ -0,0 +1,412 @@ +use vectorcraft_engine::Session; + +use super::*; + +fn frame(app: &mut VectorcraftApp) -> String { + crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) +} + +fn set(app: &mut VectorcraftApp, k: &str, v: Value) { + app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v); +} + +/// The native file of a document with a blue rectangle, assigned `rgb` (none: untagged). +fn file(rgb: Option<&str>) -> Vec { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#3366cc"})).unwrap(); + if let Some(p) = rgb { + s.execute("edit.assignProfile", &json!({ "rgb": p })).unwrap(); + } + let r = s.execute("document.serialize", &json!({})).unwrap(); + vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap() +} + +fn rgb_profile(app: &VectorcraftApp) -> Option { + vectorcraft_engine::cmd::colormgmt::doc_profiles(&app.session.doc().unwrap().doc).0 +} + +/// OK on the open question, run by `confirm`, opens one document, installed with `roots`. +fn confirm_opens_one_under( + app: &mut VectorcraftApp, + roots: Option<&std::sync::Arc>, + confirm: impl FnOnce(&mut VectorcraftApp) -> Value, +) { + let docs = app.session.documents().len(); + let r = confirm(app); + assert_eq!(app.session.documents().len(), docs + 1, "{r}"); + let opened = &app.session.documents()[r["index"].as_u64().unwrap() as usize]; + assert_eq!(opened.opened_by.as_ref().map(|o| o.describe()), roots.map(|o| o.describe())); +} + +/// An open asked under automation roots finishes under them, though OK is pressed outside them: its +/// linked files are read, and the document is installed, with the roots of the open. `tagged` asks +/// with the settings in force. +fn open_asked_under_roots(app: &mut VectorcraftApp, tagged: &[u8]) { + use vectorcraft_engine::file_access; + let dir = crate::tests_folder::Folder::new("profile-mismatch-scope"); + let roots = file_access::AutomationRoots::new(&[dir.as_path()], &[]).unwrap(); + let r = file_access::confine(roots.as_ref(), || crate::io::open_bytes(app, "tagged.vectorcraft", tagged, None)).unwrap(); + assert_eq!(r, json!({ "dialog": OPEN_KIND })); + assert!(file_access::current().is_none(), "OK is pressed outside the roots"); + confirm_opens_one_under(app, roots.as_ref(), |app| super::super::confirm(app).unwrap()); +} + +/// An open asked outside automation roots and confirmed by a caller under them finishes under that +/// caller's roots: the document is installed with them. `tagged` asks with the settings in force. +fn open_confirmed_under_roots(app: &mut VectorcraftApp, tagged: &[u8]) { + use vectorcraft_engine::file_access; + let dir = crate::tests_folder::Folder::new("profile-mismatch-confirm-scope"); + let roots = file_access::AutomationRoots::new(&[dir.as_path()], &[]).unwrap(); + let r = crate::io::open_bytes(app, "tagged.vectorcraft", tagged, None).unwrap(); + assert_eq!(r, json!({ "dialog": OPEN_KIND })); + confirm_opens_one_under(app, roots.as_ref(), |app| file_access::confine(roots.as_ref(), || super::super::confirm(app)).unwrap()); +} + +/// A PNG of one color, 8 × 8. +fn png(rgb: [u8; 3]) -> Vec { + let [r, g, b] = rgb; + let layout = (craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8); + let img = craft_image_codecs::Image::from_raw(8, 8, layout.0, layout.1, [r, g, b, 255].repeat(64)).unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap() +} + +/// The linked files of a document asked about under automation roots, and confirmed outside them, +/// are read under those roots, apart from where the document is installed: of two linked files +/// changed since the save, the one inside the roots updates, and the one outside keeps the picture +/// the document holds. The Ask When Opening box for a mismatch is on. +fn links_read_under_the_roots_of_the_open(app: &mut VectorcraftApp) { + use vectorcraft_engine::file_access; + let dir = crate::tests_folder::Folder::new("profile-mismatch-links"); + let (inside, outside) = (dir.join("inside"), dir.join("outside")); + let (a, b) = (inside.join("in.png"), outside.join("out.png")); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + for p in [&a, &b] { + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, png([200, 40, 40])).unwrap(); + s.execute("file.place", &json!({"path": p.to_str().unwrap(), "at": [50, 50]})).unwrap(); + } + s.execute("edit.assignProfile", &json!({ "rgb": cms::WIDE_GAMUT_RGB })).unwrap(); + let r = s.execute("document.serialize", &json!({})).unwrap(); + let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); + // The profiles in use are the process's: back to the working spaces. + s.execute("edit.assignProfile", &json!({ "rgb": null })).unwrap(); + for p in [&a, &b] { + let stamp = std::fs::metadata(p).unwrap().modified().unwrap(); + std::fs::write(p, png([40, 40, 200])).unwrap(); + // Link stamps use milliseconds: the new file is dated 2 s later. + let later = std::fs::FileTimes::new().set_modified(stamp + std::time::Duration::from_secs(2)); + std::fs::OpenOptions::new().write(true).open(p).unwrap().set_times(later).unwrap(); + } + let update = std::mem::replace(&mut app.session.prefs.update_links, "automatically".into()); + let roots = file_access::AutomationRoots::new(&[inside.as_path()], &[]).unwrap(); + let r = file_access::confine(roots.as_ref(), || crate::io::open_bytes(app, "linked.vectorcraft", &bytes, None)).unwrap(); + assert_eq!(r, json!({ "dialog": OPEN_KIND })); + let r = super::super::confirm(app).unwrap(); + let updated: Vec<&str> = r["updatedLinks"].as_array().map(|a| a.iter().filter_map(|l| l["name"].as_str()).collect()).unwrap_or_default(); + assert_eq!(updated, ["in.png"], "{r}"); + app.session.prefs.update_links = update; + // A question about the link outside the roots is not part of this check. + if app.ui.dialog.is_some() { + super::super::cancel(app); + } +} + +/// A file read while another one's question is open waits and asks its own question in turn, and +/// each opens only after its own answer: Cancel on the first leaves it closed and asks about the +/// second. `tagged` asks with the settings in force. +fn files_opened_together_ask_in_turn(app: &mut VectorcraftApp, tagged: &[u8]) { + let docs = app.session.documents().len(); + assert_eq!(crate::io::open_bytes(app, "first.vectorcraft", tagged, None).unwrap(), json!({ "dialog": OPEN_KIND })); + let r = crate::io::open_bytes(app, "second.vectorcraft", tagged, None).unwrap(); + assert_eq!(r, json!({ "dialog": OPEN_KIND, "queued": true })); + assert_eq!(app.queued_profile_opens.len(), 1); + super::super::cancel(app); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.kind == OPEN_KIND) && app.pending_profile_open.is_some(), "the second asks"); + assert!(app.queued_profile_opens.is_empty()); + assert_eq!(app.session.documents().len(), docs, "neither is open"); + super::super::confirm(app).unwrap(); + assert_eq!(app.session.documents().len(), docs + 1); + assert!(app.ui.dialog.is_none() && app.pending_profile_open.is_none()); +} + +/// Color Settings change the open question while it is open: OK asks the question as it is now +/// (another working space) instead of opening, and opens by the policy once there is no question +/// (the working space is the file's profile). `tagged` (Wide Gamut RGB) asks with the settings in +/// force, the working space sRGB. +fn an_answer_waits_for_the_question_it_answers(app: &mut VectorcraftApp, tagged: &[u8]) { + let docs = app.session.documents().len(); + crate::io::open_bytes(app, "tagged.vectorcraft", tagged, None).unwrap(); + app.run("edit.colorSettings", json!({"rgb": cms::DISPLAY_P3})).unwrap(); + assert_eq!(super::super::confirm(app).unwrap(), json!({ "dialog": OPEN_KIND })); + assert_eq!(app.session.documents().len(), docs, "not opened under the old question"); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("working"), cms::canonical_name(cms::DISPLAY_P3), "asked again"); + app.run("edit.colorSettings", json!({"rgb": cms::WIDE_GAMUT_RGB})).unwrap(); + let r = super::super::confirm(app).unwrap(); + assert!(r.get("index").is_some() && app.ui.dialog.is_none(), "{r}"); + assert_eq!(app.session.documents().len(), docs + 1); +} + +/// Swatch Conflict asks again when the conflicts a converting paste raises change while it is open: +/// the destination is assigned another profile, so the pasted swatch converts to another color. OK +/// then pastes nothing and asks about the new conflict; OK on that one pastes as chosen. +fn swatch_conflicts_are_asked_again_when_they_change(app: &mut VectorcraftApp) { + use super::super::swatch_conflict; + let swatch = json!({"name": "Brand", "color": "#3366cc", "global": true}); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.new", swatch.clone()).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.run("paint.setFill", json!({"swatch": "Brand"})).unwrap(); + app.run("edit.assignProfile", json!({ "rgb": cms::WIDE_GAMUT_RGB })).unwrap(); + app.run("edit.copy", json!({})).unwrap(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.new", swatch).unwrap(); + let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + let before = count(app); + let r = app.run("edit.paste", json!({"profileMismatch": "convert"})).unwrap(); + assert_eq!(r["dialog"], swatch_conflict::KIND, "{r}"); + let asked = app.ui.dialog.as_ref().unwrap().fields["conflicts"].clone(); + set(app, "choice", json!("add")); + app.run("edit.assignProfile", json!({ "rgb": cms::DISPLAY_P3 })).unwrap(); + let r = super::super::confirm(app).unwrap(); + assert_eq!(r["dialog"], swatch_conflict::KIND, "asked again: {r}"); + assert_eq!(count(app), before, "nothing pasted under the old list"); + assert_ne!(app.ui.dialog.as_ref().unwrap().fields["conflicts"], asked); + set(app, "choice", json!("add")); + let r = super::super::confirm(app).unwrap(); + assert_eq!((count(app), r["renamed"].as_array().map(Vec::len)), (before + 1, Some(1)), "{r}"); +} + +/// Cancel on the paste question pastes nothing, and a null `profileMismatch` asks as leaving it out +/// does. `count` counts the active document's objects. +fn paste_canceled(app: &mut VectorcraftApp, count: impl Fn(&VectorcraftApp) -> usize) { + let before = count(app); + for params in [json!({}), json!({ "profileMismatch": null })] { + assert_eq!(app.run("edit.paste", params.clone()).unwrap(), json!({ "dialog": PASTE_KIND }), "{params} asks"); + super::super::cancel(app); + assert_eq!(count(app), before); + } +} + +/// Another document becomes the active one while the paste question is open: OK pastes nothing, into +/// neither document, whichever is active. +fn paste_asked_before_another_document_is_active(app: &mut VectorcraftApp) { + let counts = |app: &VectorcraftApp| -> Vec<(u64, usize)> { + app.session.documents().iter().map(|st| (st.uid, st.doc.layers[0].children().map_or(0, |c| c.len()))).collect() + }; + let (asked_in, before) = (app.session.active_index().unwrap(), counts(app)); + assert_eq!(app.run("edit.paste", json!({})).unwrap(), json!({ "dialog": PASTE_KIND })); + app.run("document.activate", json!({"index": 0})).unwrap(); + super::super::confirm(app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(counts(app), before, "nothing pasted into any document"); + app.run("document.activate", json!({ "index": asked_in })).unwrap(); +} + +/// A drag of the art of the document assigned Display P3 into the active one asks as Paste does: +/// Cancel drops nothing, and OK drops it as chosen. When the source document's profile changes while +/// the question is open, OK drops nothing and asks again about the new profile. `count` counts the +/// active document's objects. +fn drop_asks_as_paste_does(app: &mut VectorcraftApp, count: impl Fn(&VectorcraftApp) -> usize) { + let p3 = Some(cms::DISPLAY_P3); + let docs = app.session.documents(); + let at = docs.iter().position(|st| vectorcraft_engine::cmd::colormgmt::doc_profiles(&st.doc).0.as_deref() == p3).unwrap(); + let source = &docs[at]; + let ids: Vec = source.doc.layers[0].children().unwrap().iter().map(|n| n.id.0).collect(); + let n = ids.len(); + let drop = json!({"sourceDocument": source.uid, "ids": ids, "grab": [0, 0], "at": [50, 50]}); + let before = count(app); + assert_eq!(app.run(DROP, drop.clone()).unwrap(), json!({ "dialog": PASTE_KIND })); + assert_eq!(count(app), before, "nothing dropped yet"); + super::super::cancel(app); + assert_eq!(count(app), before, "Cancel drops nothing"); + assert_eq!(app.run(DROP, drop).unwrap(), json!({ "dialog": PASTE_KIND })); + // The source document is assigned another profile before OK. + let asked_in = app.session.active_index().unwrap(); + app.run("document.activate", json!({ "index": at })).unwrap(); + app.session.execute("edit.assignProfile", &json!({ "rgb": cms::WIDE_GAMUT_RGB })).unwrap(); + app.run("document.activate", json!({ "index": asked_in })).unwrap(); + assert_eq!(super::super::confirm(app).unwrap(), json!({ "dialog": PASTE_KIND })); + assert_eq!(count(app), before, "nothing dropped under the old question"); + let asked = &app.ui.dialog.as_ref().unwrap().fields["mismatches"][0]["clipboard"]; + assert_eq!(asked, &json!(cms::WIDE_GAMUT_RGB), "asked again about the new profile"); + set(app, "choice", json!("convert")); + let r = super::super::confirm(app).unwrap(); + assert_eq!(r["profileMismatch"][0]["choice"], "convert"); + assert!(app.ui.dialog.is_none()); + assert_eq!(count(app), before + n); +} + +/// A paste question about both models has a choice for each, starting on its model's policy, and +/// picking one model's choice in the dialog leaves the other's as it was; OK checks the choice. +#[test] +fn a_paste_question_about_both_models_has_a_choice_for_each() { + let both = [ + json!({"model": "rgb", "clipboard": "Wide RGB", "document": "sRGB", "default": "preserveNumbers", "convertible": true}), + json!({"model": "cmyk", "clipboard": "Ink A", "document": "Ink B", "default": "convert", "convertible": true}), + ]; + assert_eq!(first_choice(&both), json!({"rgb": "preserveNumbers", "cmyk": "convert"})); + assert_eq!(first_choice(&both[1..]), json!("convert"), "one model starts on its policy"); + for (choice, ok) in [ + (json!({"rgb": "convert", "cmyk": "preserveNumbers"}), true), + (json!("convert"), true), + (json!({"rgb": "convert"}), false), + (json!({"rgb": "convert", "cmyk": "keep"}), false), + (json!({"rgb": "convert", "cmyk": "convert", "lab": "convert"}), false), + (json!(""), false), + ] { + assert_eq!(valid_choice(&choice, &both), ok, "{choice}"); + } + // Picking CMYK's choice keeps RGB's, also when one choice was set for both. + let start = first_choice(&both); + assert_eq!(pick(&start, &both, "cmyk", "preserveNumbers"), json!({"rgb": "preserveNumbers", "cmyk": "preserveNumbers"})); + assert_eq!(pick(&json!("convert"), &both, "rgb", "preserveNumbers"), json!({"rgb": "preserveNumbers", "cmyk": "convert"})); + assert_eq!(pick(&json!("convert"), &both[..1], "rgb", "preserveNumbers"), json!("preserveNumbers")); + // The dialog draws a pair of choices under each model's line. + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let fields = json!({ "mismatches": both, "choice": start, "__command": "edit.paste", "__params": {} }); + app.ui.dialog = Some(Dialog::new(PASTE_KIND, fields)); + let text = frame(&mut app); + assert_eq!(text.matches("Preserve the color numbers").count(), 2, "{text}"); +} + +/// With Color Settings' Ask boxes on, File › Open asks about a document whose profile is not the +/// working space, or that has none, and opens it as chosen; Cancel doesn't open it, and a refused +/// choice keeps the dialog. Paste, and a drag from another document, ask about colors from another +/// profile and paste or drop as chosen. With the boxes off, nothing asks. An open asked or confirmed +/// under automation roots finishes under them, and a paste asked in one document pastes nothing once +/// another is active. +#[test] +fn opening_and_pasting_ask_about_profiles() { + const CHILD: &str = "VECTORCRAFT_TEST_PROFILE_PROMPTS"; + if std::env::var_os(CHILD).is_none() { + // Color settings are process-wide: change them in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "dialogs::profile_mismatch::tests::opening_and_pasting_ask_about_profiles", "--nocapture"]) + .env(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 profile prompt test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let (tagged, plain) = (file(Some(cms::WIDE_GAMUT_RGB)), file(None)); + // The boxes are off: the document opens as the policy says. + let r = crate::io::open_bytes(&mut app, "tagged.vectorcraft", &tagged, None).unwrap(); + assert!(r.get("index").is_some() && app.ui.dialog.is_none()); + assert_eq!(rgb_profile(&app).as_deref(), Some(cms::WIDE_GAMUT_RGB)); + + // Profile Mismatches: Ask When Opening. + app.run("edit.colorSettings", json!({"askMismatchOpen": true, "rgbPolicy": "convert"})).unwrap(); + let docs = app.session.documents().len(); + let r = crate::io::open_bytes(&mut app, "tagged.vectorcraft", &tagged, None).unwrap(); + assert_eq!(r, json!({ "dialog": OPEN_KIND })); + assert_eq!(app.session.documents().len(), docs, "not open yet"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!( + (d.str("issue"), d.str("model"), d.str("profile"), d.str("choice")), + ("mismatch".into(), "RGB".into(), cms::WIDE_GAMUT_RGB.into(), "convert".into()) + ); + let text = frame(&mut app); + for label in [ + "Embedded Profile Mismatch", + "Use the embedded profile", + "Convert the colors to the working space", + "Discard the embedded profile", + cms::WIDE_GAMUT_RGB, + ] { + assert!(text.contains(label), "{label} in {text}"); + } + // Cancel: nothing opens. + super::super::cancel(&mut app); + assert!(app.pending_profile_open.is_none()); + assert_eq!(app.session.documents().len(), docs); + crate::io::open_bytes(&mut app, "tagged.vectorcraft", &tagged, None).unwrap(); + set(&mut app, "choice", json!("useEmbedded")); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none() && app.pending_profile_open.is_none()); + assert_eq!(app.session.documents().len(), docs + 1); + assert_eq!(rgb_profile(&app).as_deref(), Some(cms::WIDE_GAMUT_RGB), "kept, though the policy converts"); + + open_asked_under_roots(&mut app, &tagged); + open_confirmed_under_roots(&mut app, &tagged); + links_read_under_the_roots_of_the_open(&mut app); + files_opened_together_ask_in_turn(&mut app, &tagged); + + // Missing Profiles: Ask When Opening, and a choice the file refuses. + app.run("edit.colorSettings", json!({"askMismatchOpen": false, "askMissingOpen": true, "rgbPolicy": "preserveEmbedded"})).unwrap(); + crate::io::open_bytes(&mut app, "plain.vectorcraft", &plain, None).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), d.str("issue"), d.str("choice")), (OPEN_KIND, "missing".into(), "leave".into())); + let text = frame(&mut app); + for label in ["Missing Profile", "Leave as is", "Assign the working space", "Assign profile:"] { + assert!(text.contains(label), "{label} in {text}"); + } + set(&mut app, "choice", json!("assign")); + set(&mut app, "assignProfile", json!(cms::DEVICE_CMYK)); + assert!(super::super::confirm(&mut app).is_err()); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.kind == OPEN_KIND) && app.pending_profile_open.is_some(), "still asking"); + set(&mut app, "assignProfile", json!(cms::DISPLAY_P3)); + super::super::confirm(&mut app).unwrap(); + assert_eq!(rgb_profile(&app).as_deref(), Some(cms::DISPLAY_P3)); + assert!(app.session.doc().unwrap().is_dirty(), "assigning changed the document"); + + // Profile Mismatches: Ask When Pasting. + app.run("edit.colorSettings", json!({"askMissingOpen": false, "askMismatchPaste": true})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("edit.copy", json!({})).unwrap(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let r = app.run("edit.paste", json!({})).unwrap(); + assert_eq!(r, json!({ "dialog": PASTE_KIND })); + let text = frame(&mut app); + for label in ["Paste Profile Mismatch", "Preserve the color numbers", "Convert to keep the colors' appearance", cms::DISPLAY_P3] { + assert!(text.contains(label), "{label} in {text}"); + } + set(&mut app, "choice", json!("convert")); + let r = super::super::confirm(&mut app).unwrap(); + assert_eq!(r["profileMismatch"][0]["choice"], "convert"); + assert!(app.ui.dialog.is_none()); + // Cancel pastes nothing; with the box off nothing asks. + let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()); + paste_canceled(&mut app, count); + paste_asked_before_another_document_is_active(&mut app); + drop_asks_as_paste_does(&mut app, count); + let before = count(&app); + app.run("edit.colorSettings", json!({"askMismatchPaste": false})).unwrap(); + let r = app.run("edit.paste", json!({})).unwrap(); + assert_eq!(r["profileMismatch"][0]["choice"], "preserveNumbers"); + assert_eq!(count(&app), before + 1); + swatch_conflicts_are_asked_again_when_they_change(&mut app); + all_artboards_leaves_backgrounds_out(&mut app); + // It changes the working space: last. + app.run("edit.colorSettings", json!({"askMismatchOpen": true})).unwrap(); + an_answer_waits_for_the_question_it_answers(&mut app, &tagged); +} + +/// Convert is offered only for a model whose colors can convert (`convertible`). +#[test] +fn convert_needs_both_profiles() { + let stuck = json!({"model": "rgb", "clipboard": "Gone", "document": "sRGB", "default": "preserveNumbers", "convertible": false}); + let free = json!({"model": "rgb", "clipboard": "Wide RGB", "document": "sRGB", "default": "convert", "convertible": true}); + assert!(allowed(&stuck, "preserveNumbers") && !allowed(&stuck, "convert")); + assert!(allowed(&free, "convert") && allowed(&json!({"model": "rgb"}), "convert")); +} + +/// Paste on All Artboards asks about what it brings, without the backgrounds of copied artboards. +fn all_artboards_leaves_backgrounds_out(app: &mut VectorcraftApp) { + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("artboard.setProps", json!({"index": 0, "color": "#3366cc"})).unwrap(); + app.run("edit.assignProfile", json!({ "rgb": cms::WIDE_GAMUT_RGB })).unwrap(); + app.run("artboard.copy", json!({"index": 0})).unwrap(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let listed = |app: &mut VectorcraftApp, command: &str| paste_mismatches(app, command, &json!({})).map(|m| m.len()); + assert_eq!(listed(app, "edit.paste"), Some(1), "the background is RGB"); + assert_eq!(listed(app, ALL_ARTBOARDS), Some(0)); +} diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index cfa699b7b9..267b2ac0c8 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -70,6 +70,12 @@ //! the most used color first and repeating when the rows outnumber them, and the art previews //! them; OK keeps them as one undo step. A new count of Colors keeps the picks: the new rows take them again. //! +//! Undo Changes and Redo Changes beside the Color Theme Picker (`ui.recolorUndo`, `ui.recolorRedo`) +//! step back and forward through the dialog's own color edits ([`History`]), not the document's +//! undo history; Cancel discards them and OK still records one undo step. Each opening starts +//! with nothing to undo, and selecting another color group or Save Changes leaves nothing to undo +//! or redo. +//! //! Fields (`ui.dialog.set`): `rows` ([{from: [keys], to: key, exclude?, tint?: percent of a spot //! color, added?}]; a row with no current colors, `from: []`, recolors no art, and with `added: true` //! (a color the Add Color tool added) adds its new color to the color group; `to: null`, no new color), `colors` (null: Auto, or a count), `method`, `preserveWhite`, `preserveBlack`, @@ -223,6 +229,8 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let mut rs = rows(&d); snap(app, &d, &mut rs); d.fields.insert("rows".into(), Value::Array(rs)); + // Undo Changes has nothing to undo on a new opening. + app.ui.recolor_history = History { opened: Some(snapshot(&d)), ..History::default() }; app.ui.dialog = Some(d); Ok(Value::Null) } @@ -499,6 +507,7 @@ fn select_group(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> d.fields.insert("__newGroup".into(), json!(true)); d.fields.insert("groupName".into(), json!(NEW_GROUP)); } + restart_history(app, d); return Ok(()); } Value::String(n) => n.clone(), @@ -538,6 +547,7 @@ fn select_group(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> d.fields.remove(COMPS); } d.fields.insert("__assign".into(), Value::Array(assign)); + restart_history(app, d); Ok(()) } @@ -559,6 +569,7 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res // 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()) { + restart_history(app, d); return Ok(()); } cancel_preview(app, d); @@ -572,6 +583,7 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res d.fields.insert("group".into(), name.clone()); d.fields.insert(GROUP_LOADED.into(), name.clone()); d.fields.insert("groupName".into(), name); + restart_history(app, d); Ok(()) } Some("save") => { @@ -678,6 +690,7 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res reread_rows(app, d, &rs, &before, &gone); } } + restart_history(app, d); Ok(()) } Some("delete") => { @@ -1338,14 +1351,19 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { /// 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)> { + seed(app, d); sync(app, d); sync_theme(app, d); sync_weights(app, d); + // The fields as the dialog read the art are where Undo Changes starts, also when the pointer is + // down on the first frame and the first step is recorded only on release. + app.ui.recolor_history.start(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); + let mut stepped = None; ui.horizontal(|ui| { let tab = d.str("tab"); for (id, label) in [("assign", tl!("Assign")), ("edit", tl!("Edit"))] { @@ -1357,6 +1375,12 @@ fn main(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> Option<(usize, if widgets::icon_button(ui, "pipette", tl!("Color Theme Picker"), picking, 24.0).clicked() { d.fields.insert(THEME_PICKER.into(), json!(!picking)); } + let h = &app.ui.recolor_history; + for (back, icon, tip) in [(true, "undo-2", tl!("Undo Changes")), (false, "redo-2", tl!("Redo Changes"))] { + if widgets::icon_button_enabled(ui, icon, tip, false, h.can(d, back), 24.0).clicked() { + stepped = Some(back); + } + } 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)); @@ -1369,6 +1393,9 @@ fn main(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> Option<(usize, ui.label(egui::RichText::new(tl!("Preset:")).color(t.text_dim)); }); }); + if let Some(back) = stepped { + app.ui.recolor_history.step(d, back); + } widgets::divider(ui); ui.add_space(4.0); if d.bool(THEME_PICKER) { @@ -1405,6 +1432,12 @@ fn main(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> Option<(usize, }); } sync(app, d); + // New rows take the picks now, so that a new count of Colors is one step. + sync_theme(app, d); + // A change is a step once the pointer is up: a drag is one step from press to release. + if !ui.input(|i| i.pointer.any_down()) { + app.ui.recolor_history.note(d); + } if d.bool("__art") { match find_params(d) { // Find shows the art so with Preview off too. @@ -1431,6 +1464,187 @@ pub(super) fn with_new_color(app: &VectorcraftApp, mut d: Dialog, i: usize, c: C d } +/// The fields a step of Undo Changes and Redo Changes restores: what the art is recolored with. +const STEP_FIELDS: [&str; 11] = + ["rows", "colors", "method", "preserveWhite", "preserveBlack", "preserveGrays", "limitTo", "rule", "globalAdjust", THEME_PICKS, WEIGHTS]; +/// The fields that record which reduction, picks and weights the rows already took, restored with +/// [`STEP_FIELDS`] so that the restored rows are not reduced, picked or weighed again. +const STEP_MARKS: [&str; 4] = ["__reduced", THEME_DONE, WEIGHED, PRESERVED]; +/// VectorCraft's own limits on the steps Undo Changes keeps: at most this many, and at most this +/// many bytes of them as JSON; the oldest go first. +const MAX_STEPS: usize = 64; +const MAX_STEP_BYTES: usize = 4 << 20; + +type Snapshot = serde_json::Map; + +/// The open dialog's own history of color edits: Undo Changes goes back one edit and Redo Changes +/// forward one, without touching the document's undo history. A change of [`STEP_FIELDS`] is one +/// step once the pointer is up, so a drag is one step; a new edit after Undo Changes ends what Redo +/// Changes could restore. +#[derive(Clone, Debug, Default)] +pub struct History { + /// The fields the dialog opened with (or had when its steps were dropped), before it read the + /// art, until its first frame or command. + opened: Option, + /// The fields after the last step (none before the dialog's first frame). + base: Option, + undo: Vec, + redo: Vec, +} + +/// Drop the dialog's steps, after another color group is selected or Save Changes rewrites the +/// group: Undo Changes and Redo Changes then have no step to go to. The fields of `d` are where +/// Undo Changes starts again, as on a new opening, so fields set before the next frame or step +/// (with `ui.dialog.set`) are a step back to them. +fn restart_history(app: &mut VectorcraftApp, d: &Dialog) { + app.ui.recolor_history = History { opened: Some(snapshot(d)), ..History::default() }; +} + +/// The size of `s` as JSON, which [`MAX_STEP_BYTES`] limits. +fn snapshot_size(s: &Snapshot) -> usize { + serde_json::to_vec(s).map_or(0, |b| b.len()) +} + +/// The fields of `d` a step restores ([`STEP_FIELDS`] and [`STEP_MARKS`]). +fn snapshot(d: &Dialog) -> Snapshot { + STEP_FIELDS.iter().chain(&STEP_MARKS).filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect() +} + +/// Before the first step is recorded: when fields were set after the dialog opened (with +/// `ui.dialog.set`, before a frame drew it), the fields it opened with, as they read the art, are +/// the step Undo Changes goes back to. +fn seed(app: &mut VectorcraftApp, d: &Dialog) { + let Some(opened) = app.ui.recolor_history.opened.take() else { return }; + if app.ui.recolor_history.base.is_some() || snapshot(d) == opened { + return; + } + let mut first = d.clone(); + first.fields.remove(super::form::PREVIEWED); + for k in STEP_FIELDS.iter().chain(&STEP_MARKS) { + match opened.get(*k) { + Some(v) => first.fields.insert(k.to_string(), v.clone()), + None => first.fields.remove(*k), + }; + } + sync(app, &mut first); + sync_theme(app, &mut first); + app.ui.recolor_history.base = Some(snapshot(&first)); +} + +impl History { + /// Take the fields of `d` as those after the last step when no step has them yet. + fn start(&mut self, d: &Dialog) { + if self.base.is_none() { + self.base = Some(snapshot(d)); + } + } + + /// Whether the fields of `d` differ from those after the last step. + fn pending(&self, d: &Dialog) -> bool { + self.base.as_ref().is_some_and(|b| STEP_FIELDS.iter().any(|k| d.fields.get(*k) != b.get(*k))) + } + + /// Record a change of `d`'s fields since the last step as a step. + fn note(&mut self, d: &Dialog) { + if self.base.is_some() && !self.pending(d) { + return; + } + if let Some(before) = self.base.replace(snapshot(d)) { + self.undo.push(before); + self.redo.clear(); + self.trim(); + } + } + + /// Drop the oldest steps past [`MAX_STEPS`] and [`MAX_STEP_BYTES`], keeping the newest step + /// even when it and the current fields alone pass the byte limit. + fn trim(&mut self) { + let extra = self.undo.len().saturating_sub(MAX_STEPS); + self.undo.drain(..extra); + let mut total: usize = self.base.iter().chain(&self.undo).map(snapshot_size).sum(); + let mut gone = 0; + while total > MAX_STEP_BYTES && gone + 1 < self.undo.len() { + total -= snapshot_size(&self.undo[gone]); + gone += 1; + } + self.undo.drain(..gone); + } + + fn can(&self, d: &Dialog, back: bool) -> bool { + // Before the first frame or command, fields set since the dialog opened are a step back, + // except rows and weights that the art's reduction is about to replace or drop ([`sync`]). + if self.base.is_none() + && let Some(opened) = &self.opened + { + let reduces = d.bool("__art") && d.fields.get("__reduced") != Some(&reduce_params(d)); + let kept = |k: &&&str| !(reduces && (**k == "rows" || **k == WEIGHTS)); + return back && STEP_FIELDS.iter().filter(kept).any(|k| d.fields.get(*k) != opened.get(*k)); + } + if back { !self.undo.is_empty() || self.pending(d) } else { !self.redo.is_empty() && !self.pending(d) } + } + + /// Undo Changes (`back`) or Redo Changes on `d`: give it the fields of the step before or after. + /// Returns false when there is none. + fn step(&mut self, d: &mut Dialog, back: bool) -> bool { + self.note(d); + let (from, to) = if back { (&mut self.undo, &mut self.redo) } else { (&mut self.redo, &mut self.undo) }; + let Some(s) = from.pop() else { return false }; + to.extend(self.base.take()); + for k in STEP_FIELDS.iter().chain(&STEP_MARKS) { + match s.get(*k) { + Some(v) => d.fields.insert(k.to_string(), v.clone()), + None => d.fields.remove(*k), + }; + } + // The rows hold no slider edit or drag, and the selection keeps to them. + for k in [COMPS, DRAG, BAR_DRAG, SHUFFLED] { + d.fields.remove(k); + } + let n = rows(d).len(); + d.fields.insert("__sel".into(), json!(selection(d).into_iter().filter(|i| *i < n).collect::>())); + self.base = Some(s); + true + } +} + +/// Undo Changes (`ui.recolorUndo`, `back`) or Redo Changes (`ui.recolorRedo`) in the open Recolor +/// Artwork dialog → {changed, canUndo, canRedo}. +pub(crate) fn step(app: &mut VectorcraftApp, back: bool) -> Result { + if app.ui.dialog.as_ref().is_none_or(|d| d.kind != KIND) { + return Err("Recolor Artwork is not open".into()); + } + let Some(mut d) = app.ui.dialog.take() else { return Err("Recolor Artwork is not open".into()) }; + // Fields set since the last frame take effect first, as the next frame would give them. + seed(app, &d); + sync(app, &mut d); + sync_theme(app, &mut d); + sync_weights(app, &mut d); + let mut h = std::mem::take(&mut app.ui.recolor_history); + let changed = h.step(&mut d, back); + let r = json!({"changed": changed, "canUndo": h.can(&d, true), "canRedo": h.can(&d, false)}); + app.ui.recolor_history = h; + // The art previews the step at once, as the frame after a button would preview it. + if changed && d.bool("__art") { + sync_weights(app, &mut d); + match find_params(&d) { + Some(p) => { + let _ = form::preview_now(app, &mut d, "Recolor Artwork", "command.batch", p); + } + None => { + let p = apply_params(&d); + form::preview_without_check(app, &mut d, "Recolor Artwork", CMD, p); + } + } + } + app.ui.dialog = Some(d); + Ok(r) +} + +/// Whether Undo Changes (`back`) or Redo Changes can run: Recolor Artwork is open with a step to go to. +pub(crate) fn can_step(app: &VectorcraftApp, back: bool) -> bool { + app.ui.dialog.as_ref().filter(|d| d.kind == KIND).is_some_and(|d| app.ui.recolor_history.can(d, back)) +} + /// OK: keep the previewed recolour as one undo step (or apply it, e.g. to a colour group only; or /// save colours opened alone as a new colour group). fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { @@ -1450,9 +1664,12 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } 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})); + let r = form::commit_preview(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true}))?; + app.ui.recolor_history = History::default(); + return Ok(r); } let r = form::commit_preview(app, CMD, apply_params(&d))?; + app.ui.recolor_history = History::default(); // The Preserve checkboxes (shown with art) open as confirmed here next time (#2960). if d.bool("__art") { app.ui.recolor_preserve = @@ -3449,6 +3666,47 @@ mod tests { assert_eq!(g.swatches.iter().filter_map(|w| w.paint.color()).collect::>(), [Color::rgb8(255, 128, 0)]); } + /// Undo Changes keeps at most [`MAX_STEPS`] steps and [`MAX_STEP_BYTES`] of them, the oldest + /// going first; fields that change nothing make no step, and with fields larger than the limit + /// only the newest step is kept, so Undo Changes is never on with no step to go to. + #[test] + fn undo_changes_keeps_a_bounded_history() { + let mut d = Dialog::new(KIND, json!({"rows": [], "colors": null})); + let mut h = History::default(); + h.note(&d); + h.note(&d); + assert!(h.undo.is_empty(), "no change, no step"); + for n in 0..MAX_STEPS + 6 { + d.fields.insert("colors".into(), json!(n)); + h.note(&d); + } + assert_eq!(h.undo.len(), MAX_STEPS, "the oldest steps go first"); + assert_eq!(h.undo[0]["colors"], json!(5)); + // Rows of 100 KiB each: the steps kept stay within the byte limit. + let big = |n: usize| json!([{"from": [format!("{n}{}", "x".repeat(100 << 10))], "to": null}]); + for n in 0..60 { + d.fields.insert("rows".into(), big(n)); + h.note(&d); + } + let size = |s: &Snapshot| serde_json::to_vec(s).unwrap().len(); + let total: usize = h.base.iter().chain(&h.undo).map(size).sum(); + assert!(total <= MAX_STEP_BYTES, "{total}"); + assert!(h.undo.len() < 60 && !h.undo.is_empty(), "{}", h.undo.len()); + assert!(h.step(&mut d, true), "the newest step is kept"); + assert_eq!(d.fields["rows"], big(58)); + // Current fields past the limit alone: only the step to them is kept, so Undo Changes + // still goes back one step. + d.fields.insert("rows".into(), json!([{"from": ["x".repeat(MAX_STEP_BYTES)], "to": null}])); + h.note(&d); + assert!(h.undo.len() == 1 && h.redo.is_empty(), "{}", h.undo.len()); + d.fields.insert("colors".into(), json!(1)); + assert!(h.can(&d, true), "the change to colors is a step too"); + assert!(h.step(&mut d, true), "and it is kept"); + assert_eq!(d.fields["colors"], json!(MAX_STEPS + 5), "Undo Changes gives back the colors before it"); + assert_eq!(h.undo.len(), 0, "the step before it went to keep the newest"); + assert!(!h.can(&d, true)); + } + /// 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> { @@ -3536,6 +3794,105 @@ mod tests { assert_eq!(group_hex(&app, "A"), Some(vec!["#ff0000".into(), "#00ff00".into()]), "other groups are left as they are"); } + /// Without art: selecting another color group in the list and Save Changes leave Undo Changes + /// and Redo Changes no step to go to, so OK gives the selected group the rows read for it. + #[test] + fn another_group_or_save_changes_leaves_nothing_to_undo() { + 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(); + frame(&mut app, &ctx, 0.0, vec![], 0); + let edit = |app: &mut VectorcraftApp, to: &str| { + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[0]["to"] = json!(to); + d.fields.insert("rows".into(), Value::Array(rs)); + }; + edit(&mut app, "rgb 0 0 0"); + frame(&mut app, &ctx, 0.1, vec![], 0); + assert!(super::can_step(&app, true), "the edit is a step"); + + set(&mut app, "group", json!("B")).unwrap(); + frame(&mut app, &ctx, 0.2, vec![], 0); + assert!(!super::can_step(&app, true) && !super::can_step(&app, false), "another group leaves no step"); + assert_eq!(super::step(&mut app, true).unwrap()["changed"], json!(false)); + assert_eq!(new_colors(&app).len(), 3, "the rows of B"); + + edit(&mut app, "rgb 0 128 0"); + frame(&mut app, &ctx, 0.3, vec![], 0); + assert!(super::can_step(&app, true), "the edit is a step"); + act(&mut app, &ctx, 0.4, "save").unwrap(); + assert_eq!(group_hex(&app, "B"), Some(vec!["#008000".into(), "#ffff00".into(), "#ffffff".into()])); + assert!(!super::can_step(&app, true) && !super::can_step(&app, false), "Save Changes leaves no step"); + assert_eq!(super::step(&mut app, true).unwrap()["changed"], json!(false)); + + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(group_hex(&app, "B"), Some(vec!["#008000".into(), "#ffff00".into(), "#ffffff".into()]), "OK keeps B's saved colors"); + assert_eq!(group_hex(&app, "A"), Some(vec!["#ff0000".into(), "#00ff00".into()]), "and leaves A as it was"); + } + + /// Without art: rows set after another color group is selected, with no frame between, are a + /// step back to the rows read for that group. + #[test] + fn an_edit_right_after_another_group_is_a_step() { + 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(); + frame(&mut app, &ctx, 0.0, vec![], 0); + set(&mut app, "group", json!("B")).unwrap(); + assert!(!super::can_step(&app, true) && !super::can_step(&app, false), "another group leaves no step"); + let b = new_colors(&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)); + assert!(super::can_step(&app, true), "the edit is a step"); + assert_eq!(super::step(&mut app, true).unwrap()["changed"], json!(true)); + assert_eq!(new_colors(&app), b, "Undo Changes gives back the rows read for B"); + assert_eq!(super::step(&mut app, false).unwrap()["changed"], json!(true)); + assert_eq!(new_colors(&app)[0], json!("rgb 0 0 0"), "Redo Changes gives back the edit"); + } + + /// With art not linked to the group: Save Changes with the rows as the last Save Changes left + /// them, after an edit and Undo Changes, leaves Redo Changes no step to go to either. + #[test] + fn an_unchanged_save_changes_leaves_nothing_to_redo() { + 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(); + let (red, blue) = (square(&mut app, 10.0, "#ff0000"), square(&mut app, 40.0, "#0000ff")); + app.run("swatch.newGroup", json!({"name": "Plain", "colors": ["#ff0000", "#0000ff"], "keepModel": true})).unwrap(); + app.run("select.set", json!({"ids": [red, blue]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "Plain"})).unwrap(); + frame(&mut app, &ctx, 0.0, vec![], 0); + let edit = |app: &mut VectorcraftApp, to: &str| { + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[0]["to"] = json!(to); + d.fields.insert("rows".into(), Value::Array(rs)); + }; + edit(&mut app, "rgb 0 128 0"); + frame(&mut app, &ctx, 0.1, vec![], 0); + act(&mut app, &ctx, 0.2, "save").unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().fields.contains_key(SAVED_ROWS), "the art kept its colors"); + edit(&mut app, "rgb 0 0 0"); + frame(&mut app, &ctx, 0.3, vec![], 0); + assert_eq!(super::step(&mut app, true).unwrap()["changed"], json!(true)); + assert!(unchanged_since_save(app.ui.dialog.as_ref().unwrap()), "the rows are as saved"); + assert!(super::can_step(&app, false), "the edit can be redone"); + act(&mut app, &ctx, 0.4, "save").unwrap(); + assert!(!super::can_step(&app, true) && !super::can_step(&app, false), "Save Changes leaves no step"); + } + /// 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] @@ -3600,7 +3957,7 @@ mod tests { vectorcraft_color::Swatch { name: "Fade".into(), paint, global: false, spot: false } } - /// With art, the preview rewrites the group being edited, its other swatch included; Save + /// With art, the preview rewrites the group being edited and keeps its other swatch; Save /// Changes is still refused, as the group is without the preview, and Cancel leaves it as it was. #[test] fn saving_a_group_with_a_swatch_that_is_not_a_color_is_refused_while_previewing() { @@ -3619,12 +3976,17 @@ mod tests { 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"); + let row_of = |rs: &[Value], hex: &str| rs.iter().position(|r| super::from_colors(r).iter().any(|c| c.to_hex() == hex)).unwrap(); + let red_row = row_of(&rs, "#ff0000"); + rs[red_row]["to"] = json!("rgb 0 0 0"); + let blue_to = super::to_color(&rs[row_of(&rs, "#0000ff")]).unwrap().to_hex(); d.fields.insert("rows".into(), Value::Array(rs)); frame(&mut app, &ctx, 0.1, vec![], 0); assert!(app.session.in_interaction(), "the art previews"); - let previewed = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").map(|g| g.swatches.len()); - assert_eq!(previewed, Some(2), "the preview's rewrite of the group leaves out its other swatch"); + let previewed = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Mixed").map(|g| g.swatches.clone()); + assert_eq!(previewed.as_ref().map(Vec::len), Some(3), "the preview's rewrite of the group keeps its other swatch"); + assert_eq!(previewed.and_then(|s| s.last().cloned()), Some(fade_swatch()), "with its paint"); + assert_eq!(group_hex(&app, "Mixed"), Some(vec!["#000000".into(), blue_to]), "each color swatch takes its row's new color"); let refused: Result<(), String> = Err("color group `Mixed` holds swatches that are not colors, which Save Changes can't keep".into()); assert_eq!(act(&mut app, &ctx, 0.2, "save"), refused); crate::dialogs::cancel(&mut app); diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index c7c98a5de0..1812f41d42 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -37,12 +37,19 @@ pub(super) fn body(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let id = d.str("__effect"); let defaults = vectorcraft_effects::default_params(&id).unwrap_or(json!({})); - // Reset all resets the shape, view and light; the mapped graphics and the render - // settings stay. + // Reset all resets the shape, view and light; the mapped graphics, Map Art with its + // options and the render settings stay. let defaults = match defaults { Value::Object(mut m) => { - m.remove(vectorcraft_effects::GRAPHICS); - m.remove(vectorcraft_effects::RENDER); + for key in [ + vectorcraft_effects::GRAPHICS, + vectorcraft_effects::RENDER, + vectorcraft_effects::MAP_ART, + vectorcraft_effects::MAP_SHADE, + vectorcraft_effects::MAP_INVISIBLE, + ] { + m.remove(key); + } Value::Object(m) } other => other, @@ -175,6 +182,11 @@ pub(super) fn c3(s: &'static str) -> &'static str { /// first two, the light gizmo on Lighting. fn solid_controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, id: &str) { let classic = vectorcraft_effects::is_classic_three_d(id); + // Map Art takes the place of the tabs until its Done. + if classic && super::three_d_classic::map_art_open(d) { + super::three_d_classic::map_art_controls(app, ui, d); + return; + } let object = id == EXTRUDE || id == INFLATE || id == CLASSIC_EXTRUDE || id == CLASSIC_REVOLVE; let mut tabs = vec![]; if object { diff --git a/crates/ui-egui/src/dialogs/revolve/tests.rs b/crates/ui-egui/src/dialogs/revolve/tests.rs index 223c617981..dd5f05ad5d 100644 --- a/crates/ui-egui/src/dialogs/revolve/tests.rs +++ b/crates/ui-egui/src/dialogs/revolve/tests.rs @@ -106,6 +106,83 @@ fn button(pos: Pos2, pressed: bool) -> Event { Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Default::default() } } +#[test] +fn map_art_maps_a_symbol_onto_a_surface_of_extrude_and_bevel_classic() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width":300,"height":300})).unwrap(); + let mark = app.run("path.create", json!({"d":"M250 250L260 250L260 270L250 270Z"})).unwrap()["id"].clone(); + app.run("threeD.addGraphic", json!({"name":"Mark","ids":[mark]})).unwrap(); + app.run("path.create", json!({"d":"M50 50L150 50L150 150L50 150Z"})).unwrap(); + app.run("effect.dialog", json!({"effect":CLASSIC_EXTRUDE,"item":null})).unwrap(); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + theme::apply(&ctx, Default::default()); + let mut h = Harness { app, ctx, screen: vec2(1280.0, 900.0), texts: vec![] }; + h.settle(); + h.click(h.rect("Map Art…").center()); + assert!(h.app.ui.dialog.as_ref().unwrap().bool("__mapArt"), "Map Art… opens Map Art"); + let count: usize = h.texts.iter().find_map(|(s, _)| s.strip_prefix("/ ")).and_then(|n| n.parse().ok()).expect("the surface count"); + assert!(count >= 6, "a square's solid has at least six surfaces: {count}"); + // The Symbol menu maps the symbol onto the surface shown, the first. + h.click(h.rect("None").center()); + h.click(h.rect("Mark").center()); + let maps = |h: &Harness| vectorcraft_effects::surface_maps(&json!({"mapArt": h.app.ui.dialog.as_ref().unwrap().fields.get("mapArt").cloned()})); + assert_eq!(maps(&h).iter().map(|m| (m.surface, m.symbol.as_str(), m.scale_x)).collect::>(), [(1, "Mark", 100.0)]); + // The next surface has no map until it is given one; Scale to Fit fills the first. + h.click(h.rect(">").center()); + assert_eq!(h.value("__mapSurface"), 2.0); + assert_eq!(maps(&h).len(), 1); + h.click(h.rect("<").center()); + h.click(h.rect("Scale to Fit").center()); + assert!(maps(&h)[0].scale_x > 100.0, "the 10-point art is scaled up to the 100-point cap: {:?}", maps(&h)); + h.click(h.rect("Done").center()); + assert!(!h.app.ui.dialog.as_ref().unwrap().bool("__mapArt"), "Done goes back to the effect's options"); + dialogs::confirm(&mut h.app).unwrap(); + let state = h.app.session.doc().unwrap(); + let id = state.selection.objects[0]; + let params = &state.doc.node(id).unwrap().appearance.effects[0].params; + assert_eq!(vectorcraft_effects::surface_maps(params).len(), 1, "{params}"); + assert!(params.get("__mapArt").is_none() && params.get("__mapSurface").is_none(), "the dialog's own state stays out of the effect"); +} + +#[test] +fn map_art_maps_no_more_surfaces_than_an_object_takes() { + let max = vectorcraft_effects::MAX_MAPS; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width":300,"height":300})).unwrap(); + let mark = app.run("path.create", json!({"d":"M250 250L260 250L260 270L250 270Z"})).unwrap()["id"].clone(); + app.run("threeD.addGraphic", json!({"name":"Mark","ids":[mark]})).unwrap(); + // A star with 36 points has 72 corners, so its solid has two caps and 72 walls. + let corners: Vec = (0..72) + .map(|i| { + let (r, a) = (if i % 2 == 0 { 100.0 } else { 60.0 }, f64::from(i) * std::f64::consts::TAU / 72.0); + format!("{:.3} {:.3}", 150.0 + r * a.cos(), 150.0 + r * a.sin()) + }) + .collect(); + app.run("path.create", json!({"d": format!("M{}Z", corners.join(" L"))})).unwrap(); + app.run("effect.dialog", json!({"effect":CLASSIC_EXTRUDE,"item":null})).unwrap(); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + theme::apply(&ctx, Default::default()); + let mut h = Harness { app, ctx, screen: vec2(1280.0, 900.0), texts: vec![] }; + h.settle(); + h.click(h.rect("Map Art…").center()); + let count: usize = h.texts.iter().find_map(|(s, _)| s.strip_prefix("/ ")).and_then(|n| n.parse().ok()).expect("the surface count"); + assert!(count > max, "{count} surfaces"); + // Every map the object takes is used, and the surface shown has none. + let full: Vec = (1..=max).map(|surface| json!({"surface": surface, "symbol": "Mark"})).collect(); + let d = h.app.ui.dialog.as_mut().unwrap(); + d.fields.insert("mapArt".into(), json!(full)); + d.fields.insert("__mapSurface".into(), json!(max + 1)); + h.settle(); + h.click(h.rect("None").center()); + if h.texts.iter().any(|(s, _)| s == "Mark") { + h.click(h.rect("Mark").center()); + } + let raw = h.app.ui.dialog.as_ref().unwrap().fields.get("mapArt").cloned().unwrap_or_default(); + assert_eq!(raw.as_array().map(Vec::len), Some(max), "no map past the limit is written"); +} + #[test] fn values_labels_sliders_and_reset_dots_change_the_live_effect_in_one_undo_step() { let mut h = Harness::new(vec2(1280.0, 900.0)); @@ -694,6 +771,27 @@ fn every_3d_dialog_has_color_and_reset_all_restores_white() { } } +#[test] +fn reset_all_keeps_map_art_and_its_options() { + for effect in [CLASSIC_EXTRUDE, CLASSIC_REVOLVE] { + let mut h = Harness::with("M100 100L200 100L200 200L100 200Z", effect, vec2(1280.0, 900.0)); + h.settle(); + let maps = json!([{"surface": 1, "symbol": "Mark"}]); + let d = h.app.ui.dialog.as_mut().unwrap(); + d.fields.insert("mapArt".into(), maps.clone()); + d.fields.insert("mapShade".into(), json!(true)); + d.fields.insert("mapInvisible".into(), json!(true)); + d.fields.insert("rotationX".into(), json!(40.0)); + h.settle(); + h.click(h.response("revolve-reset-all").center()); + let d = h.app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.f64("rotationX", 0.0), -21.88, "{effect}: the view is reset"); + assert_eq!(d.fields.get("mapArt"), Some(&maps), "{effect}: the maps stay"); + assert!(d.bool("mapShade") && d.bool("mapInvisible"), "{effect}: Shade Artwork and Invisible Geometry stay"); + dialogs::cancel(&mut h.app); + } +} + #[test] fn light_list_add_select_edit_delete_and_reset_keep_each_light_independent() { for effect in [REVOLVE, EXTRUDE, INFLATE, vectorcraft_effects::ROTATE] { diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index c412bc2dcb..7ad629afb8 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -2,8 +2,9 @@ //! 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, Delete Color -//! and Restore Generated Table), image size and anti-aliasing, Clip to Artboard, sRGB, metadata, +//! 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 @@ -11,7 +12,8 @@ //! `optimized`, `2up`, `4up`), `__zoom` (`fit` or a percentage), `__kbps` (connection speed), //! `__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), `__presetName` (shown while saving a +//! 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 @@ -242,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) }) } @@ -386,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()) } @@ -535,6 +549,7 @@ 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; // In a window too narrow for both, the panes are narrower, so the settings beside them and the @@ -565,6 +580,12 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { 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 } @@ -623,9 +644,9 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, set ui.add_space(6.0); let mut browser = false; // Preview in Browser goes on a row of its own when the panes are too narrow for it beside the - // two lists (its width as `widgets::secondary_button` draws it). - let label = tl!("Preview in Browser"); - let button_w = (ui.painter().layout_no_wrap(label.to_string(), crate::theme::semibold(12.5), t.text).size().x + 32.0).max(72.0); + // two lists. + let label = "Preview in Browser"; + let button_w = widgets::button_width(ui, label); let mut beside = false; let mut button = |ui: &mut egui::Ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { @@ -1088,7 +1109,9 @@ fn matte_row(ui: &mut egui::Ui, d: &mut Dialog) { /// 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. Returns an error for a deletion that would leave +/// (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()); @@ -1117,15 +1140,20 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Re .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( @@ -1144,6 +1172,15 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Re } } 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 { @@ -1161,18 +1198,37 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Re let pickable = !c.transparent || *mapped; 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 && resp.clicked() && resp.interact_pointer_pos().is_some_and(|pos| r.contains(pos)) { + 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 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")), @@ -1183,21 +1239,30 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Re "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. - let (mut delete, mut restore) = (false, false); + // 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, !picked.is_empty(), 24.0).clicked(); + 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"), !picked.is_empty(), false) { + if widgets::menu_item(ui, tl!("Delete Color"), deletable, false) { delete = true; ui.close(); } @@ -1205,6 +1270,10 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Re 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; @@ -1219,14 +1288,20 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Re if restore { restore_table(d); } + if unshift_all { + unshift_all_colors(d); + } if delete { - let palette: Vec = - shot.colors.iter().filter(|c| !c.transparent).map(|c| hex(c.source)).chain(shot.mapped.iter().map(|c| hex(*c))).collect(); 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 = @@ -1276,11 +1351,14 @@ pub(super) fn pick(d: &mut Dialog, order: &[String], color: &str, shift: bool, c /// 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. The selection is -/// cleared. +/// 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 = selection(d); + 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 { @@ -1316,6 +1394,9 @@ pub(super) fn delete_colors(d: &mut Dialog, palette: &[String]) -> Result<(), St } } } + for c in &picked { + unshift(d, c); + } set_table(d, "customPalette", json!(custom)); set_table(d, "deleted", json!(deleted)); d.fields.remove("__colors"); @@ -1330,6 +1411,71 @@ pub(super) fn restore_table(d: &mut Dialog) { 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. pub(super) fn toggle(d: &mut Dialog, list: &str, color: &str, add: bool) { let mut v: Vec = d.fields.get("colorTable").and_then(|t| t.get(list)).and_then(Value::as_array).cloned().unwrap_or_default(); diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index edfb66e7f4..a8db555bfb 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -4,7 +4,8 @@ //! The fields are the `document.exportPdf` options (sections are objects such as `compression`), //! plus `preset`, `range`, `path?` and UI-only `__` keys, so agents fill the dialog with //! `ui.dialog.set`. OK runs `document.exportPdf` through [`io::export_pdf`]; the Summary is -//! `document.pdfSettings`. Save Preset… names the settings as a preset (`pdf.preset.save`). +//! `document.pdfSettings`, and its Save Summary… writes it to a text file (`ui.pdfSummary.save`). +//! Save Preset… names the settings as a preset (`pdf.preset.save`). //! Opened from Export As with Use Artboards off (`__artBounds`), the dialog has no Artboards //! section, and OK writes one page of the visible art's bounds through [`io::export`]; opened //! from Export Selection (`__selection` too), the page is the selection's crop. While Alt (Option @@ -18,8 +19,8 @@ use std::sync::LazyLock; use serde_json::{Map, Value, json}; use vectorcraft_doc::Unit; -use vectorcraft_engine::cmd::FlattenOptions; use vectorcraft_engine::cmd::fileio::{SaveMode, pdf}; +use vectorcraft_engine::cmd::{FlattenOptions, FlattenerPreset}; use vectorcraft_pdf::{ Changes, Choice, ColorConversion, Compatibility, Downsample, Encryption, ImageCodec, JpegQuality, MarkKind, MonoCodec, Overprint, PdfSettings, Printing, ProfileInclusion, Standard, @@ -37,11 +38,22 @@ pub(super) const SPEC: DialogSpec = DialogSpec { body, confirm, ok: Some("Save PDF"), - inputs: |_| &["path"], + inputs: |_| &["path", "flattener"], reset: Some(reset), ..DialogSpec::FORM }; +/// Custom Transparency Flattener Options, opened over Save PDF by Custom… beside Flattener preset. +pub(super) const CUSTOM_KIND: &str = "pdfFlattenerOptions"; + +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 +}; + /// The dialog kind of the preset editor (New / Edit in Edit → PDF Presets). pub(super) const PRESET_KIND: &str = "pdfPreset"; @@ -99,6 +111,19 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) -> Result { Some(v) => return Err(format!("useArtboards must be true or false, not {v}")), }; let mut fields = settings_fields(app, params)?; + // The PDF settings keep no flattener options: those asked for go over the flattener preset. + match params.get("flattener") { + None | Some(Value::Null) => {} + Some(f @ Value::Object(o)) => { + let known = serde_json::to_value(FlattenOptions::default()).unwrap_or_default(); + if let Some(k) = o.keys().find(|k| known.get(k.as_str()).is_none()) { + return Err(format!("flattener.{k} is not a flattener option")); + } + FlattenOptions::for_export(None, Some(f), &[]).map_err(|e| format!("flattener: {e}"))?; + fields.insert("flattener".into(), f.clone()); + } + Some(v) => return Err(format!("flattener must be an object of flattener options, not {v}")), + } let s = |k: &str| params.get(k).and_then(Value::as_str); fields.insert("preset".into(), json!(s("preset").unwrap_or(pdf::DEFAULT_PRESET))); fields.insert("__presets".into(), json!(pdf::presets(&app.session))); @@ -534,6 +559,10 @@ fn preset_rows(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { d.fields.remove(SAVE_AS); } }); + // `pdf.preset.save` keeps `flattenerPreset` but not `flattener`. + if d.fields.contains_key("flattener") { + note(ui, tl!("The PDF preset keeps the flattener preset but not the Custom… settings.")); + } } } @@ -552,10 +581,12 @@ fn apply_preset(app: &mut VectorcraftApp, d: &mut Dialog, name: &str) { const OPTION_FLAGS: [&str; 2] = ["__requireOpenPassword", "__restrictPermissions"]; /// Replace every option with `settings` (from [`settings_fields`]), the password checkboxes -/// included. The preset, the artboard choice, the path and the other UI-only fields (the section, -/// the Save Preset name) stay. +/// included, and let the bleed link follow the new values. The preset, the artboard choice, the +/// path and the other UI-only fields (the section, the Save Preset name) stay. fn replace_settings(d: &mut Dialog, settings: Map) { - d.fields.retain(|k, _| matches!(k.as_str(), "preset" | "range" | "path") || (k.starts_with("__") && !OPTION_FLAGS.contains(&k.as_str()))); + d.fields.retain(|k, _| { + matches!(k.as_str(), "preset" | "range" | "path") || (k.starts_with("__") && !OPTION_FLAGS.contains(&k.as_str()) && k != BLEED_LINKED) + }); d.fields.extend(settings); } @@ -687,25 +718,111 @@ 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. A flattener +/// preset set there drops the Custom… options, as choosing it in the dropdown does. +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(()) + } + "flattenerPreset" => { + d.fields.remove("flattener"); + 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. @@ -779,6 +896,103 @@ fn output(ui: &mut egui::Ui, d: &mut Dialog) { } } +/// The name of the flattener preset Save PDF `d` flattens with: its `flattenerPreset` (High +/// Resolution when empty), a built-in one named by id (`high`) as its name. +fn flattener_name(d: &Dialog) -> String { + let name = get(d, "flattenerPreset").as_str().map(str::trim).filter(|n| !n.is_empty()).unwrap_or(pdf::DEFAULT_FLATTENER); + FlattenOptions::preset_label(&name.to_ascii_lowercase()).unwrap_or(name).to_string() +} + +/// The flattener options Save PDF `d` flattens with: its preset, with the Custom… options over it. +fn flattener(d: &Dialog, saved: &[FlattenerPreset]) -> Result { + FlattenOptions::for_export(Some(&flattener_name(d)), d.fields.get("flattener"), saved) +} + +/// The switches the PDF 1.3 writer sets itself, which Custom Transparency Flattener Options show +/// but can't change: rasterized areas are always clipped to their regions and keep no alpha, and +/// overprints are kept only with Overprint set to Preserve. +const FIXED: [&str; 3] = ["clipComplexRegions", "preserveAlpha", "preserveOverprints"]; + +/// `o` as the PDF 1.3 writer flattens with it (see [`FIXED`]), for Save PDF `parent`. +fn as_written(o: &mut FlattenOptions, parent: &Dialog) { + o.clip_complex_regions = true; + o.preserve_alpha = false; + o.preserve_overprints &= choice::(parent, "advanced.overprint") != Some(Overprint::Discard); +} + +/// Custom Transparency Flattener Options over Save PDF `parent`, on the options it flattens with +/// (the default preset's while those are not valid). +pub(super) fn over(parent: &Dialog, saved: &[FlattenerPreset]) -> Dialog { + let mut o = flattener(parent, saved).unwrap_or_else(|_| FlattenOptions::preset(pdf::DEFAULT_FLATTENER).unwrap_or_default()); + let kept = o.preserve_overprints; + as_written(&mut o, parent); + let mut d = Dialog::new(CUSTOM_KIND, json!({})); + super::flatten::put_options(&mut d.fields, &o); + d.fields.insert(KEPT_OVERPRINTS.into(), json!(kept)); + d.fields.insert(super::PARENT.into(), serde_json::to_value(parent).unwrap_or_default()); + d +} + +/// The `preserveOverprints` value of the options Custom Transparency Flattener Options opened on, +/// before Overprint applies to it. +const KEPT_OVERPRINTS: &str = "__keptOverprints"; + +/// The options Custom Transparency Flattener Options `d` holds. +fn custom_options(d: &Dialog) -> Result { + FlattenOptions::from_params_with(&Value::Object(d.fields.clone()), &[]) +} + +/// The flattener options, with the switches of [`FIXED`] showing what the PDF 1.3 writer does. +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. + let (mut o, unread) = super::flatten::shown_options(&d.fields, ¤t); + if let Some(parent) = super::parent(d) { + as_written(&mut o, &parent); + } + super::flatten::fields_editor(ui, "pdf-flattener", &mut d.fields, &mut o, &unread, &FIXED); + 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); + form::caption(ui, tl!("PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept.")); + false +} + +/// OK: Save PDF again, flattening with these options over its preset (High Resolution when a saved +/// preset was deleted meanwhile). Options equal to the preset's leave the preset alone; bad options +/// keep the dialog open. +fn custom_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let mut o = custom_options(d)?; + let mut parent = super::parent(d).ok_or("the dialog it was opened over is no longer open")?; + let kept = d + .fields + .get(KEPT_OVERPRINTS) + .and_then(Value::as_bool) + .or_else(|| flattener(&parent, &app.session.prefs.flattener_presets).ok().map(|before| before.preserve_overprints)); + let base = match FlattenOptions::find_preset(&flattener_name(&parent), &app.session.prefs.flattener_presets) { + Some(base) => base, + None => { + set(&mut parent, "flattenerPreset", json!("")); + FlattenOptions::preset(pdf::DEFAULT_FLATTENER).unwrap_or_default() + } + }; + // The writer sets the first two itself, so they take the preset's values: options that + // otherwise match the preset leave its name showing. The writer keeps overprints only where the + // options and Overprint both keep them, so the options keep the value they opened with, even + // when their preset was deleted, changed or made again under its name meanwhile. + o.clip_complex_regions = base.clip_complex_regions; + o.preserve_alpha = base.preserve_alpha; + o.preserve_overprints = kept.unwrap_or(o.preserve_overprints); + if o == base { + parent.fields.remove("flattener"); + } else { + parent.fields.insert("flattener".into(), serde_json::to_value(&o).map_err(|e| e.to_string())?); + } + app.ui.dialog = Some(parent); + Ok(Value::Null) +} + fn advanced(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { heading(ui, tl!("Fonts")); let outline = get(d, "advanced.outlineText").as_bool() == Some(true); @@ -796,17 +1010,24 @@ fn advanced(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { || choice::(d, "standard").is_some_and(Standard::flattens); row(ui, tl!("Flattener preset:"), |ui| { let presets = app.session.flattener_presets(); - let names: Vec<&str> = presets.iter().map(|p| p.name.as_str()).collect(); - // The built-in presets come first (translated); the saved ones are names. - let builtins = names.len().saturating_sub(app.session.prefs.flattener_presets.len()); - let name = get(d, "flattenerPreset").as_str().map(str::trim).filter(|n| !n.is_empty()).unwrap_or(pdf::DEFAULT_FLATTENER); - // A built-in preset named by id (`high`) shows as its name. - let current = FlattenOptions::preset_label(&name.to_ascii_lowercase()).unwrap_or(name).to_string(); + let saved = &app.session.prefs.flattener_presets; + // [Custom] while Custom… options differ from the preset's. + let current = flattener(d, saved).ok(); + // The preset as the list names it: the export finds a name in any case. + let name = flattener_name(d); + let name = presets.iter().find(|p| p.name.eq_ignore_ascii_case(name.trim())).map_or(name.as_str(), |p| p.name.as_str()); + let mut custom = false; ui.add_enabled_ui(flat, |ui| { - if let Some(n) = super::mixed_dropdown(ui, "flattenerPreset", ¤t, &names, 200.0, |k| k < builtins).and_then(|i| names.get(i)) { - set(d, "flattenerPreset", json!(n)); + if let Some(p) = super::flatten::preset_dropdown(ui, "flattenerPreset", &presets, name, current.as_ref(), 200.0) { + set(d, "flattenerPreset", json!(p.name)); + d.fields.remove("flattener"); } + // PDF presets keep no custom flattener options, so the preset editor has no Custom…. + custom = d.kind == KIND && widgets::flat_button_fit(ui, tl!("Custom…"), 72.0).clicked(); }); + if custom { + *d = over(d, saved); + } }); if flat { let name = get(d, "flattenerPreset").as_str().map(str::trim).filter(|n| !n.is_empty()).unwrap_or(pdf::DEFAULT_FLATTENER); @@ -909,26 +1130,57 @@ pub(super) fn option_label(option: &str) -> String { } /// `document.pdfSettings` for the dialog with the document's warnings (an export in memory), -/// cached until a field or the document changes. +/// cached until a field, the document, the saved PDF or flattener presets, the loaded color +/// profiles or the available fonts change. fn summary_of(app: &mut VectorcraftApp, ctx: &egui::Context, p: &Value) -> Result { - let revision = app.session.active().map_or(0, |s| s.revision); - let stamp = egui::Id::unique((p.to_string(), revision)); - let key = egui::Id::unique("save-pdf-summary"); + let (key, stamp) = summary_key(app, p); if let Some((s, v)) = ctx.data(|m| m.get_temp::<(egui::Id, Result)>(key)) && s == stamp { return v; } - let mut q = p.clone(); - q["includeDocument"] = json!(true); - let v = app.session.execute("document.pdfSettings", &q).map_err(|e| e.to_string()); + let v = summary_settings(app, p); ctx.data_mut(|m| m.insert_temp(key, (stamp, v.clone()))); v } +/// Where [`summary_of`] keeps the Summary, and the stamp of what it was computed for: the params +/// `p`, the active document and its revision, the saved PDF presets (which `preset` can name), the +/// saved flattener presets (which `flattenerPreset` can name), the loaded color profiles (which +/// `output.destination` and `output.outputIntent` can name) and the available fonts (which decide +/// what is embedded or outlined). +fn summary_key(app: &VectorcraftApp, p: &Value) -> (egui::Id, egui::Id) { + let document = app.session.active().map(|s| (s.uid, s.revision)); + let prefs = &app.session.prefs; + let presets = serde_json::to_string(&(&prefs.pdf_presets, &prefs.flattener_presets)).unwrap_or_default(); + let shared = (vectorcraft_color::cms::profiles_generation(), vectorcraft_text::FontDb::global().generation()); + (egui::Id::unique("save-pdf-summary"), egui::Id::unique((p.to_string(), document, presets, shared))) +} + +/// `document.pdfSettings` for the dialog's `document.exportPdf` params `p`, with the document's +/// warnings (an export in memory). +fn summary_settings(app: &mut VectorcraftApp, p: &Value) -> Result { + let mut q = p.clone(); + q["includeDocument"] = json!(true); + app.session.execute("document.pdfSettings", &q).map_err(|e| e.to_string()) +} + +/// The `document.pdfSettings` params of the Summary: the dialog's export params, without the +/// preset editor's own `name` and `description`, which are not PDF options. +fn summary_params(d: &Dialog) -> Value { + let mut p = params(d); + if d.kind == PRESET_KIND + && let Some(o) = p.as_object_mut() + { + o.remove("name"); + o.remove("description"); + } + p +} + fn summary(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { let t = Tokens::get(ui.ctx()); - let v = match summary_of(app, ui.ctx(), ¶ms(d)) { + let v = match summary_of(app, ui.ctx(), &summary_params(d)) { Ok(v) => v, Err(e) => { heading(ui, tl!("Error")); @@ -937,31 +1189,145 @@ fn summary(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { } }; heading(ui, tl!("Options")); - let mut changed: Vec<&Value> = v["changed"].as_array().map(|a| a.iter().collect()).unwrap_or_default(); - changed.sort_by_key(|c| section_of(c["option"].as_str().unwrap_or_default())); + let changed = changed_options(&v); if changed.is_empty() { - let base = if d.kind == PRESET_KIND { pdf::DEFAULT_PRESET } else { tl!("the preset") }; - note(ui, &crate::i18n::fmt(tl!("Every option matches {base}."), &[("base", base)])); + note(ui, &unchanged_line(d)); } option_rows(ui, changed, option_label); heading(ui, tl!("Warnings")); warning_rows(ui, v["warnings"].as_array().map(Vec::as_slice).unwrap_or_default()); + ui.add_space(8.0); + if widgets::secondary_button(ui, tl!("Save Summary…")).clicked() { + // The text of the Summary drawn now: saving it does not compute the settings again. + let text = summary_text(d, &v); + if let Err(e) = crate::picks::in_dialog(app, d, move |app, d| save_summary_from_dialog(app, d, &text)) { + app.status(e); + } + } +} + +/// The changed options of `document.pdfSettings`'s reply `v`, in the order of the sections. +fn changed_options(v: &Value) -> Vec<&Value> { + let mut changed: Vec<&Value> = v["changed"].as_array().map(|a| a.iter().collect()).unwrap_or_default(); + changed.sort_by_key(|c| section_of(c["option"].as_str().unwrap_or_default())); + changed +} + +/// The Summary's line when no option differs from the preset. +fn unchanged_line(d: &Dialog) -> String { + let base = if d.kind == PRESET_KIND { pdf::DEFAULT_PRESET } else { tl!("the preset") }; + crate::i18n::fmt(tl!("Every option matches {base}."), &[("base", base)]) +} + +/// The Summary of `document.pdfSettings`'s reply `v` as text, line for line as the section shows +/// it in the interface language: Options and each changed option (or the line saying none +/// changed), a blank line, then Warnings and each warning (or "None."). Lines end in LF, including +/// line breaks inside an option's value. +fn summary_text(d: &Dialog, v: &Value) -> String { + let lang = crate::i18n::current(); + let mut lines = vec![tl!("Options").to_string()]; + let changed = changed_options(v); + if changed.is_empty() { + lines.push(unchanged_line(d)); + } + lines.extend(changed.into_iter().map(|c| option_line(c, option_label))); + lines.push(String::new()); + lines.push(tl!("Warnings").to_string()); + let warnings = v["warnings"].as_array().map(Vec::as_slice).unwrap_or_default(); + if warnings.is_empty() { + lines.push(tl!("None.").to_string()); + } + lines.extend(warnings.iter().map(|w| warning_line(lang, w.as_str().unwrap_or_default()))); + let mut text = lines.join("\n").replace("\r\n", "\n").replace('\r', "\n"); + text.push('\n'); + text +} + +/// The UI command that writes the Summary to a text file. +pub(crate) const SAVE_SUMMARY: &str = "ui.pdfSummary.save"; + +/// Is a dialog with the Summary open (Save PDF, or the preset editor)? +pub(crate) fn summary_open(app: &VectorcraftApp) -> bool { + app.ui.dialog.as_ref().is_some_and(|d| d.kind == KIND || d.kind == PRESET_KIND) +} + +/// `ui.pdfSummary.save {path}`: write the open Save PDF dialog's (or preset editor's) Summary as +/// text to `path` (the web downloads it under the path's file name). The Summary the section last +/// drew for the same fields, document, saved PDF and flattener presets, loaded color profiles +/// and available fonts is used as it is; the settings are computed only when there is none. The dialog stays open and the document is not changed → +/// `{path, bytes}`. A missing, empty or non-string `path` is an error that writes nothing. +pub(crate) fn save_summary(app: &mut VectorcraftApp, p: &Value) -> Result { + let key = "path"; + let path = match p.get(key) { + None | Some(Value::Null) => return Err("missing `path`".into()), + Some(Value::String(s)) if s.trim().is_empty() => return Err("path is empty".into()), + Some(Value::String(s)) => Some(s.clone()), + Some(_) => return Err(format!("`{key}` must be a string")), + }; + let d = app.ui.dialog.clone().filter(|_| summary_open(app)).ok_or("the Save PDF dialog is not open")?; + let p = summary_params(&d); + let v = match app.ui_ctx.clone() { + Some(ctx) => summary_of(app, &ctx, &p), + None => summary_settings(app, &p), + }?; + write_summary(app, path, &summary_text(&d, &v)) +} + +/// Save Summary…: the Summary's `text` to a file picked in a save panel (the web downloads it). A +/// write that fails is told in a message over the dialog, which shows again when it closes; a +/// canceled panel writes nothing. +fn save_summary_from_dialog(app: &mut VectorcraftApp, d: &mut Dialog, text: &str) -> Result<(), String> { + let waiting = app.ui.told.len(); + let r = write_summary(app, None, text); + // The message about a failed write: the open dialog when the panel answered after this frame, + // else waiting behind the dialog being drawn. + let told = app.ui.dialog.take_if(|t| t.kind == super::confirm::MESSAGE).or_else(|| { + (app.ui.told.len() > waiting && app.ui.told.last().is_some_and(|t| t.kind == super::confirm::MESSAGE)).then(|| app.ui.told.pop()).flatten() + }); + if let Some(mut told) = told { + told.fields.insert(super::PARENT.into(), serde_json::to_value(&*d).unwrap_or_default()); + *d = told; + } + match r { + Err(e) if e == "cancelled" => Ok(()), + r => r.map(|_| ()), + } +} + +/// Write the Summary's `text` (UTF-8) to `path`, else to a picked ` PDF Summary.txt` +/// next to the document → `{path, bytes}`. +fn write_summary(app: &mut VectorcraftApp, path: Option, text: &str) -> Result { + let title = app.session.active().map(|d| d.title()).unwrap_or_default(); + let stem = std::path::Path::new(&title).file_stem().map_or_else(|| "Untitled".into(), |s| s.to_string_lossy().into_owned()); + let path = io::write_named(app, path, &format!("{stem} PDF Summary.txt"), text.as_bytes())?; + app.status(format!("Saved {path}")); + Ok(json!({ "path": path, "bytes": text.len() })) } /// A Summary line per changed option (`{option, value}`), labelled by `label`. pub(super) fn option_rows<'a>(ui: &mut egui::Ui, changed: impl IntoIterator, label: impl Fn(&str) -> String) { let t = Tokens::get(ui.ctx()); for c in changed { - let value = match &c["value"] { - Value::Bool(b) => if *b { tl!("On") } else { tl!("Off") }.to_string(), - Value::String(s) if c["option"] == "marks.kind" => choice_label(crate::i18n::current(), "marks.kind", s).to_string(), - Value::String(s) => s.clone(), - other => other.to_string(), - }; - ui.label(egui::RichText::new(format!("{} {value}", crate::i18n::colon(&label(c["option"].as_str().unwrap_or_default())))).color(t.text)); + ui.label(egui::RichText::new(option_line(c, &label)).color(t.text)); } } +/// The displayed value of the changed option `c` (`{option, value}`). +fn option_value(c: &Value) -> String { + match &c["value"] { + Value::Bool(b) => if *b { tl!("On") } else { tl!("Off") }.to_string(), + Value::String(s) if c["option"] == "marks.kind" => choice_label(crate::i18n::current(), "marks.kind", s).to_string(), + Value::String(s) => s.clone(), + other => other.to_string(), + } +} + +/// The Summary's line for the changed option `c` (`{option, value}`), labeled by `label`, with the +/// colon the interface language writes. +fn option_line(c: &Value, label: impl Fn(&str) -> String) -> String { + format!("{} {}", crate::i18n::colon(&label(c["option"].as_str().unwrap_or_default())), option_value(c)) +} + /// The Summary's warnings ("None." without any). pub(super) fn warning_rows(ui: &mut egui::Ui, warnings: &[Value]) { let t = Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index 6e02006cac..501aed4ed0 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -68,6 +68,372 @@ fn every_section_draws() { assert!(warnings.len() == 1 && warnings[0].as_str().unwrap().contains("permissions"), "{warnings:?}"); } +/// `ui.pdfSummary.save` writes the Summary as the section shows it, as UTF-8 text with LF line +/// endings: Options with each changed option in the order of the sections, a blank line, then +/// Warnings. The dialog stays open and the document does not change. +#[test] +fn save_summary_writes_the_summary_as_text() { + let (mut app, written, _) = app(); + app.run("file.export.pdf", json!({})).unwrap(); + set_field(&mut app, "thumbnails", json!(true)); + set_field(&mut app, "security.printing", json!("low")); + let revision = app.session.active().unwrap().revision; + let r = app.run(SAVE_SUMMARY, json!({"path": "/tmp/Ünïcode (1) summary.txt"})).unwrap(); + assert_eq!(r["path"], "/tmp/Ünïcode (1) summary.txt", "the path is used as given"); + let w = written.borrow(); + assert_eq!(w.len(), 1); + assert_eq!(w[0].0, "/tmp/Ünïcode (1) summary.txt"); + assert_eq!(r["bytes"], w[0].1.len()); + let text = String::from_utf8(w[0].1.clone()).expect("UTF-8"); + assert!(!text.contains('\r') && text.ends_with('\n'), "LF line endings: {text:?}"); + let lines: Vec<&str> = text.lines().collect(); + assert_eq!(lines[..5], ["Options", "General › Thumbnails: On", "Security › Printing: low", "", "Warnings"], "{text}"); + assert!(lines.len() == 6 && lines[5].starts_with("⚠ ") && lines[5].contains("permissions"), "{text}"); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND), "the dialog stays open"); + assert_eq!(app.session.active().unwrap().revision, revision, "the document does not change"); + assert_eq!(app.ui.status, "Saved /tmp/Ünïcode (1) summary.txt"); +} + +/// A text option whose value holds CRLF or CR line breaks is written with LF line breaks, so the +/// file has one kind of line ending. +#[test] +fn save_summary_writes_line_breaks_in_values_as_lf() { + let (mut app, written, _) = app(); + app.run("file.export.pdf", json!({})).unwrap(); + set_field(&mut app, "output.outputCondition", json!("first\r\nsecond\rthird")); + app.run(SAVE_SUMMARY, json!({"path": "/tmp/summary.txt"})).unwrap(); + let text = String::from_utf8(written.borrow()[0].1.clone()).unwrap(); + assert!(!text.contains('\r'), "LF line endings: {text:?}"); + assert!(text.contains("first\nsecond\nthird\n"), "{text:?}"); +} + +/// With every option as the preset has it and nothing to warn about, the file holds the lines +/// that say so, in the interface language. +#[test] +fn save_summary_writes_the_lines_for_no_changes_and_no_warnings() { + let (mut app, written, _) = app(); + app.run("file.export.pdf", json!({})).unwrap(); + app.run(SAVE_SUMMARY, json!({"path": "/tmp/summary.txt"})).unwrap(); + let text = String::from_utf8(written.borrow()[0].1.clone()).unwrap(); + assert_eq!(text, "Options\nEvery option matches the preset.\n\nWarnings\nNone.\n"); + crate::i18n::set_current(crate::i18n::Lang::from_code("de").expect("de registered")); + let r = app.run(SAVE_SUMMARY, json!({"path": "/tmp/zusammenfassung.txt"})); + crate::i18n::set_current(crate::i18n::Lang::EN); + r.unwrap(); + let de = String::from_utf8(written.borrow()[1].1.clone()).unwrap(); + let de_lang = crate::i18n::Lang::from_code("de").unwrap(); + let expected = format!( + "{}\n{}\n\n{}\n{}\n", + crate::i18n::tr(de_lang, "Options"), + crate::i18n::fmt(crate::i18n::tr(de_lang, "Every option matches {base}."), &[("base", crate::i18n::tr(de_lang, "the preset"))]), + crate::i18n::tr(de_lang, "Warnings"), + crate::i18n::tr(de_lang, "None."), + ); + assert_eq!(de, expected); + assert_ne!(de, text, "the labels are translated"); +} + +/// The preset editor's Summary is saved too, measured against the app's default preset, and the +/// editor stays open. +#[test] +fn save_summary_writes_the_preset_editors_summary() { + let (mut app, written, _) = app(); + open_preset(&mut app, &json!({})).unwrap(); + set_field(&mut app, "thumbnails", json!(true)); + app.run(SAVE_SUMMARY, json!({"path": "/tmp/preset summary.txt"})).unwrap(); + let text = String::from_utf8(written.borrow()[0].1.clone()).unwrap(); + assert_eq!(text, "Options\nGeneral › Thumbnails: On\n\nWarnings\nNone.\n"); + set_field(&mut app, "thumbnails", json!(false)); + app.run(SAVE_SUMMARY, json!({"path": "/tmp/preset summary.txt"})).unwrap(); + let text = String::from_utf8(written.borrow()[1].1.clone()).unwrap(); + assert_eq!(text, format!("Options\nEvery option matches {}.\n\nWarnings\nNone.\n", pdf::DEFAULT_PRESET)); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(PRESET_KIND), "the editor stays open"); +} + +/// A path that is empty or not a string, and no Save PDF dialog open, are errors that write +/// nothing. +#[test] +fn save_summary_refuses_a_bad_path_and_a_closed_dialog() { + let (mut app, written, _) = app(); + assert_eq!(app.run(SAVE_SUMMARY, json!({"path": "/tmp/s.txt"})).unwrap_err(), "the Save PDF dialog is not open"); + app.run("file.export.pdf", json!({})).unwrap(); + assert_eq!(app.run(SAVE_SUMMARY, json!({"path": ""})).unwrap_err(), "path is empty"); + assert_eq!(app.run(SAVE_SUMMARY, json!({"path": " "})).unwrap_err(), "path is empty"); + assert_eq!(app.run(SAVE_SUMMARY, json!({"path": 5})).unwrap_err(), "`path` must be a string"); + assert!(written.borrow().is_empty()); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); +} + +/// The command needs a path: omitted or null, it is an error that shows no save panel and writes +/// nothing. +#[test] +fn save_summary_requires_a_path() { + let (mut app, written, _) = app(); + let asked: Rc> = Rc::default(); + let a = asked.clone(); + app.services.pick_save = Some(Box::new(move |pick: &crate::FilePick| { + *a.borrow_mut() += 1; + Some(format!("/tmp/{}", pick.name)) + })); + app.run("file.export.pdf", json!({})).unwrap(); + assert_eq!(app.run(SAVE_SUMMARY, json!({})).unwrap_err(), "missing `path`"); + assert_eq!(app.run(SAVE_SUMMARY, json!({"path": null})).unwrap_err(), "missing `path`"); + assert_eq!(*asked.borrow(), 0, "no save panel"); + assert!(written.borrow().is_empty()); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); +} + +/// The command uses the Summary the section drew for the same fields and document, without +/// computing the settings again (an export in memory), and computes them once a field changes. +#[test] +fn save_summary_uses_the_summary_the_section_drew() { + let (mut app, written, _) = app(); + app.run("file.export.pdf", json!({})).unwrap(); + set_field(&mut app, "__section", json!("Summary")); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + app.ui_ctx = Some(ctx.clone()); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + // The drawn Summary, replaced with one that no computation gives. + let (key, stamp) = summary_key(&app, ¶ms(app.ui.dialog.as_ref().unwrap())); + let drawn = ctx.data(|m| m.get_temp::<(egui::Id, Result)>(key)).expect("the section's Summary"); + assert_eq!(drawn.0, stamp, "drawn for these fields"); + let kept: Result = Ok(json!({"changed": [{"option": "thumbnails", "value": "kept"}], "warnings": []})); + ctx.data_mut(|m| m.insert_temp(key, (stamp, kept))); + app.run(SAVE_SUMMARY, json!({"path": "/tmp/a.txt"})).unwrap(); + let text = String::from_utf8(written.borrow()[0].1.clone()).unwrap(); + assert_eq!(text, "Options\nGeneral › Thumbnails: kept\n\nWarnings\nNone.\n"); + set_field(&mut app, "thumbnails", json!(true)); + app.run(SAVE_SUMMARY, json!({"path": "/tmp/b.txt"})).unwrap(); + let text = String::from_utf8(written.borrow()[1].1.clone()).unwrap(); + assert!(text.starts_with("Options\nGeneral › Thumbnails: On\n"), "computed for the changed field: {text}"); +} + +/// The Summary drawn for one document is not used for another that becomes active with the same +/// revision and the same fields. +#[test] +fn save_summary_does_not_use_another_documents_summary() { + let (mut app, written, _) = app(); + let first = app.session.active_index().unwrap(); + let revision = app.session.active().unwrap().revision; + app.run("file.new", json!({"width": 120, "height": 90})).unwrap(); + let second = app.session.active_index().unwrap(); + app.session.set_active(first); + app.run("file.export.pdf", json!({})).unwrap(); + let ctx = egui::Context::default(); + app.ui_ctx = Some(ctx.clone()); + let (key, stamp) = summary_key(&app, ¶ms(app.ui.dialog.as_ref().unwrap())); + let kept: Result = Ok(json!({"changed": [{"option": "thumbnails", "value": "kept"}], "warnings": []})); + ctx.data_mut(|m| m.insert_temp(key, (stamp, kept))); + app.session.set_active(second); + app.session.active_mut().unwrap().revision = revision; + app.run(SAVE_SUMMARY, json!({"path": "/tmp/a.txt"})).unwrap(); + let text = String::from_utf8(written.borrow()[0].1.clone()).unwrap(); + assert!(!text.contains("kept"), "the other document's Summary: {text}"); +} + +/// The Summary is computed again when the saved preset it compares against is replaced while the +/// dialog stays open. +#[test] +fn save_summary_compares_against_a_replaced_preset() { + let (mut app, written, _) = app(); + app.run("pdf.preset.save", json!({"name": "Mine", "thumbnails": true})).unwrap(); + app.run("ui.savePdfDialog", json!({"preset": "Mine"})).unwrap(); + set_field(&mut app, "thumbnails", json!(false)); + app.ui_ctx = Some(egui::Context::default()); + app.run(SAVE_SUMMARY, json!({"path": "/tmp/a.txt"})).unwrap(); + let text = String::from_utf8(written.borrow()[0].1.clone()).unwrap(); + assert!(text.starts_with("Options\nGeneral › Thumbnails: Off\n"), "{text}"); + app.run("pdf.preset.save", json!({"name": "Mine", "thumbnails": false})).unwrap(); + app.run(SAVE_SUMMARY, json!({"path": "/tmp/b.txt"})).unwrap(); + let text = String::from_utf8(written.borrow()[1].1.clone()).unwrap(); + assert!(text.starts_with("Options\nEvery option matches the preset.\n"), "compared against the replaced preset: {text}"); +} + +/// The Summary is computed again when the saved flattener preset the dialog names is deleted while +/// the dialog stays open: the settings are then refused, and nothing is written. +#[test] +fn save_summary_sees_a_deleted_flattener_preset() { + let (mut app, written, _) = app(); + app.run("flattener.presets.save", json!({"name": "Mine Flat", "preset": "Low Resolution"})).unwrap(); + app.run("file.export.pdf", json!({})).unwrap(); + set_field(&mut app, "flattenerPreset", json!("Mine Flat")); + app.ui_ctx = Some(egui::Context::default()); + app.run(SAVE_SUMMARY, json!({"path": "/tmp/a.txt"})).unwrap(); + app.run("flattener.presets.delete", json!({"name": "Mine Flat"})).unwrap(); + let e = app.run(SAVE_SUMMARY, json!({"path": "/tmp/b.txt"})).unwrap_err(); + assert!(e.contains("Mine Flat"), "the deleted preset is refused: {e}"); + assert_eq!(written.borrow().len(), 1, "nothing written for the deleted preset"); +} + +/// The Summary is computed again when a loaded profile the dialog converts to is removed while the +/// dialog stays open: the settings are then refused, and nothing is written. +#[test] +fn save_summary_sees_a_removed_profile() { + use vectorcraft_color::cms; + let name = "Summary Stamp CMYK"; + // The built-in CMYK profile's file renamed `name`: padded with spaces, which names drop. + let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::>(); + let mut bytes = cms::icc_bytes(cms::DEVICE_CMYK).unwrap().to_vec(); + let (from, to) = (utf16(cms::DEVICE_CMYK), utf16(&format!("{name: PDF +/// Summary.txt`, the file holds the text the section shows, and the dialog stays open. A canceled +/// panel writes nothing; a failed write is told over the dialog, which shows again when the +/// message closes. The web downloads the file under the suggested name. +#[test] +fn the_save_summary_button_writes_the_summary() { + let (mut app, written, _) = app(); + let suggested: Rc>> = Rc::default(); + let s = suggested.clone(); + app.services.pick_save = Some(Box::new(move |pick: &crate::FilePick| { + s.borrow_mut().push(pick.name.clone()); + Some(format!("/tmp/{}", pick.name)) + })); + app.run("file.export.pdf", json!({})).unwrap(); + set_field(&mut app, "__section", json!("Summary")); + set_field(&mut app, "thumbnails", json!(true)); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + click_save_summary(&mut app, &ctx); + let title = app.session.active().unwrap().title(); + let stem = std::path::Path::new(&title).file_stem().unwrap().to_string_lossy().into_owned(); + let name = format!("{stem} PDF Summary.txt"); + assert_eq!(suggested.borrow()[..], *std::slice::from_ref(&name)); + { + let w = written.borrow(); + assert_eq!(w.len(), 1, "written once"); + assert_eq!(w[0].0, format!("/tmp/{name}")); + let text = String::from_utf8(w[0].1.clone()).unwrap(); + assert!(text.starts_with("Options\nGeneral › Thumbnails: On\n\nWarnings\n"), "{text}"); + } + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND), "the dialog stays open"); + // Canceled: nothing written, no status, the dialog stays. + app.services.pick_save = Some(Box::new(|_: &crate::FilePick| None)); + app.ui.status.clear(); + click_save_summary(&mut app, &ctx); + assert_eq!(written.borrow().len(), 1, "a canceled panel writes nothing"); + assert!(app.ui.status.is_empty(), "{}", app.ui.status); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); + // A failed write: a message names the file, over the dialog. + app.services.pick_save = Some(Box::new(|pick: &crate::FilePick| Some(format!("/tmp/{}", pick.name)))); + app.services.write = Some(Box::new(|_: &str, _: &[u8]| Err("disk full".into()))); + click_save_summary(&mut app, &ctx); + let told = app.ui.dialog.clone().expect("a message"); + assert_eq!(told.kind, super::super::confirm::MESSAGE, "status {:?}, waiting {:?}", app.ui.status, app.ui.told); + assert!(told.str("message").contains(&name), "{:?}", told.fields); + assert_eq!(super::super::parent(&told).map(|d| d.kind), Some(KIND.to_string()), "the dialog is under the message"); + super::super::cancel(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND), "the dialog shows again"); + // The web downloads it under the suggested name. + let downloads: Log = Log::default(); + let dl = downloads.clone(); + app.services.download = Some(Box::new(move |n: &str, b: &[u8]| { + dl.borrow_mut().push((n.to_string(), b.to_vec())); + Ok(()) + })); + click_save_summary(&mut app, &ctx); + let d = downloads.borrow(); + assert_eq!(d.len(), 1); + assert_eq!(d[0].0, name); + assert!(String::from_utf8(d[0].1.clone()).unwrap().starts_with("Options\n")); +} + +/// The saved Summary writes each option line with the colon the interface language uses, as the +/// Summary section shows it: French puts a no-break space before the colon, Japanese writes a +/// full-width colon. +#[test] +fn the_summary_text_uses_the_languages_colon() { + let changed = json!({"option": "thumbnails", "value": true}); + for (code, colon) in [("en", ":"), ("fr", "\u{a0}:"), ("ja", ":")] { + crate::i18n::set_current(crate::i18n::Lang::from_code(code).expect("registered")); + let line = option_line(&changed, |_| "X".to_string()); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert!(line.starts_with(&format!("X{colon} ")), "{code}: {line:?}"); + } +} + +/// Click the Summary section's Save Summary… button in frames of the dialog layer (the dialog's +/// window draws nothing in its first frame, which sizes it). +fn click_save_summary(app: &mut VectorcraftApp, ctx: &egui::Context) { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0)); + let run = |app: &mut VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + crate::tests_removeanchors::shapes_text(&out.shapes.iter().map(|c| c.shape.clone()).collect::>()) + }; + run(app, vec![]); + let labels = run(app, vec![]); + let at = + labels.iter().find(|(t, _)| t.trim() == "Save Summary…").map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no Save Summary… in {labels:?}")); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + run(app, vec![egui::Event::PointerMoved(at), button(true)]); + run(app, vec![button(false)]); +} + #[test] fn confirm_runs_export_pdf_with_the_dialog_options() { let (mut app, written, opened) = app(); @@ -464,6 +830,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"); @@ -721,3 +1282,291 @@ fn advanced_section_shows_raster_resolution_note() { frame(&mut app); assert!(app.ui.dialog.is_some()); } + +/// Headless frames of the dialog layer with screen-reader output. +struct Reader(egui::Context); + +impl Reader { + 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 mut out = + self.0.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + out + } + + /// The Custom… button of the open dialog, with whether it is enabled. + fn custom(&self, app: &mut VectorcraftApp) -> Option<(egui::accesskit::NodeId, bool)> { + self.run(app, vec![]); + let out = self.run(app, vec![]); + let nodes = &out.platform_output.accesskit_update.as_ref()?.nodes; + nodes.iter().find(|(_, n)| n.label() == Some("Custom…") && n.role() == egui::accesskit::Role::Button).map(|(id, n)| (*id, !n.is_disabled())) + } + + /// The labels and values the open dialog shows. + fn texts(&self, app: &mut VectorcraftApp) -> Vec { + self.run(app, vec![]); + let out = self.run(app, vec![]); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + nodes.iter().flat_map(|(_, n)| [n.label(), n.value()]).flatten().map(str::to_string).collect() + } + + /// Click Custom… in Save PDF's Advanced section. + fn click_custom(&self, app: &mut VectorcraftApp) { + let (node, enabled) = self.custom(app).expect("a Custom… button"); + assert!(enabled, "Custom… is enabled"); + let click = egui::accesskit::ActionRequest { + action: egui::accesskit::Action::Click, + target_node: node, + target_tree: egui::accesskit::TreeId::ROOT, + data: None, + }; + self.run(app, vec![egui::Event::AccessKitActionRequest(click)]); + } +} + +fn kind(app: &VectorcraftApp) -> Option<&str> { + app.ui.dialog.as_ref().map(|d| d.kind.as_str()) +} + +/// Save PDF on `params` (and `path`), showing Advanced. +fn open_advanced(app: &mut VectorcraftApp, params: Value) { + let mut p = params; + p["path"] = json!("/tmp/out.pdf"); + app.run("ui.savePdfDialog", p).unwrap(); + set_field(app, "__section", json!("Advanced")); +} + +/// A second rectangle, half transparent, over the first one. +fn transparent_overlap(app: &mut VectorcraftApp) { + app.run("select.none", json!({})).unwrap(); + app.run("shape.rectangle", json!({"x": 30, "y": 20, "width": 50, "height": 40})).unwrap(); + app.run("transparency.set", json!({"opacity": 50})).unwrap(); +} + +/// The images a written PDF reopens with. +fn images(pdf: &[u8]) -> usize { + let doc = vectorcraft_pdf::import(pdf).unwrap(); + let mut n = 0; + for l in &doc.layers { + l.walk(&mut |x| n += matches!(x.kind, vectorcraft_doc::NodeKind::Image(_)) as usize); + } + n +} + +#[test] +fn custom_is_enabled_where_the_save_flattens() { + let (mut app, _, _) = app(); + let r = Reader::new(); + for (params, flattens) in [ + (json!({"compatibility": "1.3"}), true), + (json!({"standard": "pdfX1a"}), true), + (json!({"standard": "pdfX3"}), true), + (json!({"compatibility": "1.4"}), false), + (json!({"standard": "pdfX4"}), false), + ] { + open_advanced(&mut app, params.clone()); + assert_eq!(r.custom(&mut app).map(|(_, enabled)| enabled), Some(flattens), "{params}"); + } + // PDF presets keep no custom flattener options, so the preset editor has no Custom…. + open_preset(&mut app, &json!({})).unwrap(); + set_field(&mut app, "__section", json!("Advanced")); + set_field(&mut app, "compatibility", json!("1.3")); + assert_eq!(r.custom(&mut app), None); +} + +#[test] +fn custom_starts_from_the_preset_and_cancel_goes_back_unchanged() { + let (mut app, _, _) = app(); + open_advanced(&mut app, json!({"compatibility": "1.3", "flattenerPreset": "low"})); + let r = Reader::new(); + r.custom(&mut app); + let before = app.ui.dialog.as_ref().unwrap().fields.clone(); + r.click_custom(&mut app); + assert_eq!(kind(&app), Some(CUSTOM_KIND)); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.f64("balance", 0.0), d.f64("gradientPpi", 0.0)), (75.0, 150.0), "Low Resolution's"); + // Low Resolution doesn't clip, but the PDF 1.3 writer does. + assert!(d.bool("clipComplexRegions"), "shown as written"); + app.ui.dialog.as_mut().unwrap().fields.insert("balance".into(), json!(10)); + super::super::cancel(&mut app); + assert_eq!(kind(&app), Some(KIND)); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields, before, "Cancel leaves Save PDF as it was"); +} + +#[test] +fn custom_options_are_written_until_a_preset_is_chosen() { + let (mut app, written, _) = app(); + transparent_overlap(&mut app); + open_advanced(&mut app, json!({"compatibility": "1.3"})); + let r = Reader::new(); + r.click_custom(&mut app); + app.ui.dialog.as_mut().unwrap().fields.insert("balance".into(), json!(0)); + super::super::confirm(&mut app).unwrap(); + assert_eq!(kind(&app), Some(KIND), "OK goes back to Save PDF"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.fields["flattener"]["balance"].as_f64(), Some(0.0)); + let saved = &app.session.prefs.flattener_presets; + assert_ne!(flattener(d, saved).ok(), FlattenOptions::preset(pdf::DEFAULT_FLATTENER), "the preset shows [Custom]"); + // A preset set through `ui.dialog.set` drops the custom options. + let kept = d.clone(); + let dialog = app.ui.dialog.as_mut().unwrap(); + assert!(super::super::accepts_field(dialog, "flattenerPreset")); + let old = dialog.fields.get("flattenerPreset").cloned(); + super::super::set_field(dialog, "flattenerPreset".into(), json!("Low Resolution")); + super::super::field_set(&mut app, "flattenerPreset", old.as_ref()).unwrap(); + assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("flattener")); + app.ui.dialog = Some(kept); + super::super::confirm(&mut app).unwrap(); + assert!(images(&written.borrow()[0].1) > 0, "balance 0 rasterizes the flattened art"); + open_advanced(&mut app, json!({"compatibility": "1.3"})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(images(&written.borrow()[1].1), 0, "High Resolution keeps it vector"); +} + +#[test] +fn custom_options_equal_to_the_preset_leave_its_name() { + let (mut app, _, _) = app(); + let r = Reader::new(); + for overprint in ["preserve", "discard"] { + open_advanced(&mut app, json!({"compatibility": "1.3", "flattenerPreset": "medium", "advanced": {"overprint": overprint}})); + r.click_custom(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().bool("preserveOverprints"), overprint == "preserve", "{overprint}"); + super::super::confirm(&mut app).unwrap(); + assert_eq!(kind(&app), Some(KIND)); + assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("flattener"), "{overprint}"); + } +} + +/// OK keeps Custom… options that drop overprints dropping them, although the preset keeps them. +#[test] +fn custom_keeps_options_that_drop_overprints() { + let (mut app, _, _) = app(); + let params = json!({"compatibility": "1.3", "advanced": {"overprint": "preserve"}, "flattener": {"preserveOverprints": false}}); + open_advanced(&mut app, params); + Reader::new().click_custom(&mut app); + assert!(!app.ui.dialog.as_ref().unwrap().bool("preserveOverprints"), "shown as written"); + super::super::confirm(&mut app).unwrap(); + assert_eq!(kind(&app), Some(KIND)); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(flattener(d, &app.session.prefs.flattener_presets).map(|o| o.preserve_overprints), Ok(false)); +} + +#[test] +fn custom_shows_alpha_as_the_pdf_1_3_writer_drops_it() { + let (mut app, written, _) = app(); + transparent_overlap(&mut app); + open_advanced(&mut app, json!({"compatibility": "1.3", "flattener": {"balance": 0, "preserveAlpha": true}})); + Reader::new().click_custom(&mut app); + assert!(!app.ui.dialog.as_ref().unwrap().bool("preserveAlpha"), "shown as written"); + super::super::confirm(&mut app).unwrap(); + assert_eq!(kind(&app), Some(KIND)); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["flattener"]["preserveAlpha"].as_bool(), Some(false)); + super::super::confirm(&mut app).unwrap(); + assert!(written.borrow()[0].1.starts_with(b"%PDF-1.3") && images(&written.borrow()[0].1) > 0); +} + +#[test] +fn bad_custom_options_keep_the_dialog_open() { + let (mut app, _, _) = app(); + open_advanced(&mut app, json!({"compatibility": "1.3"})); + Reader::new().click_custom(&mut app); + app.ui.dialog.as_mut().unwrap().fields.insert("gradientPpi".into(), json!(9000)); + let e = super::super::confirm(&mut app).unwrap_err(); + assert!(e.contains("resolutions"), "{e}"); + assert_eq!(kind(&app), Some(CUSTOM_KIND)); +} + +#[test] +fn custom_options_outlive_a_saved_preset_deleted_meanwhile() { + let (mut app, written, _) = app(); + app.run("flattener.presets.save", json!({"name": "Mine", "balance": 20})).unwrap(); + open_advanced(&mut app, json!({"compatibility": "1.3", "flattenerPreset": "Mine"})); + Reader::new().click_custom(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("balance", 0.0), 20.0, "the saved preset's"); + app.run("flattener.presets.delete", json!({"name": "Mine"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("balance".into(), json!(30)); + super::super::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("flattenerPreset"), d.fields["flattener"]["balance"].as_f64()), (String::new(), Some(30.0))); + super::super::confirm(&mut app).unwrap(); + assert!(written.borrow()[0].1.starts_with(b"%PDF-1.3")); +} + +/// OK keeps the overprint option of a saved preset deleted meanwhile, whichever value Overprint +/// shows it with, although the default preset keeps overprints. +#[test] +fn custom_keeps_the_overprint_option_of_a_saved_preset_deleted_meanwhile() { + let (mut app, _, _) = app(); + for (kept, overprint) in [(false, "preserve"), (true, "discard")] { + app.run("flattener.presets.save", json!({"name": "Mine", "balance": 20, "preserveOverprints": kept})).unwrap(); + open_advanced(&mut app, json!({"compatibility": "1.3", "flattenerPreset": "Mine", "advanced": {"overprint": overprint}})); + Reader::new().click_custom(&mut app); + assert!(!app.ui.dialog.as_ref().unwrap().bool("preserveOverprints"), "shown as written ({overprint})"); + app.run("flattener.presets.delete", json!({"name": "Mine"})).unwrap(); + super::super::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.fields["flattener"]["preserveOverprints"].as_bool(), Some(kept), "{overprint}"); + } +} + +/// OK keeps the overprint option Custom… opened with when its saved preset is deleted and made +/// again under the same name with another overprint option meanwhile. +#[test] +fn custom_keeps_the_overprint_option_it_opened_with_over_a_preset_made_again() { + let (mut app, _, _) = app(); + app.run("flattener.presets.save", json!({"name": "Mine", "balance": 20, "preserveOverprints": false})).unwrap(); + open_advanced(&mut app, json!({"compatibility": "1.3", "flattenerPreset": "Mine", "advanced": {"overprint": "preserve"}})); + Reader::new().click_custom(&mut app); + assert!(!app.ui.dialog.as_ref().unwrap().bool("preserveOverprints"), "shown as the preset had it"); + app.run("flattener.presets.delete", json!({"name": "Mine"})).unwrap(); + app.run("flattener.presets.save", json!({"name": "Mine", "balance": 20, "preserveOverprints": true})).unwrap(); + super::super::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.fields["flattener"]["preserveOverprints"].as_bool(), Some(false)); +} + +/// Flattener preset shows a preset named in another case by its name, not as [Custom]. +#[test] +fn flattener_preset_shows_a_name_given_in_any_case() { + let (mut app, _, _) = app(); + app.run("flattener.presets.save", json!({"name": "Mine", "balance": 20})).unwrap(); + let r = Reader::new(); + for (given, shown) in [("MINE", "Mine"), ("HIGH RESOLUTION", "High Resolution")] { + open_advanced(&mut app, json!({"compatibility": "1.3", "flattenerPreset": given})); + let texts = r.texts(&mut app); + assert!(texts.iter().any(|t| t == shown), "{given}: {texts:?}"); + assert!(!texts.iter().any(|t| t == "[Custom]"), "{given}: {texts:?}"); + } +} + +#[test] +fn save_preset_says_it_leaves_the_custom_flattener_options_out() { + let (mut app, _, _) = app(); + let r = Reader::new(); + let note = "The PDF preset keeps the flattener preset but not the Custom… settings."; + app.run("ui.savePdfDialog", json!({"compatibility": "1.3", "flattener": {"balance": 10}})).unwrap(); + set_field(&mut app, SAVE_AS, json!("Mine")); + assert!(r.texts(&mut app).iter().any(|t| t == note), "with Custom… options"); + app.ui.dialog.as_mut().unwrap().fields.remove("flattener"); + assert!(!r.texts(&mut app).iter().any(|t| t == note), "without them"); +} + +#[test] +fn save_pdf_opens_with_the_flattener_options_given_and_refuses_bad_ones() { + let (mut app, _, _) = app(); + app.run("ui.savePdfDialog", json!({"compatibility": "1.3", "flattener": {"lineArtPpi": 600}})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["flattener"], json!({"lineArtPpi": 600})); + for bad in [json!({"bogus": 1}), json!(5), json!({"gradientPpi": 9000})] { + app.ui.dialog = None; + assert!(app.run("ui.savePdfDialog", json!({"flattener": bad})).is_err(), "{bad}"); + assert!(app.ui.dialog.is_none(), "{bad}"); + } +} diff --git a/crates/ui-egui/src/dialogs/shortcut_import.rs b/crates/ui-egui/src/dialogs/shortcut_import.rs index e6c9a6ee0a..3409a0b987 100644 --- a/crates/ui-egui/src/dialogs/shortcut_import.rs +++ b/crates/ui-egui/src/dialogs/shortcut_import.rs @@ -518,6 +518,10 @@ pub fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } if let Some(k) = app.ui.dialog.as_mut() { k.fields.insert("overrides".into(), crate::keymap::stored::to_value(&shortcut_editor::saved_overrides(km.overrides(), &ov))); + // VectorCraft's defaults have no hold shortcuts; Add to the Current Shortcuts keeps them. + if !current { + k.fields.insert("holds".into(), json!({})); + } k.fields.insert("set".into(), json!(set)); k.fields.insert("__message".into(), json!(tl!("Imported. Press OK to keep the imported set."))); } diff --git a/crates/ui-egui/src/dialogs/svg_options.rs b/crates/ui-egui/src/dialogs/svg_options.rs index 13586ae3e1..c185a3d5cb 100644 --- a/crates/ui-egui/src/dialogs/svg_options.rs +++ b/crates/ui-egui/src/dialogs/svg_options.rs @@ -1,16 +1,19 @@ //! SVG Options (Export As SVG, Save As / Save a Copy to .svg): profile, styling, fonts, images, //! object ids, decimals, encoding, minify, responsive, embedded fonts, artboards (export) or //! editing data (save), and a read-only view of the code. OK remembers the choices for next time and runs the export or save command with -//! them as `svg: {…}`. +//! them as `svg: {…}`. Show in Browser (`file.export.svg.browser`) writes the SVG the choices give +//! to a temporary folder and opens it in the default browser, leaving the dialog open. +use std::borrow::Cow; use std::sync::Arc; use serde_json::{Map, Value, json}; +use vectorcraft_engine::cmd::fileio; use super::DialogSpec; use crate::state::Dialog; use crate::theme::{self, Tokens}; -use crate::{VectorcraftApp, widgets}; +use crate::{VectorcraftApp, io, widgets}; pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("SVG Options").into(), @@ -26,6 +29,12 @@ pub(super) const SPEC: DialogSpec = DialogSpec { /// `Dialog::kind` of this dialog. pub const KIND: &str = "svgOptions"; +/// The UI command of the dialog's Show in Browser button. +pub const BROWSER: &str = "file.export.svg.browser"; + +/// The folder in the system's temporary folder that Show in Browser's previews go to. +const PREVIEW_ROOT: &str = "VectorCraft SVG Preview"; + /// What OK does: Export As SVG, Save As or Save a Copy. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Mode { @@ -196,8 +205,16 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } ui.add_space(10.0); let show = d.bool("showCode"); - if widgets::secondary_button(ui, if show { tl!("Hide Code") } else { tl!("Show Code") }).clicked() { - d.fields.insert("showCode".into(), json!(!show)); + let mut browser = false; + ui.horizontal(|ui| { + if widgets::secondary_button(ui, if show { tl!("Hide Code") } else { tl!("Show Code") }).clicked() { + d.fields.insert("showCode".into(), json!(!show)); + } + let b = ui.add_enabled(!io::is_web(app), |ui: &mut egui::Ui| widgets::secondary_button(ui, tl!("Show in Browser"))); + browser = b.on_disabled_hover_text(tl!("Needs the desktop app")).clicked(); + }); + if browser && let Err(e) = app.run(BROWSER, preview_params(d)) { + app.status(e); } if show { ui.add_space(6.0); @@ -269,6 +286,102 @@ fn artboards(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { }); } +/// The SVG options the dialog `d`'s OK writes with: [`options`], with hidden layers kept (not +/// displayed) when OK saves, as a save keeps them unless told otherwise. +fn written_options(d: &Dialog) -> Value { + let mut o = options(d); + if Mode::of(d) != Mode::Export + && let Some(m) = o.as_object_mut() + { + m.entry("hiddenLayers").or_insert(json!(true)); + } + o +} + +/// The params of [`BROWSER`] for the dialog `d`: the SVG options OK writes with +/// ([`written_options`]), and `exportSelection` when Export Selection opened it. +fn preview_params(d: &Dialog) -> Value { + super::export_as::exported(d, json!({ "svg": written_options(d) })) +} + +/// The SVG file that the SVG options `svg` write for one page of the document `st`, and the +/// document it is drawn from. With `selection` (Export Selection) the page is the selection alone, +/// cropped to it. Otherwise it is the first artboard the options choose, checked against the +/// document's artboards as OK checks them, or what the options write without artboards (also for +/// a document that has none). Linked scripts and images are checked against the read roots in +/// force first. +fn encode_page<'a>( + st: &'a vectorcraft_engine::DocState, + svg: &Value, + selection: bool, +) -> Result<(Cow<'a, vectorcraft_doc::Document>, fileio::Encoded), String> { + let mut opts = svg.clone(); + if let Some(o) = opts.as_object_mut() { + if selection { + // Export Selection writes one crop, without artboards to choose. + for k in fileio::ARTBOARD_PARAMS.iter().chain(&["useArtboards"]) { + o.remove(*k); + } + } else if st.doc.artboards.is_empty() { + for k in fileio::ARTBOARD_PARAMS { + o.remove(k); + } + } else { + let pick: fileio::ArtboardPick = serde_json::from_value(Value::Object(o.clone())).map_err(|e| e.to_string())?; + if let Some(first) = pick.resolve(st.doc.artboards.len())?.and_then(|v| v.first().copied()) { + for k in fileio::ARTBOARD_PARAMS { + o.remove(k); + } + o.insert("artboard".into(), json!(first)); + } + } + } + let params = json!({ "svg": opts }); + fileio::check_linked_scripts("document.export", "svg", st, ¶ms).map_err(|e| e.to_string())?; + let doc = if selection { + Cow::Owned(fileio::selection_doc(st, "document.exportSelection", false).map_err(|e| e.to_string())?.0) + } else { + Cow::Borrowed(&*st.doc) + }; + fileio::check_linked_images("document.export", "svg", st, &doc, ¶ms).map_err(|e| e.to_string())?; + let enc = fileio::encode_all(&doc, "svg", ¶ms).map_err(|e| e.to_string())?; + Ok((doc, enc)) +} + +/// `file.export.svg.browser {svg?, exportSelection?}` (SVG Options' Show in Browser): the SVG file +/// that the SVG options `svg` write for one page ([`encode_page`]), written with its linked images +/// to a new folder inside `VectorCraft SVG Preview` in the system's temporary folder and opened in +/// the default browser (desktop) → `{path, warnings}`. Nothing is written to the chosen +/// destination, and the document, its path and the remembered choices are left as they were. +/// When the export has warnings, the status bar shows them as [`io::report_saved`] shows a save's +/// notes. Nothing opens when a check, the encoding or a write fails. +pub(crate) fn browser_preview(app: &mut VectorcraftApp, p: &Value) -> Result { + if io::is_web(app) { + return Err("no file system here".into()); + } + app.refuse_automation(BROWSER)?; + let (selection, p) = io::take_selection(p)?; + let svg = p.get("svg").cloned().unwrap_or_else(|| json!({})); + let (path, warnings) = { + let st = app.session.active().ok_or("no document")?; + let stem = fileio::file_stem(&st.doc.title); + let (doc, enc) = encode_page(st, &svg, selection)?; + let dir = super::save_for_web::temp_folder_under(PREVIEW_ROOT)?; + let target = format!("{dir}/{}.svg", super::save_for_web::preview_name(&stem)); + let named = enc.named(&doc, &target); + for (p, bytes) in &named { + io::write_to(&mut app.services, p, bytes)?; + } + (named.first().map_or(target, |(p, _)| p.clone()), enc.notes()) + }; + app.open_url(&io::file_url(&path)); + let r = json!({ "path": path, "warnings": warnings }); + if !warnings.is_empty() { + io::report_saved(app, &path, &r); + } + Ok(r) +} + /// The SVG the current options write for the first chosen artboard, or under Export Selection for /// the selection alone, cropped to it (read-only, selectable), encoded again only when the /// options, the document or the selection change. @@ -276,19 +389,7 @@ fn code_view(app: &VectorcraftApp, ui: &mut egui::Ui, d: &Dialog) { let t = Tokens::get(ui.ctx()); let Some(st) = app.session.active() else { return }; let selection = d.bool(super::export_as::SELECTION_FIELD); - let mut opts = options(d); - if let Some(o) = opts.as_object_mut() { - if selection { - // Export Selection writes one crop, without artboards to choose. - for k in vectorcraft_engine::cmd::fileio::ARTBOARD_PARAMS.iter().chain(&["useArtboards"]) { - o.remove(*k); - } - } else if let Some(r) = o.remove("range") { - // The first artboard of the range (or the first one). - let first = r.as_str().and_then(|r| r.split([',', '-', '\u{2013}']).next()).and_then(|n| n.trim().parse::().ok()); - o.insert("artboard".into(), json!(first.map_or(0, |n| n.saturating_sub(1)))); - } - } + let opts = written_options(d); // One cached text, replaced when the document, the options or the selection change. let key = egui::Id::unique("svg-code"); // The read roots in force and the document's folder decide whether the text may be shown. @@ -299,27 +400,15 @@ fn code_view(app: &VectorcraftApp, ui: &mut egui::Ui, d: &Dialog) { Some((_, c)) => c, None => { const MAX: usize = 200_000; - let params = json!({ "svg": opts }); - let encoded = vectorcraft_engine::cmd::fileio::check_linked_scripts("document.export", "svg", st, ¶ms).and_then(|()| { - let selected; - let doc = if selection { - selected = vectorcraft_engine::cmd::fileio::selection_doc(st, "document.exportSelection", false)?.0; - &selected - } else { - &st.doc - }; - vectorcraft_engine::cmd::fileio::check_linked_images("document.export", "svg", st, doc, ¶ms)?; - vectorcraft_engine::cmd::fileio::encode_all(doc, "svg", ¶ms) - }); - let mut text = match encoded { + let mut text = match encode_page(st, &opts, selection) { // Shown as text whatever the file's encoding. - Ok(enc) => enc + Ok((_, enc)) => enc .files .into_iter() .next() .map(|(_, b)| vectorcraft_svg::text_of(&b).map_or_else(|_| String::from_utf8_lossy(&b).into_owned(), |t| t.into_owned())) .unwrap_or_default(), - Err(e) => e.to_string(), + Err(e) => e, }; if text.len() > MAX { let cut = (0..=MAX).rev().find(|i| text.is_char_boundary(*i)).unwrap_or(0); @@ -389,6 +478,153 @@ mod tests { String::from_utf8(w.borrow()[i].1.clone()).unwrap() } + type Opened = Rc>>; + + /// [`app`] whose browser records each URL it is asked to open. + fn browsing(picked: &str) -> (VectorcraftApp, Written, Opened) { + let (mut app, written) = app(picked); + let opened = Opened::default(); + let o = opened.clone(); + app.services.open_url = Some(Box::new(move |u: &str| o.borrow_mut().push(u.to_string()))); + (app, written, opened) + } + + /// Show in Browser for the open dialog's current choices, as its button runs it. + fn show_in_browser(app: &mut VectorcraftApp) -> Result { + let p = preview_params(app.ui.dialog.as_ref().expect("SVG Options open")); + app.run(BROWSER, p) + } + + /// Show in Browser writes the SVG of the dialog's current, unconfirmed choices for the first + /// artboard of the range to a new temporary folder and opens that file once. The dialog stays + /// open, nothing is remembered, and OK then writes the same SVG to the chosen file. + #[test] + fn show_in_browser_opens_what_ok_writes_without_confirming() { + let (mut app, written, opened) = browsing("/tmp/out.svg"); + app.run("file.export.svg", Value::Null).unwrap(); + frame(&mut app); + let f = &mut app.ui.dialog.as_mut().unwrap().fields; + f.insert("decimals".into(), json!(1)); + f.insert("allArtboards".into(), json!(false)); + f.insert("range".into(), json!("2")); + let remembered = app.ui.svg_options.clone(); + let r = show_in_browser(&mut app).unwrap_or_else(|e| panic!("{e}")); + let path = r["path"].as_str().unwrap().to_string(); + assert!(path.contains("/VectorCraft SVG Preview/") && path.ends_with("/Untitled-1.svg"), "{path}"); + assert_eq!(*opened.borrow(), [io::file_url(&path)]); + assert_eq!(written.borrow().len(), 1); + assert_eq!(written.borrow()[0].0, path); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND), "the dialog stays open"); + assert_eq!(app.ui.svg_options, remembered, "nothing is remembered"); + assert!(app.session.active().unwrap().path.is_none()); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + assert_eq!(written.borrow()[1].0, "/tmp/out.svg"); + assert_eq!(text(&written, 0), text(&written, 1), "the preview is the file OK writes"); + assert_eq!(opened.borrow().len(), 1); + } + + /// A range the document has no artboard for is refused, as OK refuses it: nothing is written + /// or opened, and the dialog stays open. + #[test] + fn show_in_browser_refuses_a_range_the_document_lacks() { + let (mut app, written, opened) = browsing("/tmp/out.svg"); + app.run("file.export.svg", Value::Null).unwrap(); + let f = &mut app.ui.dialog.as_mut().unwrap().fields; + f.insert("allArtboards".into(), json!(false)); + f.insert("range".into(), json!("5")); + assert!(show_in_browser(&mut app).is_err()); + assert!(written.borrow().is_empty() && opened.borrow().is_empty()); + assert!(app.ui.dialog.is_some()); + } + + /// Under Export Selection the preview is the selection alone, cropped to it, as OK writes it. + #[test] + fn show_in_browser_under_export_selection_shows_the_selection() { + let (mut app, written, opened) = browsing("/tmp/selection.svg"); + app.run("shape.rectangle", json!({"x": 70, "y": 40, "width": 20, "height": 20})).unwrap(); + app.run("document.exportSelection", Value::Null).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().bool(super::super::export_as::SELECTION_FIELD)); + show_in_browser(&mut app).unwrap_or_else(|e| panic!("{e}")); + super::super::confirm(&mut app).unwrap(); + assert_eq!(written.borrow()[1].0, "/tmp/selection.svg"); + assert_eq!(text(&written, 0), text(&written, 1)); + assert_eq!(text(&written, 0).matches("