diff --git a/.coderabbit.yaml b/.coderabbit.yaml new file mode 100644 index 0000000000..2408084cf9 --- /dev/null +++ b/.coderabbit.yaml @@ -0,0 +1,6 @@ +# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json +reviews: + auto_review: + # Dependabot bumps are checked by CI; skip CodeRabbit reviews on them. + ignore_usernames: + - "dependabot[bot]" diff --git a/ASSETS.md b/ASSETS.md index 81b0bd630a..f8121c35bd 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -167,6 +167,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-new-fill.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-new-item.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-new-stroke.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-objects-on-path.svg` | VectorCraft contributors | Original work, drawn for VectorCraft: three small squares along a curve | MIT OR Apache-2.0 | | | `assets/icons/dc-options.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-para-center.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-para-justify-all.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | diff --git a/Cargo.lock b/Cargo.lock index 431791145f..312d2d5b00 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3852,6 +3852,17 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "sctk-adwaita" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec" +dependencies = [ + "log", + "smithay-client-toolkit 0.19.2", + "tiny-skia", +] + [[package]] name = "self_cell" version = "1.3.0" @@ -4688,7 +4699,7 @@ dependencies = [ [[package]] name = "vectorcraft" -version = "0.13.1" +version = "0.14.0" dependencies = [ "arboard", "block2 0.6.2", @@ -4725,7 +4736,7 @@ dependencies = [ [[package]] name = "vectorcraft-affinity" -version = "0.13.1" +version = "0.14.0" dependencies = [ "crc32fast", "flate2", @@ -4736,7 +4747,7 @@ dependencies = [ [[package]] name = "vectorcraft-brush" -version = "0.13.1" +version = "0.14.0" dependencies = [ "kurbo 0.13.1", "serde", @@ -4748,7 +4759,7 @@ dependencies = [ [[package]] name = "vectorcraft-cad" -version = "0.13.1" +version = "0.14.0" dependencies = [ "image", "kurbo 0.13.1", @@ -4764,7 +4775,7 @@ dependencies = [ [[package]] name = "vectorcraft-cli" -version = "0.13.1" +version = "0.14.0" dependencies = [ "log", "objc2-core-foundation", @@ -4786,7 +4797,7 @@ dependencies = [ [[package]] name = "vectorcraft-color" -version = "0.13.1" +version = "0.14.0" dependencies = [ "kurbo 0.13.1", "moxcms", @@ -4798,7 +4809,7 @@ dependencies = [ [[package]] name = "vectorcraft-doc" -version = "0.13.1" +version = "0.14.0" dependencies = [ "hayro-ccitt", "image", @@ -4816,7 +4827,7 @@ dependencies = [ [[package]] name = "vectorcraft-effects" -version = "0.13.1" +version = "0.14.0" dependencies = [ "image", "kurbo 0.13.1", @@ -4832,7 +4843,7 @@ dependencies = [ [[package]] name = "vectorcraft-engine" -version = "0.13.1" +version = "0.14.0" dependencies = [ "craft-docpath", "crc32fast", @@ -4875,7 +4886,7 @@ dependencies = [ [[package]] name = "vectorcraft-eps" -version = "0.13.1" +version = "0.14.0" dependencies = [ "fax", "flate2", @@ -4898,7 +4909,7 @@ dependencies = [ [[package]] name = "vectorcraft-format" -version = "0.13.1" +version = "0.14.0" dependencies = [ "flate2", "proptest", @@ -4913,7 +4924,7 @@ dependencies = [ [[package]] name = "vectorcraft-geom" -version = "0.13.1" +version = "0.14.0" dependencies = [ "kurbo 0.13.1", "proptest", @@ -4925,7 +4936,7 @@ dependencies = [ [[package]] name = "vectorcraft-mcp" -version = "0.13.1" +version = "0.14.0" dependencies = [ "image", "log", @@ -4944,7 +4955,7 @@ dependencies = [ [[package]] name = "vectorcraft-metafile" -version = "0.13.1" +version = "0.14.0" dependencies = [ "image", "kurbo 0.13.1", @@ -4958,7 +4969,7 @@ dependencies = [ [[package]] name = "vectorcraft-pathops" -version = "0.13.1" +version = "0.14.0" dependencies = [ "kurbo 0.13.1", "linesweeper", @@ -4970,7 +4981,7 @@ dependencies = [ [[package]] name = "vectorcraft-pdf" -version = "0.13.1" +version = "0.14.0" dependencies = [ "aes", "craft-pdf", @@ -5000,7 +5011,7 @@ dependencies = [ [[package]] name = "vectorcraft-plugins" -version = "0.13.1" +version = "0.14.0" dependencies = [ "serde", "serde_json", @@ -5014,7 +5025,7 @@ dependencies = [ [[package]] name = "vectorcraft-render" -version = "0.13.1" +version = "0.14.0" dependencies = [ "flate2", "gif", @@ -5041,14 +5052,14 @@ dependencies = [ [[package]] name = "vectorcraft-scriptcheck" -version = "0.13.1" +version = "0.14.0" dependencies = [ "proptest", ] [[package]] name = "vectorcraft-svg" -version = "0.13.1" +version = "0.14.0" dependencies = [ "craft-docpath", "flate2", @@ -5073,7 +5084,7 @@ dependencies = [ [[package]] name = "vectorcraft-testkit" -version = "0.13.1" +version = "0.14.0" dependencies = [ "fax", "image", @@ -5091,7 +5102,7 @@ dependencies = [ [[package]] name = "vectorcraft-text" -version = "0.13.1" +version = "0.14.0" dependencies = [ "harfrust 0.13.3", "icu_segmenter", @@ -5111,7 +5122,7 @@ dependencies = [ [[package]] name = "vectorcraft-three-d" -version = "0.13.1" +version = "0.14.0" dependencies = [ "vectorcraft-geom", "vectorcraft-pathops", @@ -5119,7 +5130,7 @@ dependencies = [ [[package]] name = "vectorcraft-tools" -version = "0.13.1" +version = "0.14.0" dependencies = [ "image", "kurbo 0.13.1", @@ -5135,7 +5146,7 @@ dependencies = [ [[package]] name = "vectorcraft-trace" -version = "0.13.1" +version = "0.14.0" dependencies = [ "image", "kurbo 0.13.1", @@ -5147,7 +5158,7 @@ dependencies = [ [[package]] name = "vectorcraft-ui-egui" -version = "0.13.1" +version = "0.14.0" dependencies = [ "craft-ui", "egui", @@ -5181,7 +5192,7 @@ dependencies = [ [[package]] name = "vectorcraft-web" -version = "0.13.1" +version = "0.14.0" dependencies = [ "eframe", "egui", @@ -6129,6 +6140,7 @@ dependencies = [ "raw-window-handle", "redox_syscall 0.4.1", "rustix 0.38.44", + "sctk-adwaita", "smithay-client-toolkit 0.19.2", "smol_str", "tracing", @@ -6292,7 +6304,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.13.1" +version = "0.14.0" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index 496c5de948..b6e948188a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/vectorcraft", "apps/vectorcraft-cli", "xtask"] [workspace.package] -version = "0.13.1" +version = "0.14.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" diff --git a/NOTICE b/NOTICE index bcd3055b96..5cf3c8952f 100644 --- a/NOTICE +++ b/NOTICE @@ -92,3 +92,34 @@ Assets already bundled through Hayro's default features retain their licences: non-visual character-mapping data; see licenses/pdf-backend/hayro-cmap/LICENSE.txt. Adobe and contributor names do not endorse or promote this product. Per-file hashes and sources are recorded in ASSETS.md. + +Linux Wayland window decorations +------------------------------- +sctk-adwaita 0.10.1 (https://github.com/PolyMeilex/sctk-adwaita, +commit d5f343c45c04d4a026db57f76760819b7325db00) is used by winit on Linux +for vector window controls. Its title-font features are disabled: no Cantarell +font is embedded by this dependency and no font file is added to this repo. + +sctk-adwaita's MIT licence: + +MIT License + +Copyright (c) 2022 Bartłomiej Maryńczak + +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/README.md b/README.md index 68aa538e7d..2dfcd8fb3c 100644 --- a/README.md +++ b/README.md @@ -20,11 +20,14 @@

- Status: in active development - Written in pure Rust - Runs on macOS, Windows, Linux, FreeBSD and the web - MCP server for agents - License: MIT OR Apache-2.0 + Status: in active development + Written in pure Rust + Runs on macOS, Windows, Linux, FreeBSD and the web + MCP server for agents + License: MIT OR Apache-2.0 +
+ Scanned by SonarCloud + Reviewed by CodeRabbit

@@ -163,6 +166,8 @@ exposes to agents, and exported by VectorCraft's own renderer. The source files ## Quick start +For posters and sewing patterns, see [Print a large poster across multiple pages](docs/print-tiling.md). + ```sh git clone https://github.com/storytold/vectorcraft cd vectorcraft @@ -178,6 +183,8 @@ cd apps/vectorcraft-web && trunk build --release # web build → dist cargo xtask ci # fmt, clippy, tests, layering, wasm, vendor names ``` +For text and custom letter shapes, see [Typography and Custom Lettering](docs/typography-lettering.md). + Japanese fonts come from [storytold/craft-fonts](https://github.com/storytold/craft-fonts), an optional build input (releases always use it): `CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo run --release -p vectorcraft` (an absolute path). Without it, Japanese text uses the installed system fonts. See [`docs/development.md`](docs/development.md#fonts-craft-fonts-optional-build-input). @@ -246,7 +253,7 @@ The scores are self-assessed from our code against public documentation; - reliable exchange of .ai files (layer structure in real files; proprietary editing data isn't written); - an interaction-fidelity pass covering every tool's modifiers and small behaviours; - 3D and Materials beyond the initial live Revolve (Extrude & Bevel, Inflate, Rotate, materials); -- about half of the raster effects (24 of 57 still missing; Cutout, Film Grain, Neon Glow and Poster Edges are available under Artistic, Halftone Pattern under Sketch) and the Effect Gallery; +- most of the raster effects (11 of 57 still missing; Cutout, Film Grain, Neon Glow, Plastic Wrap, Poster Edges, Smudge Stick, Sponge and Watercolor are available under Artistic, Bas Relief, Chalk & Charcoal, Charcoal, Chrome, Graphic Pen, Halftone Pattern, Note Paper, Photocopy, Plaster, Reticulation and Stamp under Sketch) and the Effect Gallery; - CJK composition for vertical type (vertical type itself has initial support, with a Japanese interface); - scripting, and the rest of Variables (image and graph kinds, dataset import); - generative AI features. diff --git a/ROADMAP.md b/ROADMAP.md index 579a791482..8ae1cf14af 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -9,7 +9,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-18 · **Change:** minor (Background Export progress dialog with Cancel, #2564; about 85 community PRs of 2026-10-18: Justification…, Word .docx placed as area type, CCITT Group 3 TIFF, Roman Hanging Punctuation, blend spines edited with the Anchor Point tool, shadows and glows in stack order, coloured 3D lights, a Dutch catalog completed; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; about 145 community PRs of 2026-10-17: image-decode overflow guards, opaque floating panels, MCP export cancel and progress, editable Illustrator EPS import, scoped `doc_inspect`, Dutch, Danish and Indonesian, Simplified Chinese messages, screen-reader names; headline numbers unchanged; about 160 community PRs of 2026-10-15/16: PDF import crash fixes, Dimension tool, legacy `.ai` save, Intertwine, web pen input, Image Trace fixes, `.ai`/EPS/PDF import fidelity, Bulgarian, Greek, Swedish and Finnish catalogs; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-19 · **Change:** minor (about 90 community PRs of 2026-10-19: Objects on Path, the Simplify slider, Pencil Edit Selected Paths in the middle of a path, Georgian, and more; Background Export progress dialog with Cancel, #2564; about 85 community PRs of 2026-10-18: Justification…, Word .docx placed as area type, CCITT Group 3 TIFF, Roman Hanging Punctuation, blend spines edited with the Anchor Point tool, shadows and glows in stack order, coloured 3D lights, a Dutch catalog completed; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; about 145 community PRs of 2026-10-17: image-decode overflow guards, opaque floating panels, MCP export cancel and progress, editable Illustrator EPS import, scoped `doc_inspect`, Dutch, Danish and Indonesian, Simplified Chinese messages, screen-reader names; headline numbers unchanged; about 160 community PRs of 2026-10-15/16: PDF import crash fixes, Dimension tool, legacy `.ai` save, Intertwine, web pen input, Image Trace fixes, `.ai`/EPS/PDF import fidelity, Bulgarian, Greek, Swedish and Finnish catalogs; headline numbers unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -29,7 +29,7 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)). | | Value | Kind | |---|---|---| -| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 348/375 wired (92.8%), tools 89/92, Illustrator effects 46/50, Photoshop effects 33/57, 3D 4/4 (initial types, no materials) | +| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 348/375 wired (92.8%), tools 89/92, Illustrator effects 46/50, Photoshop effects 46/57, 3D 4/4 (initial types, no materials) | | **Feature depth** (weighted by use, scored by behaviour) | **~75%** | estimated | | **To beta** | **~170–270 h** one agent · ~50–80 h with 4–6 agents | estimated | | **To full parity** | **~360–590 h** one agent · ~95–165 h with 4–6 agents | estimated | @@ -76,7 +76,7 @@ The dimension hours overlap (feature rows hold some UI, format and AI work), so | Strokes, brushes, width profiles | 88% | 8–15 | | Appearance, transparency, graphic styles, masks | 97% | 1–2 | | Live vector effects | 85% | 6–10 | -| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 49% | 21–35 | +| Raster effects (Effect Gallery) — [effects-parity.md](docs/effects-parity.md) | 81% | 8–14 | | 3D and Materials | ~25% | 30–55 | | Type core — [type-parity.md](docs/type-parity.md) | 80% | 14–19 | | Type advanced (CJK, spelling, Touch Type) | 50% | 20–28 | @@ -123,7 +123,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap 2. **`.ai` files from real users** (G9): layer structure, guides, speed: 10–20 h. 3. **Launch and stability on real machines** (G10): 20–35 h. 4. **Core-tool correctness** (G11: Shape Builder regions, Asset Export borders): 8–15 h. -5. **Raster effects** (G2) alongside: 24 filters and the Effect Gallery, 21–35 h. +5. **Raster effects** (G2) alongside: the 11 remaining filters (7 Artistic, 3 Sketch, 1 more) and the Effect Gallery, 8–14 h. 6. **Then:** type core and advanced type (G4), the Illustrator 2026 additions (G13), 3D (G3). ## Progress log @@ -134,8 +134,10 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap | Date | What landed | |---|---| -| 2026-10-18 | Exported and saved files can repeat their bytes: PNG, PDF, EPS, legacy `.ai`, packaged zips and `.vectorcraft` saves recorded the wall-clock time they were made in, so the same commands run twice gave different bytes though the pixels matched. `SOURCE_DATE_EPOCH` now stands in for the clock in everything a file records, as the reproducible-builds specification defines it; a date a command is given still wins, and a malformed value is ignored rather than refusing the export. The recovery heartbeat and the seed PDF encryption draws on keep the real clock (#2880). Headline numbers unchanged. | +| 2026-10-18 | Inch rulers divide the inch in half, not in ten. Zooming in stepped an inch ruler through 0.2, 0.1 and 0.05 of an inch, marks an inch ruler does not carry; below an inch the steps are binary fractions now, 1/2 down to 1/16, with the unlabelled ticks between them binary too (down to 1/128, so the 32nds, 64ths and 128ths appear as the report expects), while the metric units, points, pixels and picas keep their tenths. A label carries the decimals its step needs, so a sixteenth reads 0.0625 rather than the rounded 0.06, with trailing zeros dropped (#2827). Headline numbers unchanged. | +| 2026-10-18 | Exported and saved files can repeat their bytes: PNG, PDF, EPS, legacy `.ai`, packaged zips and `.vectorcraft` saves recorded the wall-clock time they were made in, so the same commands run twice gave different bytes though the pixels matched. `SOURCE_DATE_EPOCH` now stands in for the clock in everything a file records, as the reproducible-builds specification defines it; a date a command is given still wins, and a malformed value is ignored rather than refusing the export. The recovery heartbeat and the seed PDF encryption draws on keep the real clock, so a password-protected PDF still differs between runs (#2880). Headline numbers unchanged. | | 2026-10-18 | About 85 community PRs landed in two batches through the full gate, with our fixes on top. New: Word `.docx` files place as area type with their formatting (#2766), CCITT Group 3 TIFF files open (#2770), Paragraph panel menu › Roman Hanging Punctuation (#2775), the Anchor Point tool edits blend spine points and handles (#2643, fixes #2544), shadows and glows each draw from the art with the effects before them, without the old exponential cost (#2395), one to ten coloured lights in 3D effects (#2706), Artboard Options X and Y with a reference point (#2739), more Contextual Task Bar actions (#2471), Optical Margin Alignment for a whole thread (#2773), History panel Step Backward/Forward and Set History Limit (#2764), Edit › Undo and Redo name the step as the History panel does (#2774), bounding-box handles snap to the grid, pixels and guides (#2715), Ctrl/Cmd+A in the Artboards panel (#2761), Tabs panel menu items (#2742), Import Data Sets defines variables from header cells (#2736), a Linux option to use X11 when a pen is attached (#2717). Fidelity and robustness: variable fonts named by their default weight and fallback glyphs keep bold and italic (#2733, #2732), legacy `.ai` layer names in Windows Latin-1 (#2722), WMF window mapping (#2721), Magic Wand inside isolation (#2720), type values out of range in files are clamped (#2728, #2757), raster effects stay responsive in drags (#2745), exports and Save for Web report undecodable images (#2762, #2737, #2684), Windows-safe exported file names (#2738), a marquee skips a Shaper Group's originals (#2772). Second batch: an export progress dialog with Cancel on the shared cancel token (#2564), CMYK gradient meshes drawn several times faster within a 16 MB cap (#2802), Paragraph panel menu › Justification… with file values clamped (#2771), Edit › Clear History (#2843), SVG image links keep their spelling (#2837, fixes main's Windows test failures), the Linux save dialog through the XDG portal (#2783), RGB input stored as CMYK in CMYK documents (#2812), legacy `.ai` export of images and radial highlights (#2801, #2807), `.ai` import notes for damaged editing data, page sizes and variable libraries (#2799, #2800, #2842), PDF and `.ai` keep their creation date (#2838), undecodable images left out of PDF exports with a note (#2790), MCP input waits for queue room (#2776), slice, snapping, selection, type and accessibility fixes (#2794–#2797, #2805, #2806, #2809, #2815, #2844–#2846), dropdowns close after a keyboard pick (#2824), plug-in dialogs scroll (#2840). Languages: the Dutch catalog completed (#2730). Headline numbers unchanged (estimated). | +| 2026-10-19 | About 90 community PRs landed in batches through the full gate, with our fixes on top (formatting, catalog rows, small correctness fixes). New: Objects on Path (#3066), Object › Path › Simplify's slider with Auto-Simplify and More Options (#2555), Pencil Edit Selected Paths redraws the middle of a selected path (#2905), Pencil Tool Options' Alt key toggles to Smooth Tool (#2685), 3D solids built from each stroke's outline (#3049), Live Paint Selection Tool Options (#3052), Locate Selected Objects in the Layers panel (#3033), Snap to Unit for tab stops (#3039), DXF circles and arcs as native entities (#2962), Targa files (#2765), a Georgian interface (#2045), Traditional Chinese status and error messages (#2784), the web page's `window.vectorcraft` control channel (#2943), `select.color` (#2939), reproducible export bytes with `SOURCE_DATE_EPOCH` (#2947), Spacing Guides on resizes (#2966) and measurement labels on more tools. Fixed: number fields step to the next whole unit (#2916), a click away from edited type makes no new text (#2922), inch rulers in halves (#2951), Recent cards in New Document (#2904), Japanese W-weights in SVG (#2896), the point-type baseline marker (#2897) and the Reshape tool's falloff (#2900). Headline numbers unchanged. | | 2026-10-17 | Background Export shows a progress dialog: the file being exported, the artboard count and a bar, Cancel (Esc) and Continue in Background. It runs on the shared cancel token of #2546, so a cancelled export writes no file and keeps no half-drawn pattern tile or effect raster; translated in every language with complete menus (#2564). Headline numbers unchanged. | | 2026-10-17 | About 145 community PRs landed in six batches, each through the full gate, plus our fixes on top. Crashes and hostile input: an image's RGBA size is checked from its header before decoding, without overflowing, in the renderer, sampling, recoloring and Crop Image (#2442, #2468, #2407), PDF Add Around and huge art are clamped (#2440), graph axis labels past i64, `+` in hex colours and XML ids are handled (#2610, #2470, #2447), Document Raster Effects resolutions open in range (#2579), Batch names stay in their folder (#2504). Regressions: floating panel groups are opaque again while the docked card keeps its rounded corners (#2499), the Wayland pointer returns over panels (#2502). New: MCP cancels long exports, answers while one runs and reports progress (#2546), `doc_inspect` takes ids, kind and paging (#2543), raster export of a page rectangle (#2511), `text.create` returns bounds (#2478), PDF presets and ICC profiles persist (#2547), screen-reader names for widgets (#2611), Expand on Intertwine (#2622, fixes #2540), Duplicate/Copy/Cut of several artboards (#2567), print presets by name (#2607), TSV data sets (#2608), planar TIFF (#2598), Alt-click a swatch onto a gradient stop (#2623), Shift-click ranges in Links, Graphic Styles and Libraries (#2612, #2613, #2618), Space+Shift rotates the view (#2601), Presentation Mode keys (#2583), Small Caps and super/subscript buttons (#2508). Fidelity: editable vector art from Illustrator EPS (#2571), `.ai` Drop Shadow Darkness (#2513), overprint preview with Darken (#2514), Generic CMYK black round-trips (#2503), PNG sRGB chunk (#2519), kerning at a caret (#2518), tab widths in justified area type (#2487), Transform copies keep their own gradients (#2486), smooth Zig Zag (#2475), Live Corners round up to their neighbours (#2484), kerning across style runs (#2554), SVG letter spacing on justified lines (#2574), Dimension tool snapping (#2482), gradient chips (#2495), Transform panel flips and percentages (#2400, #2404). Later the same day: PostScript `.ps` and `.epsf` files open (#2461), EPS images with CCITTFax compression draw (#2445), Illustrator 3 EPS without layers (#2436), `.ai` type opacity and blend modes (#2420), envelope meshes and compound holes in `.ai` (#2410, #2444), CMYK image soft masks in PDF export (#2448), Show Transparency Grid saved with the document (#2488), Save Selection in the Layers panel menu (#2483), Character and Paragraph Reset Panel (#2479, #2438), Cmd/Ctrl+Shift double-click releases a guide (#2467), Shift+Enter keeps a field active (#2431), Shift keeps reshaped handles perpendicular (#2425), emptied type keeps its style (#2464), Smart Blur radius (#2443), freeform gradients recolour (#2397), mesh slivers (#2456), Recolor wheel handles in CMYK (#2454), and six Image Trace fixes (#2387, #2584, #2586–#2589). Fifth batch: Optical Margin Alignment (#2563), Window › Blend panel (#2573), graph column designs (#2406), Live Paint Gap Options (#2424), the SVG Interactivity panel (#2437), RTF placed as area type (#2524), the Touch Type tool (#2469), pattern fills expand into clipped tiles (#2616), Save and Export ask before replacing a file an added extension names (#2619), the Artboard tool's Control bar and Contextual Task Bar (#2559, #2556), Alt-click New Artboard for its options (#2496), Shift-click in Brushes (#2562), the Move dialog remembers the last move (#2542), PDF export uses the document's assigned profiles (#2536), Printer Setup opens the selected printer's preferences on Windows (#2577). Sixth batch: Effect › Artistic › Cutout, Neon Glow and Poster Edges (#2453), View › Rulers › Change to Global / Artboard Rulers (#2416), Symbol Options 9-slice guides (#2512), Create Gradient Mesh on an embedded image (#2538), Rotate View cursors and the Mac trackpad rotation gesture (#2594, #2644), choice parameters as dropdowns in the inline effect editor (#2582), Group Selection picks and moves one path of a compound path (part of #2441), Shift-click ranges in the Artboards panel (#2626), Lock Variables (#2631), a layer dropped under the last row goes to the bottom (#2632), and robustness work: huge selections draw bounded overlays (#2635, #2645, part of #2460), values out of range in presets and files are clamped (#2656), whole-number checks for counts (#2638, #2659), exports warn about overset type (#2628), symbol instances measured by their art (#2614), colour-managed Eyedropper in CMYK documents (#2664). Later: Effect › Rasterize (#2409), variable-font axis sliders in the Character panel (#2710), Image Trace Create Strokes on an exact distance transform with Guo–Hall thinning and a skeleton graph (#2703–#2705), Auto Color keeps rare colours (#2702), large images trace with a warning (#2700), a 1e9 pt input bound on Reshape Segment, Convert Anchor Point and the Pencil (#2709), task-bar Connect, Corner and Smooth for selected anchors (#2697), PDF 0 w strokes import as hairlines (#2696), threading text from the out port (#2713, part of #2572), a panel per swatch library with Persistent (#2714, #2603), installed plug-ins kept across restarts (#2695, #2541). Languages: Dutch, Danish and Indonesian complete (#2393), Simplified Chinese status and error messages (#2578), translated file filters and presets (#2590). Headline numbers unchanged (estimated). | | 2026-10-16 | Symbol Options › Export Type (Graphic or Movie Clip, default Movie Clip) with Registration; `symbol.options` / `symbol.list` (G5). diff --git a/apps/vectorcraft/Cargo.toml b/apps/vectorcraft/Cargo.toml index 28ccdacedf..3459689111 100644 --- a/apps/vectorcraft/Cargo.toml +++ b/apps/vectorcraft/Cargo.toml @@ -72,6 +72,9 @@ objc2-core-text = { version = "0.3", default-features = false, features = ["std" pollster = "1" [target.'cfg(target_os = "linux")'.dependencies] +# GNOME/Wayland needs client-side window controls without a bundled title font. +winit = { version = "0.30", default-features = false, features = ["wayland-csd-adwaita-notitle"] } + # Asks the Wayland compositor which GPU it draws with (linux-dmabuf feedback, src/compositor_gpu.rs), # so Automatic draws on that one. Both are already in the build through winit. wayland-client = "0.31" diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 1724287808..a457d98089 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -1090,4 +1090,116 @@ mod tests { assert!(types > 1 && plist.matches("LSHandlerRank").count() == types, "every document type has a rank"); assert_eq!(plist.matches("Owner").count(), 2, "only VectorCraft documents and templates are owned"); } + + /// The MIME types a Linux desktop gives each extension in `OPEN_EXTS` but `UNASSOCIATED_EXTS` + /// (one row per type): shared-mime-info's, or one that `ai.storyteller.vectorcraft.mime.xml` + /// declares. + const LINUX_TYPES: &[(&str, &str)] = &[ + ("vectorcraft", "application/x-vectorcraft"), + ("drawcraft", "application/x-vectorcraft"), + ("svg", "image/svg+xml"), + ("svgz", "image/svg+xml-compressed"), + ("pdf", "application/pdf"), + ("ai", "application/illustrator"), // brand-ok: shared-mime-info's type + ("ait", "application/x-ai-template"), + ("png", "image/png"), + ("jpg", "image/jpeg"), + ("jpeg", "image/jpeg"), + ("gif", "image/gif"), + ("webp", "image/webp"), + ("tif", "image/tiff"), + ("tiff", "image/tiff"), + ("bmp", "image/bmp"), + ("vctemplate", "application/x-vectorcraft-template"), + ("dxf", "image/vnd.dxf"), + ("emf", "image/emf"), + ("wmf", "image/wmf"), + ("eps", "image/x-eps"), + ("af", "application/x-affinity"), + ("afdesign", "application/x-affinity"), + ("afpub", "application/x-affinity"), + ]; + + /// The types in `LINUX_TYPES` that shared-mime-info defines. The MIME package declares every + /// other one. + const LINUX_SHARED_TYPES: &[&str] = &[ + "image/svg+xml", + "image/svg+xml-compressed", + "application/pdf", + "application/illustrator", // brand-ok: shared-mime-info's type + "image/png", + "image/jpeg", + "image/gif", + "image/webp", + "image/tiff", + "image/bmp", + "image/vnd.dxf", + "image/emf", + "image/wmf", + "image/x-eps", + ]; + + /// Extensions in `LINUX_TYPES` whose type the MIME package matches by file content and not by a + /// glob, with the package's `` rule for that type (its lines joined, indentation removed). + const LINUX_BY_CONTENT: &[(&str, &str)] = &[( + "af", + // `MAGIC` at offset 0 and `DOCUMENT_KIND` at offset 8 (crates/affinity/src/container.rs). + r#""#, + )]; + + /// The desktop entry lists a MIME type for every extension in `OPEN_EXTS` but + /// `UNASSOCIATED_EXTS`, and the app's MIME package declares the types shared-mime-info doesn't + /// have. + #[test] + fn the_linux_desktop_entry_opens_every_readable_format() { + let desktop = include_str!("../../../packaging/linux/ai.storyteller.vectorcraft.desktop"); + let mime = include_str!("../../../packaging/linux/ai.storyteller.vectorcraft.mime.xml"); + let listed: Vec<&str> = + desktop.lines().find_map(|l| l.strip_prefix("MimeType=")).unwrap_or_default().split(';').filter(|t| !t.is_empty()).collect(); + // Each type the MIME package declares, with the extensions of its globs and its `` + // rule (empty when it has none) in the form `LINUX_BY_CONTENT` gives. + let declared: Vec<(&str, Vec<&str>, String)> = mime + .split("").next().unwrap_or_default(); + let globs = body.split("")) { + (Some(start), Some(end)) => body[start..end + "".len()].lines().map(str::trim).collect(), + _ => String::new(), + }; + (block.split('"').next().unwrap_or_default(), globs, magic) + }) + .collect(); + let mut associated: Vec<&str> = fileio::OPEN_EXTS.iter().copied().filter(|e| !fileio::UNASSOCIATED_EXTS.contains(e)).collect(); + let mut typed: Vec<&str> = LINUX_TYPES.iter().map(|(e, _)| *e).collect(); + associated.sort_unstable(); + typed.sort_unstable(); + typed.dedup(); + assert_eq!(typed, associated, "a MIME type for each extension the packaging associates with the app"); + for (e, t) in LINUX_TYPES { + assert!(listed.contains(t), "the desktop entry doesn't list {t} (.{e})"); + let package = declared.iter().find(|(name, ..)| name == t); + if LINUX_SHARED_TYPES.contains(t) { + assert!(package.is_none(), "{t} is shared-mime-info's, and the MIME package declares it again"); + continue; + } + let Some((_, globs, magic)) = package else { panic!("the MIME package doesn't declare {t} (.{e})") }; + if let Some((_, rule)) = LINUX_BY_CONTENT.iter().find(|(content, _)| content == e) { + assert!(!globs.contains(e), "{t} matches .{e} files by content only"); + assert_eq!(magic, rule, "{t}'s magic rule for .{e} files"); + } else { + assert!(globs.contains(e), "{t} has no *.{e} glob"); + } + } + for t in &listed { + assert!(LINUX_TYPES.iter().any(|(_, known)| known == t), "the desktop entry lists {t}, which the app doesn't open"); + } + for (t, globs, _) in &declared { + assert!(listed.contains(t), "the desktop entry doesn't list the declared {t}"); + for g in globs { + assert!(LINUX_TYPES.contains(&(*g, *t)), "{t}'s *.{g} isn't a file the app opens as {t}"); + } + } + } } diff --git a/assets/icons/dc-appearance.svg b/assets/icons/dc-appearance.svg index 12054b4e57..41ba9d7355 100644 --- a/assets/icons/dc-appearance.svg +++ b/assets/icons/dc-appearance.svg @@ -1 +1 @@ - + diff --git a/assets/icons/dc-objects-on-path.svg b/assets/icons/dc-objects-on-path.svg new file mode 100644 index 0000000000..6ccf47c322 --- /dev/null +++ b/assets/icons/dc-objects-on-path.svg @@ -0,0 +1 @@ + diff --git a/contributors/people.toml b/contributors/people.toml index c65a339ce4..62fcd8d180 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -127,5 +127,16 @@ sync_github_name = true [people.dennismutuku2005] sync_github_name = true +[people.krinry] +display_name = "krinry" +sync_github_name = true + [people.makesomethingshit] sync_github_name = true + +[people.MiQ71] +real_name = "Mirko Kerezovic" +sync_github_name = false + +[people.KaboomFox] +sync_github_name = true diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 91523163e3..a53d205191 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -287,6 +287,8 @@ pub struct ArtBrush { pub width: f64, pub flip_along: bool, pub flip_across: bool, + /// When true, art is placed on each run between sharp corners so folds do not overlap. + pub overlap: bool, pub colorization: Colorization, } @@ -304,6 +306,7 @@ impl Default for ArtBrush { width: 100.0, flip_along: false, flip_across: false, + overlap: false, colorization: Colorization::Tints, } } diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 94e9e6014e..3dcdbf9bcd 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -152,6 +152,28 @@ fn art_brush_between_guides_keeps_ends() { assert!(near(h.x0, 280.0, 1e-6) && near(h.x1, 300.0, 1e-6), "{h:?}"); } +#[test] +fn art_brush_overlap_splits_at_corners() { + let mut bp = BezPath::new(); + bp.move_to((0.0, 0.0)); + bp.line_to((100.0, 0.0)); + bp.line_to((100.0, 100.0)); + let brush = |overlap: bool| Brush { + name: "a".into(), + kind: BrushKind::Art(ArtBrush { + art: rect_art(10.0, 4.0), + scale: ArtScale::Stretch, + overlap, + colorization: Colorization::None, + ..Default::default() + }), + }; + let one = stroke_pieces(&Document::new(1.0, 1.0), &brush(false), &bp, &stroke(1.0)); + let two = stroke_pieces(&Document::new(1.0, 1.0), &brush(true), &bp, &stroke(1.0)); + assert_eq!(one.len(), 1, "one bent copy along the whole path"); + assert_eq!(two.len(), 2, "one copy per run between corners"); +} + #[test] fn art_brush_follows_curves() { let bp = shapes::ellipse(Rect::new(0.0, 0.0, 200.0, 200.0)).to_bezpath(); diff --git a/crates/brush/src/warp.rs b/crates/brush/src/warp.rs index 8eef08c04a..35031741e1 100644 --- a/crates/brush/src/warp.rs +++ b/crates/brush/src/warp.rs @@ -154,35 +154,65 @@ fn bend(t: &Track, art: &Node, b: Rect, along: AlongMap, cross: f64) -> Option Vec<(f64, f64)> { + let l = t.len(); + let corners = t.corner_positions(); + if corners.is_empty() { + return vec![(0.0, l)]; + } + if t.closed { + let first = corners[0].1; + let mut bounds = corners.iter().map(|c| c.1).collect::>(); + bounds.push(first + l); + return bounds.windows(2).map(|w| (w[0], w[1])).collect(); + } + let mut bounds = vec![0.0]; + bounds.extend(corners.iter().map(|c| c.1)); + bounds.push(l); + bounds.windows(2).map(|w| (w[0], w[1])).collect() +} + +fn art_on_run(a: &ArtBrush, t: &Track, s0: f64, s1: f64, art: &Node, b: Rect, cross: f64) -> Option { + let l = s1 - s0; + if l <= 1e-9 { + return None; + } + let w = b.width(); + let (along, cross) = match a.scale { + ArtScale::Stretch => (AlongMap::linear(w, s0, s1), cross), + ArtScale::Proportional => { + let k = l / w; + (AlongMap::linear(w, s0, s1), k * a.width / 100.0) + } + ArtScale::BetweenGuides { start, end } => { + let (g0, g1) = (start.clamp(0.0, 1.0) * w, end.clamp(0.0, 1.0) * w); + let (g0, g1) = (g0.min(g1), g0.max(g1)); + let fixed = (g0 + (w - g1)) * cross; + if fixed >= l || g1 - g0 < 1e-9 { + (AlongMap::linear(w, s0, s1), cross) + } else { + (AlongMap { xs: [0.0, g0, g1, w], ss: [s0, s0 + g0 * cross, s1 - (w - g1) * cross, s1] }, cross) + } + } + }; + bend(t, art, b, along, cross) +} + pub(crate) fn art(a: &ArtBrush, bp: &BezPath, weight: f64) -> Vec { let Some((art, b)) = oriented(&a.art, a.direction, a.flip_along, a.flip_across) else { return vec![] }; let cross = weight * a.width / 100.0; let mut out = vec![]; for t in tracks(bp, 0.05) { - let l = t.len(); - if l <= 1e-9 { + if t.len() <= 1e-9 { continue; } - let w = b.width(); - let (along, cross) = match a.scale { - ArtScale::Stretch => (AlongMap::linear(w, 0.0, l), cross), - ArtScale::Proportional => { - let k = l / w; - (AlongMap::linear(w, 0.0, l), k * a.width / 100.0) + let runs = if a.overlap { art_runs(&t) } else { vec![(0.0, t.len())] }; + for (s0, s1) in runs { + if let Some(n) = art_on_run(a, &t, s0, s1, &art, b, cross) { + out.push(n); } - ArtScale::BetweenGuides { start, end } => { - let (g0, g1) = (start.clamp(0.0, 1.0) * w, end.clamp(0.0, 1.0) * w); - let (g0, g1) = (g0.min(g1), g0.max(g1)); - let fixed = (g0 + (w - g1)) * cross; - if fixed >= l || g1 - g0 < 1e-9 { - (AlongMap::linear(w, 0.0, l), cross) - } else { - (AlongMap { xs: [0.0, g0, g1, w], ss: [0.0, g0 * cross, l - (w - g1) * cross, l] }, cross) - } - } - }; - if let Some(n) = bend(&t, &art, b, along, cross) { - out.push(n); } } out diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index 451173e86e..84e4a3aee3 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -56,6 +56,84 @@ struct Sub { closed: bool, } +/// A subpath close enough to a circle to preserve as a native DXF CIRCLE/ARC. VectorCraft's +/// ellipse helper uses the standard four-cubic circle approximation, so recognition needs a small +/// relative tolerance rather than exact control-point tests. +struct CircularSub { + centre: Point, + radius: f64, + samples: Vec, +} + +fn cubic_point(p0: Point, p1: Point, p2: Point, p3: Point, t: f64) -> Point { + let u = 1.0 - t; + let a = u * u * u; + let b = 3.0 * u * u * t; + let c = 3.0 * u * t * t; + let d = t * t * t; + Point::new(a * p0.x + b * p1.x + c * p2.x + d * p3.x, a * p0.y + b * p1.y + c * p2.y + d * p3.y) +} + +/// Conservatively fit a curved subpath to one circle. Straight segments are never promoted. The +/// 5e-4 radial tolerance is just above the maximum radial error of the usual kappa cubic circle +/// approximation (~2.7e-4 r), while rejecting visibly elliptical or arbitrary cubic curves. +fn circular_subpath(sub: &Sub) -> Option { + if sub.segs.is_empty() || sub.segs.iter().any(|s| matches!(s, Seg::Line(_))) { + return None; + } + let mut samples = vec![sub.start]; + let mut from = sub.start; + for seg in &sub.segs { + let Seg::Cubic(a, b, to) = *seg else { return None }; + for i in 1..=8 { + samples.push(cubic_point(from, a, b, to, f64::from(i) / 8.0)); + } + from = to; + } + if samples.len() < 4 { + return None; + } + let mut anchors = vec![sub.start]; + anchors.extend(sub.segs.iter().map(|s| s.end())); + if sub.closed && anchors.last().is_some_and(|p| p.distance(sub.start) <= 1e-9) { + anchors.pop(); + } + let (p0, p1, p2) = if anchors.len() >= 3 { + (anchors[0], anchors[anchors.len() / 3], anchors[anchors.len() * 2 / 3]) + } else { + (samples[0], samples[samples.len() / 2], *samples.last()?) + }; + let d = 2.0 * (p0.x * (p1.y - p2.y) + p1.x * (p2.y - p0.y) + p2.x * (p0.y - p1.y)); + let scale2 = p0.distance(p1).max(p1.distance(p2)).max(p2.distance(p0)).powi(2); + if !d.is_finite() || d.abs() <= scale2 * 1e-9 { + return None; + } + let q0 = p0.x * p0.x + p0.y * p0.y; + let q1 = p1.x * p1.x + p1.y * p1.y; + let q2 = p2.x * p2.x + p2.y * p2.y; + let centre = Point::new( + (q0 * (p1.y - p2.y) + q1 * (p2.y - p0.y) + q2 * (p0.y - p1.y)) / d, + (q0 * (p2.x - p1.x) + q1 * (p0.x - p2.x) + q2 * (p1.x - p0.x)) / d, + ); + let radius = centre.distance(p0); + if !centre.x.is_finite() || !centre.y.is_finite() || !radius.is_finite() || radius <= 1e-9 { + return None; + } + let tolerance = (radius * 5e-4).max(1e-6); + if samples.iter().any(|p| (centre.distance(*p) - radius).abs() > tolerance) { + return None; + } + Some(CircularSub { centre, radius, samples }) +} + +fn angle_deg(p: Point, centre: Point) -> f64 { + (p.y - centre.y).atan2(p.x - centre.x).to_degrees().rem_euclid(360.0) +} + +fn on_ccw_arc(start: f64, end: f64, angle: f64) -> bool { + (angle - start).rem_euclid(360.0) <= (end - start).rem_euclid(360.0) + 1e-7 +} + /// The subpaths of `bp` (quadratics raised to cubics). fn subpaths(bp: &BezPath) -> Vec { let mut out = vec![]; @@ -576,6 +654,10 @@ impl<'a> Scene<'a> { pts.pop(); } self.polyline(&pts, sub.closed, style, width); + } else if (v.handles() || width.is_none()) && self.circular(&sub, style) { + // Native circles/arcs are preferred by CAD/CAM software. In R12, however, a + // stroked curve must stay on the flattened POLYLINE path so groups 40/41 retain + // its width. Non-circular curves continue through the existing fallback. } else if v.handles() { self.spline(&sub, style); } else { @@ -636,6 +718,73 @@ impl<'a> Scene<'a> { self.e.entity("SEQEND", end, h, &layer, style, ""); } + /// Write a safely recognized circular subpath as a native DXF CIRCLE or ARC. Returns false + /// when the curve is not circular enough, leaving the caller to write it as a spline/polyline. + fn circular(&mut self, sub: &Sub, style: &EntityStyle) -> bool { + let Some(last) = sub.segs.last().map(|s| s.end()) else { return false }; + let geometrically_closed = last.distance(sub.start) <= 1e-9; + // ClosePath can add an implicit straight closing edge. Do not replace that geometry with + // a full CIRCLE; likewise, an open curve that returns to its start is not an ARC. Check + // before fitting, updating extents or allocating an entity handle. + if sub.closed != geometrically_closed { + return false; + } + let Some(circle) = circular_subpath(sub) else { return false }; + let centre = self.to_dxf * circle.centre; + let radius = circle.radius * self.k.abs(); + if !centre.x.is_finite() || !centre.y.is_finite() || !radius.is_finite() || radius <= 1e-12 { + return false; + } + + // Count sampled points in the drawing extents. For a full circle include all cardinal + // points exactly; for an arc, the dense samples conservatively cover its visible span. + if sub.closed { + let r = circle.radius; + for p in [ + Point::new(circle.centre.x - r, circle.centre.y), + Point::new(circle.centre.x + r, circle.centre.y), + Point::new(circle.centre.x, circle.centre.y - r), + Point::new(circle.centre.x, circle.centre.y + r), + ] { + self.pt(p); + } + } else { + for p in &circle.samples { + self.pt(*p); + } + } + + let layer = self.layer.clone(); + let h = self.handle(); + if sub.closed { + self.e.entity("CIRCLE", h, fixed::MODEL_RECORD, &layer, style, "AcDbCircle"); + self.e.xyz(10, centre.x, centre.y); + self.e.num(40, radius); + self.e.normal(); + return true; + } + + let start = self.to_dxf * sub.start; + let end = self.to_dxf * last; + let middle = self.to_dxf * circle.samples[circle.samples.len() / 2]; + let mut a0 = angle_deg(start, centre); + let mut a1 = angle_deg(end, centre); + let am = angle_deg(middle, centre); + if !on_ccw_arc(a0, a1, am) { + std::mem::swap(&mut a0, &mut a1); + } + self.e.entity("ARC", h, fixed::MODEL_RECORD, &layer, style, "AcDbCircle"); + self.e.xyz(10, centre.x, centre.y); + self.e.num(40, radius); + self.e.normal(); + if self.o.version.handles() { + self.e.raw(100, "AcDbArc"); + } + self.e.num(50, a0); + self.e.num(51, a1); + true + } + /// A curved subpath as one cubic B-spline whose clamped knots repeat at every joint, so it /// passes through every anchor (straight segments become straight cubics). fn spline(&mut self, sub: &Sub, style: &EntityStyle) { diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index 37bebbd069..3701d11a9d 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -143,8 +143,8 @@ fn lines_are_lwpolylines_curves_splines_and_fills_hatches() { let out = export(&d, &opts(&d)).unwrap(); assert_eq!( kinds(&out), - ["LWPOLYLINE", "HATCH", "LWPOLYLINE", "SPLINE"], - "the fill's outline and hatch, then the stroke, then the ellipse's stroke" + ["LWPOLYLINE", "HATCH", "LWPOLYLINE", "CIRCLE"], + "the fill's outline and hatch, then the stroke, then the circle's stroke" ); let e = entities(&out); // The rectangle, y up from the artboard's bottom-left corner: 10..110 × 40..90. @@ -164,11 +164,9 @@ fn lines_are_lwpolylines_curves_splines_and_fills_hatches() { assert_eq!((get(&e[0], 370), get(&e[2], 370)), (None, Some("35"))); let hatch = &e[1]; assert_eq!((get(hatch, 2), get(hatch, 70), get(hatch, 91), get(hatch, 93)), (Some("SOLID"), Some("1"), Some("1"), Some("4"))); - // The ellipse: four cubics through clamped knots. - let spline = &e[3]; - assert_eq!((get(spline, 71), get(spline, 73)), (Some("3"), Some("13"))); - assert_eq!(get(spline, 70), Some("9"), "closed planar spline (#1299): 1 = closed, 8 = planar"); - assert_eq!(all(spline, 40), [0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0]); + // The circular ellipse is preserved as a native circle (#1299). + let circle = &e[3]; + assert_eq!((all(circle, 10), all(circle, 20), all(circle, 40)), (vec![150.0], vec![50.0], vec![30.0])); // R14 has lightweight polylines but no lineweights: the stroke is a polyline width. let r14 = export(&d, &DxfOptions { version: DxfVersion::R14, ..opts(&d) }).unwrap(); assert_eq!(get(&entities(&r14)[2], 43), Some("1")); @@ -177,16 +175,77 @@ fn lines_are_lwpolylines_curves_splines_and_fills_hatches() { // R13 has splines and hatches, and polylines of vertices. let r13 = export(&d, &DxfOptions { version: DxfVersion::R13, ..opts(&d) }).unwrap(); let poly = ["POLYLINE", "VERTEX", "VERTEX", "VERTEX", "VERTEX", "SEQEND"]; - assert_eq!(kinds(&r13), [&poly[..], &["HATCH"], &poly, &["SPLINE"]].concat()); - // R12: polylines only; the fill is its outline, the ellipse flattened. + assert_eq!(kinds(&r13), [&poly[..], &["HATCH"], &poly, &["CIRCLE"]].concat()); + // R12: visible stroke widths live on old POLYLINE entities, including curved strokes. let r12 = export(&d, &DxfOptions { version: DxfVersion::R12, ..opts(&d) }).unwrap(); let k = kinds(&r12); assert!(k.iter().all(|k| matches!(k.as_str(), "POLYLINE" | "VERTEX" | "SEQEND")), "{k:?}"); assert_eq!(k.iter().filter(|k| *k == "POLYLINE").count(), 3); - assert!(k.iter().filter(|k| *k == "VERTEX").count() > 20, "the ellipse is flattened"); + assert_eq!(k.iter().filter(|k| *k == "CIRCLE").count(), 0); assert!(r12.warnings.iter().any(|w| w.contains("R12 has no fills")), "{:?}", r12.warnings); } +#[test] +fn circles_and_circular_arcs_are_native_dxf_entities() { + let d = doc_with(|d| { + let circle = shapes::ellipse(Rect::new(20.0, 20.0, 80.0, 80.0)); + let c = Point::new(120.0, 50.0); + let r = 30.0; + let k = r * shapes::KAPPA; + let mut arc = vectorcraft_geom::BezPath::new(); + arc.move_to(Point::new(c.x + r, c.y)); + arc.curve_to(Point::new(c.x + r, c.y - k), Point::new(c.x + k, c.y - r), Point::new(c.x, c.y - r)); + vec![ + path(d, circle, Paint::None, Paint::solid(Color::BLACK), 1.0), + path(d, PathData::from_bezpath(&arc), Paint::None, Paint::solid(Color::BLACK), 1.0), + ] + }); + for version in DxfVersion::ALL.into_iter().filter(|version| *version != DxfVersion::R12) { + let out = export(&d, &DxfOptions { version, ..opts(&d) }).unwrap(); + let e = entities(&out); + assert_eq!(e.iter().map(|x| kind(x)).collect::>(), ["CIRCLE", "ARC"], "{version:?}"); + assert_eq!((all(&e[0], 10), all(&e[0], 20), all(&e[0], 40)), (vec![50.0], vec![50.0], vec![30.0]), "{version:?}"); + assert_eq!((all(&e[1], 10), all(&e[1], 20), all(&e[1], 40)), (vec![120.0], vec![50.0], vec![30.0]), "{version:?}"); + assert_eq!((all(&e[1], 50), all(&e[1], 51)), (vec![0.0], vec![90.0]), "{version:?}"); + } + + // An actual ellipse is not close enough to a circle and remains a spline. + let ellipse = doc_with(|d| vec![path(d, shapes::ellipse(Rect::new(20.0, 20.0, 100.0, 60.0)), Paint::None, Paint::solid(Color::BLACK), 1.0)]); + assert_eq!(kinds(&export(&ellipse, &opts(&ellipse)).unwrap()), ["SPLINE"]); +} + +#[test] +fn r12_stroked_circles_keep_polyline_width() { + let d = doc_with(|d| vec![path(d, shapes::ellipse(Rect::new(20.0, 20.0, 80.0, 80.0)), Paint::None, Paint::solid(Color::BLACK), 3.0)]); + let out = export(&d, &DxfOptions { version: DxfVersion::R12, ..opts(&d) }).unwrap(); + let e = entities(&out); + assert_eq!(kind(&e[0]), "POLYLINE"); + assert_eq!((get(&e[0], 40), get(&e[0], 41)), (Some("3"), Some("3"))); + assert!(!e.iter().any(|entity| kind(entity) == "CIRCLE")); +} + +#[test] +fn closed_circular_arc_with_a_closing_chord_is_not_a_circle() { + let d = doc_with(|d| { + let c = Point::new(50.0, 50.0); + let r = 30.0; + let k = r * shapes::KAPPA; + let mut arc = vectorcraft_geom::BezPath::new(); + arc.move_to(Point::new(c.x + r, c.y)); + arc.curve_to(Point::new(c.x + r, c.y - k), Point::new(c.x + k, c.y - r), Point::new(c.x, c.y - r)); + arc.curve_to(Point::new(c.x - k, c.y - r), Point::new(c.x - r, c.y - k), Point::new(c.x - r, c.y)); + arc.curve_to(Point::new(c.x - r, c.y + k), Point::new(c.x - k, c.y + r), Point::new(c.x, c.y + r)); + arc.close_path(); + vec![path(d, PathData::from_bezpath(&arc), Paint::None, Paint::solid(Color::BLACK), 1.0)] + }); + + let modern = export(&d, &opts(&d)).unwrap(); + assert_eq!(kinds(&modern), ["SPLINE"]); + let r12 = export(&d, &DxfOptions { version: DxfVersion::R12, ..opts(&d) }).unwrap(); + assert!(kinds(&r12).iter().any(|k| k == "POLYLINE")); + assert!(!kinds(&r12).iter().any(|k| k == "CIRCLE")); +} + #[test] fn spline_closed_flags_follow_path_intent_across_versions_without_changing_geometry() { let cases = [(true, true), (true, false), (false, false), (false, true)]; @@ -353,7 +412,7 @@ fn alter_paths_writes_strokes_as_filled_outlines() { // Each fill and stroke: its outlines, then its hatch. let fill = ["LWPOLYLINE", "HATCH"]; let rect_stroke = ["LWPOLYLINE", "LWPOLYLINE", "HATCH"]; - assert_eq!(kinds(&out), [&fill[..], &rect_stroke, &["SPLINE", "SPLINE", "HATCH"]].concat()); + assert_eq!(kinds(&out), [&fill[..], &rect_stroke, &["CIRCLE", "CIRCLE", "HATCH"]].concat()); // The rectangle's stroke: an outer and an inner boundary. assert_eq!(get(&entities(&out)[4], 91), Some("2")); // Preserve Appearance outlines only the strokes a line can't draw. @@ -362,9 +421,9 @@ fn alter_paths_writes_strokes_as_filled_outlines() { if let Some(st) = d.node_mut(rect).and_then(|n| n.appearance.stroke_mut()) { st.align = vectorcraft_doc::StrokeAlign::Outside; } - assert_eq!(kinds(&export(&d, &opts(&d)).unwrap()), [&fill[..], &rect_stroke, &["SPLINE"]].concat()); + assert_eq!(kinds(&export(&d, &opts(&d)).unwrap()), [&fill[..], &rect_stroke, &["CIRCLE"]].concat()); let editable = export(&d, &DxfOptions { preserve: Preserve::Editability, ..opts(&d) }).unwrap(); - assert_eq!(kinds(&editable), ["LWPOLYLINE", "HATCH", "LWPOLYLINE", "SPLINE"]); + assert_eq!(kinds(&editable), ["LWPOLYLINE", "HATCH", "LWPOLYLINE", "CIRCLE"]); assert!(editable.warnings.iter().any(|w| w.contains("stroke alignment"))); } @@ -451,7 +510,7 @@ fn crop_leaves_out_art_outside_the_region() { let d = shapes_doc(); // Only the ellipse (120..180) reaches into 115..200. let o = DxfOptions { region: Rect::new(115.0, 0.0, 200.0, 100.0), crop: true, ..opts(&d) }; - assert_eq!(kinds(&export(&d, &o).unwrap()), ["SPLINE"]); + assert_eq!(kinds(&export(&d, &o).unwrap()), ["CIRCLE"]); assert_eq!(kinds(&export(&d, &DxfOptions { crop: false, ..o }).unwrap()).len(), 4); } diff --git a/crates/doc/src/appearance.rs b/crates/doc/src/appearance.rs index 5b1dd7364d..b336ff1529 100644 --- a/crates/doc/src/appearance.rs +++ b/crates/doc/src/appearance.rs @@ -739,9 +739,10 @@ pub struct Appearance { pub items: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub effects: Vec, - /// Groups, layers and type: how many items paint below the object's contents (its members, or - /// type's characters), the slot of the Appearance panel's Contents (Characters) row. `None`: - /// every item paints above the contents (see [`Self::contents_at`]). + /// Groups, layers, type and images: how many items paint below the object's contents (its + /// members, type's characters, or an image's pixels), the slot of the Appearance panel's + /// Contents (Characters) row. `None`: every item paints above the contents (see + /// [`Self::contents_at`]). #[serde(default, skip_serializing_if = "Option::is_none")] pub contents_index: Option, } diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 8e16f1ed05..81d1d12f63 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -1,11 +1,12 @@ //! Hit testing over the document tree. use std::collections::HashSet; +use std::sync::OnceLock; use vectorcraft_geom::hit::{fill_contains, stroke_contains}; -use vectorcraft_geom::{Point, Rect}; +use vectorcraft_geom::{BezPath, FillRule, Point, Rect}; -use crate::{Document, Node, NodeId, NodeKind, SymbolBoxes}; +use crate::{AppearanceItem, Document, Node, NodeId, NodeKind, SymbolBoxes}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum HitKind { @@ -62,14 +63,37 @@ pub struct HitOptions { /// (point type's baseline, area type's frame, type on a path's path), not anywhere in its /// bounds. pub type_path_only: bool, + /// Guide objects (paths made into guides) are not hittable: View › Guides › Lock Guides is + /// on or the guides are hidden. + pub skip_guides: bool, } impl Default for HitOptions { fn default() -> Self { - Self { tol: 3.0, outline: false, path_only: false, type_path_only: false, scope: None } + Self { tol: 3.0, outline: false, path_only: false, type_path_only: false, skip_guides: false, scope: None } } } +/// The shapes that an image's own fills and strokes paint, each with its fill rule and the fill or +/// stroke that paints it (none for fills and strokes that paint nothing). Effects are evaluated +/// above this crate, so the engine registers one with [`set_image_paint`]. +pub type ImagePaint = fn(&Node) -> Vec<(BezPath, FillRule, AppearanceItem)>; + +static IMAGE_PAINT: OnceLock = OnceLock::new(); + +/// Register how the shapes of an image's own fills and strokes are found (the first registration +/// stays). +pub fn set_image_paint(f: ImagePaint) { + // Already set: the same engine, registered by another session. + let _ = IMAGE_PAINT.set(f); +} + +/// The shapes that the image `n`'s own fills and strokes paint ([`set_image_paint`]), none while +/// nothing is registered. +pub(crate) fn image_paint(n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { + IMAGE_PAINT.get().map_or_else(Vec::new, |f| f(n)) +} + /// Topmost editable object under `p`. pub fn hit_test(doc: &Document, p: Point, opt: HitOptions) -> Option { hit_test_skipping(doc, p, opt, &|_| false, true) @@ -318,6 +342,9 @@ fn may_hit(parent: &Node, i: usize, c: &Node, p: Point, opt: HitOptions, symbols if !c.visible || editable_only && (c.locked || c.is_template()) { return false; } + if opt.skip_guides && matches!(c.kind, NodeKind::Path { guide: true, .. }) { + return false; + } // (An envelope's content sits where it was, not where the envelope draws it.) edits_contents(c) || c.extras().shaper.is_some() && source_of(c, opt.scope) @@ -433,12 +460,23 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio n.geometric_bounds().filter(|b| b.inflate(opt.tol, opt.tol).contains(p))?; on_type_path(n, t, p, opt.tol).then_some(HitKind::Outline) } - NodeKind::Text(_) - | NodeKind::Image(_) - | NodeKind::PlacedDocument(_) - | NodeKind::SymbolInstance { .. } - | NodeKind::Blend { .. } - | NodeKind::Envelope { .. } => n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds), + // An image is hit within its frame, and where its own fills and strokes paint + // ([`image_paint`]) except in outline mode. + NodeKind::Image(_) => { + if n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) { + return Some(HitKind::Bounds); + } + if opt.outline { + return None; + } + image_paint(n).iter().rev().find_map(|(bp, rule, item)| match item { + AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke), + AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill), + }) + } + NodeKind::Text(_) | NodeKind::PlacedDocument(_) | NodeKind::SymbolInstance { .. } | NodeKind::Blend { .. } | NodeKind::Envelope { .. } => { + n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds) + } NodeKind::Repeat(r) => r.expand().iter().find_map(|g| hit_any(g, p, opt, symbols)), NodeKind::Mesh(m) => { let bp = m.outline().to_bezpath(); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 4e72a6cae7..12ecf8570a 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -36,6 +36,7 @@ pub mod marks; mod mem; pub mod metadata; pub mod node; +pub mod objects_on_path; pub mod orient; pub mod overprint; pub mod pattern; @@ -215,13 +216,33 @@ impl Unit { /// The rulers' label step at `zoom` (screen pixels per point), in this unit: the first of /// 1, 2, 5 × 10ⁿ that puts labels at least 50 pixels apart. Ticks mark every tenth of it. pub fn ruler_step(self, zoom: f64) -> f64 { - const STEPS: [f64; 19] = + const DECIMAL: [f64; 19] = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 25.0, 50.0, 100.0, 200.0, 500.0, 1000.0, 2000.0, 5000.0, 10000.0]; - STEPS.iter().copied().find(|s| s * self.points() * zoom >= 50.0).unwrap_or(10000.0) + // An inch is divided in half, not in ten: a tenth of an inch is not a mark an inch ruler + // carries, so below an inch the steps are binary fractions (#2827). Labelling stops at a + // sixteenth; zooming in past that leaves the labels where they are and only the ticks + // between them grow denser, down to a hundred and twenty-eighth + // ([`Self::ruler_minor`]). A label is at most six characters that way ("0.0625"), which + // the left ruler has room for when it spells one down the ruler a character at a time. + // From an inch up the ladder is the shared one. + const BINARY: [f64; 15] = [1.0 / 16.0, 0.125, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0, 25.0, 50.0, 100.0, 200.0, 500.0, 1000.0, 10000.0]; + let steps: &[f64] = if self.ruler_halves() { &BINARY } else { &DECIMAL }; + steps.iter().copied().find(|s| s * self.points() * zoom >= 50.0).unwrap_or(10000.0) + } + /// Does this unit's ruler divide a step in half rather than in ten? Inches do; the metric + /// units, points, pixels and picas are read in tenths. + fn ruler_halves(self) -> bool { + matches!(self, Unit::Inches) + } + /// The unlabelled ticks between two labels, `step` apart ([`Self::ruler_step`]): an eighth of + /// the step on an inch ruler, so every tick is a binary fraction of an inch and they stay about + /// as dense as the tenths elsewhere; a tenth of it otherwise. + pub fn ruler_minor(self, step: f64) -> f64 { + if self.ruler_halves() { step / 8.0 } else { step / 10.0 } } /// `v` (points) on the nearest ruler tick at `zoom` ([`Self::ruler_step`]). pub fn snap_to_ruler_tick(self, v: f64, zoom: f64) -> f64 { - let tick = self.ruler_step(zoom) / 10.0 * self.points(); + let tick = self.ruler_minor(self.ruler_step(zoom)) * self.points(); (v / tick).round() * tick } pub fn from_pt(self, v: f64) -> f64 { @@ -1515,6 +1536,7 @@ impl Document { n += usize::from(*k); } sel.guides = sel.guides.iter().filter_map(|i| to.get(*i).copied().flatten()).collect(); + sel.key_guide = sel.key_guide.and_then(|i| to.get(i).copied().flatten()); let before = self.guides.len(); let mut flags = kept.into_iter(); self.guides.retain(|_| flags.next().unwrap_or(true)); @@ -1560,9 +1582,17 @@ impl Document { { dimension.source = None; } + let mut renamed = std::collections::HashMap::new(); if let Some(ch) = n.children_mut() { let old: Vec> = std::mem::take(ch); *ch = old.iter().map(|c| Arc::new(self.reid(c))).collect(); + renamed.extend(old.iter().zip(ch.iter()).map(|(o, c)| (o.id, c.id))); + } + // An Objects on Path group names its path and its objects by id: the copy names the copies. + if let Some(e) = n.extras_if_any() + && let Some(on_path) = &mut e.objects_on_path + { + on_path.rename(&renamed); } n } @@ -1803,6 +1833,46 @@ mod tests { use super::*; use vectorcraft_geom::shapes; + /// Zooming in on an inch ruler divided the inch into tenths (#2827). Its steps below an inch + /// are binary fractions now, and the minor ticks between them stay binary too; every other + /// unit is still read in tenths. + #[test] + fn an_inch_ruler_steps_in_binary_fractions() { + let step = |u: Unit, zoom: f64| u.ruler_step(zoom); + // Every inch step at or below an inch is 1/2^k, never a tenth or a fifth. + for zoom in [1.0, 2.0, 5.0, 7.5, 10.0, 20.0, 40.0, 100.0, 400.0] { + let s = step(Unit::Inches, zoom); + if s <= 1.0 { + let k = s.recip(); + assert_eq!(k, k.round(), "{s} at zoom {zoom} is 1/k for a whole k"); + assert!((k.round() as u64).is_power_of_two(), "{s} at zoom {zoom} is 1/2^k"); + } + // A label step always leaves at least 50 px, which is what the ladder is picked for. + assert!(s * Unit::Inches.points() * zoom >= 50.0, "zoom {zoom}"); + } + // The steps the report named: tenths became quarters, eighths and sixteenths. + assert_eq!(step(Unit::Inches, 5.0), 0.25); + assert_eq!(step(Unit::Inches, 10.0), 0.125); + assert_eq!(step(Unit::Inches, 20.0), 0.0625); + // An inch and wider is unchanged. + assert_eq!(step(Unit::Inches, 1.0), 1.0); + // Labelling stops at a sixteenth, as the report says Illustrator's does, so zooming in + // further only adds ticks. A label therefore never needs more than the six characters of + // "0.0625", which the left ruler has room for when it spells one out a character per line. + for zoom in [20.0, 50.0, 100.0, 400.0, 1600.0] { + assert_eq!(step(Unit::Inches, zoom), 0.0625, "zoom {zoom}"); + } + // The unlabelled ticks go on down to a hundred and twenty-eighth: the 32nds, 64ths and + // 128ths the report expects to appear unlabelled when zoomed in close. + assert_eq!(Unit::Inches.ruler_minor(0.0625), 1.0 / 128.0); + // The minor ticks: an eighth of the step on an inch ruler, a tenth elsewhere. + assert_eq!(Unit::Inches.ruler_minor(0.25), 0.03125); + assert_eq!(Unit::Millimeters.ruler_minor(25.0), 2.5); + assert_eq!(Unit::Points.ruler_minor(100.0), 10.0); + // Other units keep the decimal ladder, so a tenth and a fifth still appear. + assert!([0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 25.0].contains(&step(Unit::Millimeters, 5.0)), "{}", step(Unit::Millimeters, 5.0)); + } + fn doc_with_rects() -> (Document, NodeId, NodeId) { let mut d = Document::new(612.0, 792.0); let layer = d.layers[0].id; diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index fd78867868..9175c88c57 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -587,12 +587,18 @@ fn even_steps(n: u32) -> Vec { (0..=n).map(|i| i as f64 / n as f64).collect() } +/// The number of points of a `(rows+1)×(cols+1)` grid, `None` past `usize`: counts come from +/// files, and u32::MAX rows and columns (65,535 on 32-bit targets) would wrap to an empty grid. +fn grid_len(rows: u32, cols: u32) -> Option { + (rows as usize).checked_add(1)?.checked_mul((cols as usize).checked_add(1)?) +} + impl GradientMesh { pub fn idx(&self, r: usize, c: usize) -> usize { r * (self.cols as usize + 1) + c } pub fn is_valid(&self) -> bool { - self.rows >= 1 && self.cols >= 1 && self.points.len() == (self.rows as usize + 1) * (self.cols as usize + 1) + self.rows >= 1 && self.cols >= 1 && grid_len(self.rows, self.cols) == Some(self.points.len()) } /// A 1×1 mesh from its four corners (bottom-left, top-left, top-right, bottom-right in u/v @@ -1026,7 +1032,8 @@ impl GradientMesh { /// Mesh tool Alt-click: delete the mesh lines through point `index` (interior lines only). pub fn remove_point_lines(&mut self, index: usize) -> bool { - if index >= self.points.len() { + // A mesh from a file may not have the points its rows and columns need: it is indexed below. + if !self.is_valid() || index >= self.points.len() { return false; } let w = self.cols as usize + 1; @@ -1158,7 +1165,7 @@ fn surface_of<'a>(kind: &'a EnvelopeKind, src: Rect, frame: Affine) -> Box Vec<[Vec2; 4]> /// the smooth ones, see [`smooth_handles`]) as a gradient mesh with black points: what the /// canvas draws and the Mesh tool and Direct Selection edit. `None` for a malformed grid. pub fn envelope_grid(rows: u32, cols: u32, points: &[Point], handles: &[[Vec2; 4]]) -> Option { - // (Counts come from files: no overflow on 32-bit targets.) - if rows == 0 || cols == 0 || points.len() as u64 != (u64::from(rows) + 1) * (u64::from(cols) + 1) { + if rows == 0 || cols == 0 || grid_len(rows, cols) != Some(points.len()) { return None; } let smooth; @@ -1829,6 +1835,20 @@ mod tests { assert!((p.x - 37.0).abs() < 1e-6 && (p.y - 81.0).abs() < 1e-6, "{p:?}"); } + /// A file's rows and columns can be anything: a point count too large to compute is no match + /// for the points (u32::MAX × u32::MAX wrapped to 0 and passed for a grid without points). + #[test] + fn a_grid_too_large_to_count_is_malformed() { + let m = GradientMesh { rows: u32::MAX, cols: u32::MAX, points: vec![] }; + assert!(!m.is_valid()); + assert_eq!((m.lines(), m.outline(), m.quads(8).len()), (PathData::default(), PathData::default(), 0)); + assert!(envelope_grid(u32::MAX, u32::MAX, &[], &[]).is_none()); + // A mesh envelope without handles maps through its points: malformed, it leaves art as it is. + let kind = EnvelopeKind::Mesh { rows: u32::MAX, cols: u32::MAX, points: vec![], handles: vec![] }; + let p = Point::new(25.0, 50.0); + assert_eq!(envelope_mapper(&kind, Rect::new(0.0, 0.0, 100.0, 100.0))(p), p); + } + #[test] fn mesh_insert_and_remove_lines() { let mut m = @@ -1854,4 +1874,18 @@ mod tests { m.points[1].color = Color::rgb(1.0, 0.0, 0.0); assert!(matches!(m.color_at(0, 0, 0.5, 0.5).0, Color::Rgb { .. })); } + + /// Alt-clicking a point of a mesh from a file with fewer points than its rows and columns need + /// deletes nothing (it indexed past the points, a panic). + #[test] + fn mesh_lines_of_a_malformed_mesh_stay() { + let point = |i: u32| MeshPoint { p: Point::new(f64::from(i), 0.0), color: Color::BLACK, opacity: 1.0, handles: [Vec2::ZERO; 4] }; + // An interior row's point and an interior column's point, each with 3 of the 6 points. + for (rows, cols, index) in [(2, 1, 2), (1, 2, 1)] { + let mut m = GradientMesh { rows, cols, points: (0..3).map(point).collect() }; + let before = m.clone(); + assert!(!m.remove_point_lines(index), "{rows}×{cols}, point {index}"); + assert_eq!(m, before); + } + } } diff --git a/crates/doc/src/mem.rs b/crates/doc/src/mem.rs index 3109fa4cfe..771b0b7fb6 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -253,6 +253,9 @@ fn node_bytes(n: &Node, other: Option<&Node>) -> usize { b += boxed(&e.dimension) + boxed(&e.live_paint_gaps); b += e.trace.as_ref().map_or(0, |t| ALLOC + size_of::() + json_bytes(t)); b += e.intertwine.as_deref().map_or(0, |a| ALLOC + size_of::() + path_bytes(a)); + b += e.objects_on_path.as_deref().map_or(0, |o| { + ALLOC + size_of::() + o.members.capacity() * size_of::() + }); } b += match &n.kind { NodeKind::Path { path, live, .. } => path_bytes(path) + boxed(live), diff --git a/crates/doc/src/metadata.rs b/crates/doc/src/metadata.rs index f723b1ccd6..708cb82e8f 100644 --- a/crates/doc/src/metadata.rs +++ b/crates/doc/src/metadata.rs @@ -90,7 +90,13 @@ impl DocMetadata { /// The raw clock stays in [`now_unix`], which is what a heartbeat is judged by and what seeds /// encryption: neither may be pinned by the environment. pub fn output_time() -> Option { - stamp_from_env(|n| std::env::var(n).ok()).or_else(now_unix) + pinned_or(|n| std::env::var(n).ok(), now_unix) +} + +/// [`output_time`] with the environment and the clock supplied, so a test can show that the +/// variable is preferred and that the clock answers whenever it does not. +fn pinned_or(get: impl Fn(&str) -> Option, clock: impl Fn() -> Option) -> Option { + stamp_from_env(get).or_else(clock) } /// `SOURCE_DATE_EPOCH` as Unix seconds: the reproducible-builds variable @@ -184,4 +190,21 @@ mod tests { assert_eq!(stamp_from_env(|_| Some("1791208980".to_owned())), Some(1_791_208_980)); assert_eq!(stamp_from_env(|n: &str| (n == "TZ").then(|| "1791208980".to_owned())), None); } + + /// What a file records: the variable when it is usable, the clock whenever it is not. The + /// environment and the clock are passed in, so no test changes this process's environment -- + /// that is `unsafe` under edition 2024 and would reach every other test running beside it. + #[test] + fn a_pinned_epoch_is_preferred_and_the_clock_answers_otherwise() { + let env = |v: Option<&'static str>| move |_: &str| v.map(str::to_owned); + let clock = || Some(1_000_000); + assert_eq!(pinned_or(env(Some("1791208980")), clock), Some(1_791_208_980), "the variable wins over the clock"); + assert_eq!(pinned_or(env(Some("0")), clock), Some(0), "including the epoch itself"); + for ignored in [None, Some(""), Some("-1"), Some("later")] { + assert_eq!(pinned_or(env(ignored), clock), Some(1_000_000), "{ignored:?} leaves it to the clock"); + } + // A platform with no clock and no variable has no date to record. + assert_eq!(pinned_or(env(None), || None), None); + assert_eq!(pinned_or(env(Some("1791208980")), || None), Some(1_791_208_980), "the variable needs no clock"); + } } diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index 25acfd0887..1bfabf9c19 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize}; use vectorcraft_color::{BlendMode, Color, Paint}; use vectorcraft_geom::corners::cut_corners; use vectorcraft_geom::shapes::{self, CornerKind}; -use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect}; +use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Shape}; use crate::appearance::Appearance; use crate::live::{BlendSpec, EnvelopeKind, GradientMesh, Outliner}; @@ -102,6 +102,8 @@ pub enum LiveShape { }, Polygon { radius: f64, + /// 3–1000, as [`LiveShape::set_sides`] gives it; a file's count is clamped when read. + #[serde(deserialize_with = "de_sides")] sides: u32, xf: Affine, /// Corner radii in document units, by vertex from the first one clockwise (none: sharp). @@ -326,6 +328,12 @@ fn all_round(kinds: &[CornerKind]) -> bool { kinds.iter().all(|k| *k == CornerKind::Round) } +/// A polygon's side count read from a file, clamped as the commands clamp it: the outline and its +/// corner lists hold one entry per side, so a huge count would allocate gigabytes. +fn de_sides<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + u32::deserialize(d).map(|n| n.clamp(3, 1000)) +} + /// Whether `a` only moves (no rotation, scale, shear or reflection). fn moves_only(a: Affine) -> bool { let [a0, a1, a2, a3, _, _] = a.as_coeffs(); @@ -572,6 +580,9 @@ pub struct NodeExtras { pub intertwine: Option>, /// Live Paint group: its Gap Options (Object › Live Paint › Gap Options; `None`: the defaults). pub live_paint_gaps: Option>, + /// Object › Objects on Path: the group's path and the objects attached to it (see + /// [`crate::objects_on_path`]). + pub objects_on_path: Option>, } /// No extras: what [`Node::extras`] gives for a node without any. @@ -590,6 +601,7 @@ static NO_EXTRAS: NodeExtras = NodeExtras { dimension: None, intertwine: None, live_paint_gaps: None, + objects_on_path: None, }; /// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal @@ -724,6 +736,7 @@ impl Serialize for Node { e.dimension.is_none(), e.intertwine.is_none(), e.live_paint_gaps.is_none(), + e.objects_on_path.is_none(), ]; let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?; let mut skip = skips.into_iter(); @@ -762,6 +775,7 @@ impl Serialize for Node { field!("dimension", &e.dimension); field!("intertwine", &e.intertwine); field!("live_paint_gaps", &e.live_paint_gaps); + field!("objects_on_path", &e.objects_on_path); st.end() } } @@ -821,6 +835,8 @@ struct NodeWire { intertwine: Option>, #[serde(default)] live_paint_gaps: Option>, + #[serde(default)] + objects_on_path: Option>, } impl From for Node { @@ -840,6 +856,7 @@ impl From for Node { dimension: w.dimension, intertwine: w.intertwine, live_paint_gaps: w.live_paint_gaps, + objects_on_path: w.objects_on_path, }; Node { id: w.id, @@ -1025,6 +1042,7 @@ impl Node { match &self.kind { NodeKind::Layer { .. } => "Layer", NodeKind::Group { clip: true, .. } => "Clip Group", + NodeKind::Group { .. } if self.extras().objects_on_path.is_some() => "Objects on Path", NodeKind::Group { .. } => "Group", NodeKind::Path { live: Some(l), .. } => l.label(), NodeKind::Path { guide: true, .. } => "Guide", @@ -1087,8 +1105,10 @@ impl Node { } /// A quick box round everything the object can paint, for culling clicks: paths and compound /// paths grow their geometric bounds by the farthest their strokes can reach from any path - /// ([`Appearance::outset`]) instead of measuring along their shape. Symbol instances are - /// measured as in [`Node::visual_bounds`]. + /// ([`Appearance::outset`]) instead of measuring along their shape. An image's box takes in + /// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers + /// without a clipping mask and Intertwine groups take in their members' boxes, grown by their + /// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. pub fn reach_bounds(&self) -> Option { self.reach(None) } @@ -1106,6 +1126,22 @@ impl Node { let o = self.appearance.outset(); self.geometric(symbols).map(|b| b.inflate(o, o)) } + // The members' reach, grown by the container's own strokes. + NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } => { + let o = self.appearance.outset(); + children + .iter() + .skip(usize::from(self.extras().shaper.is_some())) + .fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.reach(symbols))) + .map(|b| b.inflate(o, o)) + } + NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.reach(symbols))), + // The frame and each shape the image's own fills and strokes paint, a stroke's grown by + // the farthest it can reach from its shape. + NodeKind::Image(_) => crate::hit::image_paint(self).iter().fold(self.geometric(symbols), |acc, (bp, _, item)| { + let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 }; + vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o))) + }), _ => self.visual(symbols), } } @@ -1155,9 +1191,9 @@ impl Node { } } /// Visual bounds: what the object paints, its strokes included (paths and compound paths - /// measure theirs along their own shape, see [`Appearance::stroked_bounds`]). A symbol - /// instance is measured as in [`Node::geometric_bounds`], grown by its own strokes' reach - /// ([`Node::visual_bounds_with`] measures its art). + /// measure theirs along their own shape, see [`Appearance::stroked_bounds`]). An image is + /// measured by its frame. A symbol instance is measured as in [`Node::geometric_bounds`], + /// grown by its own strokes' reach ([`Node::visual_bounds_with`] measures its art). pub fn visual_bounds(&self) -> Option { self.visual(None) } @@ -1232,6 +1268,8 @@ impl Node { let o = self.appearance.outset().max(chars); self.geometric(symbols).map(|b| b.inflate(o, o)) } + // An image is measured by its frame, without its own fills and strokes. + NodeKind::Image(_) => self.geometric(symbols), _ => { let o = self.appearance.outset(); self.geometric(symbols).map(|b| b.inflate(o, o)) @@ -1251,6 +1289,12 @@ impl Node { { dimension.transform(a); } + // The frames of the objects attached to a path move with them. + if let Some(e) = self.extras_if_any() + && let Some(on_path) = &mut e.objects_on_path + { + on_path.transform(a); + } if !self.is_layer() { self.bbox_angle = crate::orient::transformed_angle(self.bbox_angle, a); } @@ -1683,11 +1727,11 @@ impl Node { impl Node { /// The Appearance panel's row for what this object's own fills and strokes paint around: - /// "Contents" for a group or layer (its members), "Characters" for type; `None` for objects - /// whose fills and strokes paint their own geometry. + /// "Contents" for a group or layer (its members) and for an image (its pixels), "Characters" + /// for type; `None` for objects whose fills and strokes paint their own geometry. pub fn contents_label(&self) -> Option<&'static str> { match self.kind { - NodeKind::Group { .. } | NodeKind::Layer { .. } => Some("Contents"), + NodeKind::Group { .. } | NodeKind::Layer { .. } | NodeKind::Image(_) => Some("Contents"), NodeKind::Text(_) => Some("Characters"), _ => None, } @@ -2154,6 +2198,24 @@ mod tests { assert_eq!(path.label(), "Path"); } + /// A polygon read from a file has 3 to 1000 sides, as the commands give it: selecting one + /// with four billion made its outline and corner lists allocate tens of gigabytes. + #[test] + fn a_polygon_from_a_file_has_3_to_1000_sides() { + let read = |sides: u32| { + let json = serde_json::json!({"shape": "polygon", "radius": 10.0, "sides": sides, "xf": [1, 0, 0, 1, 0, 0]}); + serde_json::from_value::(json).unwrap() + }; + let sides_of = |l: &LiveShape| match l { + LiveShape::Polygon { sides, .. } => *sides, + _ => panic!("not a polygon: {l:?}"), + }; + let huge = read(4_000_000_000); + assert_eq!([0, 5, 1000].map(|n| sides_of(&read(n))), [3, 5, 1000]); + assert_eq!(sides_of(&huge), 1000); + assert_eq!(huge.polygon_outline().anchor_count(), 1000); + } + #[test] fn a_polygon_reports_and_takes_its_radius_angle_and_equal_sides() { let close = |a: f64, b: f64| (a - b).abs() < 1e-9; diff --git a/crates/doc/src/objects_on_path.rs b/crates/doc/src/objects_on_path.rs new file mode 100644 index 0000000000..372fae87aa --- /dev/null +++ b/crates/doc/src/objects_on_path.rs @@ -0,0 +1,335 @@ +//! Object › Objects on Path: objects attached to a path and spread along it. +//! +//! An Objects on Path group is an ordinary group ([`NodeKind::Group`]) with an [`ObjectsOnPath`] +//! record in its extras ([`crate::node::NodeExtras::objects_on_path`]). One child is the path, and +//! the other children are the attached objects, kept where they are drawn: the group draws, hits, +//! saves and exports as a group. The record lists the objects in their order along the path, each +//! with the frame it is drawn in and the angle that frame is turned by. [`place`] spreads them +//! evenly along the path from its first anchor (the first object sits on that anchor, and the last +//! one sits on the end of an open path), puts the attachment point of each one +//! ([`ObjectsOnPath::pivot`]) on the path, and turns its frame to the path's direction there, +//! tilted by [`ObjectsOnPath::rotate`]. +//! +//! Behavior: . + +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use serde::{Deserialize, Serialize}; +use vectorcraft_geom::{Affine, PathData, Point}; + +use crate::blend::Spine; +use crate::symbols::SymbolBoxes; +use crate::{Node, NodeId, NodeKind}; + +/// The center of the nine reference points. +pub const CENTER: u8 = 4; + +fn center() -> u8 { + CENTER +} + +/// What makes a group an Objects on Path group (see the module docs). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ObjectsOnPath { + /// The child of the group that is the path. + pub path: NodeId, + /// The attached objects, in their order along the path. + #[serde(default)] + pub members: Vec, + /// Pivot: the reference point of each object that attaches to the path, 0 to 8, row by row + /// from the top left of the object's bounds in its frame (4: the center). + #[serde(default = "center")] + pub pivot: u8, + /// Rotate: the counter-clockwise degrees each object is turned from upright on the path. An + /// upright object has its frame's x axis along the path's direction at its attachment point. + #[serde(default, skip_serializing_if = "crate::skip::is_default")] + pub rotate: f64, +} + +/// An object attached to the path of an Objects on Path group. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(from = "MemberWire")] +pub struct Member { + pub id: NodeId, + /// The object's frame, mapped to the document: the object's art is drawn in this frame. + pub frame: Affine, + /// The angle the frame is turned by (radians, the document's axes): the path's direction at + /// the object's attachment point plus the tilt from Rotate when it was placed, or the angle of + /// the frame's x axis before then. + pub angle: f64, +} + +/// A [`Member`] as read from a file: without `angle`, the angle of the frame's x axis. +#[derive(Deserialize)] +struct MemberWire { + id: NodeId, + frame: Affine, + #[serde(default)] + angle: Option, +} + +impl From for Member { + fn from(w: MemberWire) -> Self { + let angle = w.angle.filter(|a| a.is_finite()).unwrap_or_else(|| x_angle(w.frame)); + Self { id: w.id, frame: w.frame, angle } + } +} + +/// The angle of `frame`'s x axis (radians, the document's axes). +fn x_angle(frame: Affine) -> f64 { + let [a0, a1, ..] = frame.as_coeffs(); + a1.atan2(a0) +} + +impl Member { + /// `n` in its frame as drawn ([`upright_frame`]). + pub fn new(n: &Node) -> Self { + let frame = upright_frame(n); + Self { id: n.id, frame, angle: x_angle(frame) } + } +} + +impl ObjectsOnPath { + /// A record for the objects `members` (in their order along the path) attached to `path`, each + /// in its frame as drawn ([`upright_frame`]). + pub fn new(path: NodeId, members: &[&Node], pivot: u8, rotate: f64) -> Self { + let members = members.iter().map(|n| Member::new(n)).collect(); + Self { path, members, pivot: pivot.min(8), rotate: if rotate.is_finite() { rotate } else { 0.0 } } + } + /// The frames go with the group, and each frame's angle becomes the transformed path's + /// direction at the object plus the tilt, so that [`place`] keeps each object's scale, shear + /// and reflection when it spreads the objects along the transformed path again. A reflection + /// also reverses Rotate: the objects keep the mirrored tilt to the mirrored path. + pub fn transform(&mut self, a: Affine) { + let before = tilt(self.rotate); + if a.determinant() < 0.0 && self.rotate != 0.0 { + self.rotate = -self.rotate; + } + let after = tilt(self.rotate); + let [a0, a1, a2, a3, _, _] = a.as_coeffs(); + for m in &mut self.members { + m.frame = a * m.frame; + let (sin, cos) = (m.angle - before).sin_cos(); + let (x, y) = (a0 * cos + a2 * sin, a1 * cos + a3 * sin); + if x.is_finite() && y.is_finite() && (x != 0.0 || y != 0.0) { + m.angle = y.atan2(x) + after; + } + } + } + /// The children given new ids (a copy of the group): the path and the objects by their new ids. + pub fn rename(&mut self, ids: &HashMap) { + let to = |id: NodeId| ids.get(&id).copied().unwrap_or(id); + self.path = to(self.path); + for m in &mut self.members { + m.id = to(m.id); + } + } + /// The group's children changed from `before` to `after`: a new child at the index of a member + /// that is gone replaces it (Break Link to Symbol, for one), keeping its place on the path. + pub fn follow_replacements(&mut self, before: &[Arc], after: &[Arc]) { + let now: HashSet = after.iter().map(|c| c.id).collect(); + let then: HashSet = before.iter().map(|c| c.id).collect(); + let listed: HashSet = self.members.iter().map(|m| m.id).collect(); + let mut ids = HashMap::new(); + for (old, new) in before.iter().zip(after) { + if listed.contains(&old.id) && !now.contains(&old.id) && !then.contains(&new.id) && new.id != self.path { + ids.insert(old.id, new.id); + } + } + if !ids.is_empty() { + self.rename(&ids); + } + } +} + +/// Is `n` an Objects on Path group? +pub fn is_objects_on_path(n: &Node) -> bool { + matches!(n.kind, NodeKind::Group { .. }) && n.extras().objects_on_path.is_some() +} + +/// The path of `n` if it is a path object an Objects on Path group can attach objects to: a path +/// (not a guide) whose first subpath has some length. +pub fn attachable_path(n: &Node) -> Option<&PathData> { + match &n.kind { + NodeKind::Path { path, guide: false, .. } if Spine::new(path).is_some_and(|s| s.length() > 1e-9) => Some(path), + _ => None, + } +} + +/// The frame `n` is drawn in when it is attached: the page's axes turned by its rotation +/// ([`Node::bbox_angle`]) less the nearest multiple of 90°, about the center of its bounds. Placed in +/// that frame, an object stands square to the path or across it. +pub fn upright_frame(n: &Node) -> Affine { + let a = n.bbox_angle; + let off = if a.is_finite() { a - (a / 90.0).round() * 90.0 } else { 0.0 }; + match n.geometric_bounds() { + Some(b) if off.abs() > 1e-9 => Affine::rotate_about(-off.to_radians(), b.center()), + _ => Affine::IDENTITY, + } +} + +/// Where `n` objects attach along `path` (its first subpath): the point and the direction there +/// (radians, as `atan2` gives in the document's axes). They are spread evenly by length from the +/// first anchor: on an open path the last one is at its end, on a closed path the gaps go all the way +/// around. `None` for a path without length. +pub fn stops(path: &PathData, n: usize) -> Option> { + let spine = Spine::new(path)?; + let len = spine.length(); + if !len.is_finite() || len <= 1e-9 { + return None; + } + let closed = path.subpaths.first().is_some_and(|s| s.closed); + let gaps = if closed { n } else { n.saturating_sub(1) }.max(1); + Some((0..n).map(|i| spine.at_length(len * i as f64 / gaps as f64)).collect()) +} + +/// The tilt Rotate gives (radians, the document's axes, where y points down): `rotate` degrees +/// counter-clockwise on the page. +fn tilt(rotate: f64) -> f64 { + -rotate.to_radians() +} + +/// The frame that puts the attachment point `pivot` of `n` (drawn in `m`'s frame) at `at`, turned +/// by `angle` (radians, the document's axes) instead of `m`'s angle: the frame's own scale, shear +/// and reflection are kept. Symbol instances are measured by their art (`symbols`). +fn placed_frame(n: &Node, symbols: &SymbolBoxes, m: &Member, pivot: u8, at: Point, angle: f64) -> Option { + let det = m.frame.determinant(); + if !det.is_finite() || det.abs() < 1e-12 || !at.x.is_finite() || !at.y.is_finite() || !angle.is_finite() || !m.angle.is_finite() { + return None; + } + let mut local = n.clone(); + local.transform(m.frame.inverse(), false); + let q = vectorcraft_geom::reference_point(local.geometric_bounds_with(symbols)?, usize::from(pivot.min(8))); + let [a0, a1, a2, a3, _, _] = m.frame.as_coeffs(); + let shape = Affine::rotate(-m.angle) * Affine::new([a0, a1, a2, a3, 0.0, 0.0]); + Some(Affine::translate(at.to_vec2()) * Affine::rotate(angle) * shape * Affine::translate(-q.to_vec2())) +} + +/// Is `a` the identity, give or take rounding? +fn negligible(a: Affine) -> bool { + let [a0, a1, a2, a3, a4, a5] = a.as_coeffs(); + (a0 - 1.0).abs() < 1e-9 && a1.abs() < 1e-9 && a2.abs() < 1e-9 && (a3 - 1.0).abs() < 1e-9 && a4.abs() < 1e-6 && a5.abs() < 1e-6 +} + +/// Put the objects of Objects on Path group `g` on its path (see the module docs). Before that, the +/// record lets go of the objects that are no longer in the group, and children it does not list +/// (other than the path) join it at the end of the path. A group whose path is gone, or is no +/// longer a path object, becomes a plain group. Symbol instances are measured by their art +/// (`symbols`, from the document the group is in). Returns whether `g` changed. +pub fn place(g: &mut Node, symbols: &SymbolBoxes) -> bool { + let Some(mut rec) = g.extras().objects_on_path.as_deref().cloned() else { return false }; + let old = rec.clone(); + let NodeKind::Group { children, .. } = &mut g.kind else { return false }; + let path_id = rec.path; + let Some(path) = children.iter().find(|c| c.id == path_id).filter(|c| matches!(c.kind, NodeKind::Path { .. })) else { + g.extras_mut().objects_on_path = None; + return true; + }; + let path = attachable_path(path).cloned(); + let at: HashMap = children.iter().enumerate().map(|(i, c)| (c.id, i)).collect(); + rec.members.retain(|m| m.id != path_id && at.contains_key(&m.id)); + let mut listed: HashSet = rec.members.iter().map(|m| m.id).collect(); + for c in children.iter() { + if c.id != path_id && listed.insert(c.id) { + rec.members.push(Member::new(c)); + } + } + let mut moved = false; + if let Some(stops) = path.and_then(|p| stops(&p, rec.members.len())) { + let turn = tilt(rec.rotate); + for (m, (p, dir)) in rec.members.iter_mut().zip(stops) { + let Some(c) = at.get(&m.id).and_then(|i| children.get_mut(*i)) else { continue }; + let Some(next) = placed_frame(c, symbols, m, rec.pivot, p, dir + turn) else { continue }; + let delta = next * m.frame.inverse(); + if !negligible(delta) { + Arc::make_mut(c).transform(delta, false); + *m = Member { id: m.id, frame: next, angle: dir + turn }; + moved = true; + } + } + } + if rec != old { + g.extras_mut().objects_on_path = Some(Box::new(rec)); + return true; + } + moved +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_geom::{Rect, shapes}; + + fn rect(id: u64, r: Rect) -> Node { + Node::path(NodeId(id), shapes::rectangle(r), Default::default()) + } + + #[test] + fn stops_spread_from_the_first_anchor() { + let open = shapes::line(Point::new(0.0, 0.0), Point::new(300.0, 0.0)); + let s = stops(&open, 4).unwrap(); + let xs: Vec = s.iter().map(|(p, _)| p.x.round()).collect(); + assert_eq!(xs, [0.0, 100.0, 200.0, 300.0], "first at the start, last at the end of an open path"); + let closed = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)); + let s = stops(&closed, 4).unwrap(); + let mut pts: Vec<(i64, i64)> = s.iter().map(|(p, _)| (p.x.round() as i64, p.y.round() as i64)).collect(); + pts.sort(); + assert_eq!(pts, [(0, 0), (0, 100), (100, 0), (100, 100)], "a closed path spreads them all the way round"); + assert!(stops(&shapes::line(Point::ZERO, Point::ZERO), 2).is_none()); + } + + #[test] + fn upright_frames_round_the_rotation_to_a_right_angle() { + let mut n = rect(1, Rect::new(0.0, 0.0, 10.0, 10.0)); + assert_eq!(upright_frame(&n), Affine::IDENTITY); + n.bbox_angle = 90.0; + assert_eq!(upright_frame(&n), Affine::IDENTITY); + n.bbox_angle = 30.0; + let f = upright_frame(&n); + let [a0, a1, ..] = f.as_coeffs(); + assert!((a1.atan2(a0).to_degrees() + 30.0).abs() < 1e-9, "a frame turned 30° counter-clockwise"); + } + + #[test] + fn a_symbol_instance_is_placed_by_its_art() { + // The art is a 40 × 10 box to the right of and below the origin, not the 20 × 20 square + // around it that instances are measured by without the symbols. + let mut d = crate::Document::new(400.0, 400.0); + d.symbols.push(crate::Symbol { name: "Bar".into(), art: Arc::new(rect(9, Rect::new(0.0, 0.0, 40.0, 10.0))) }); + let line = Node::path(NodeId(1), shapes::line(Point::new(100.0, 300.0), Point::new(300.0, 300.0)), Default::default()); + let instance = Node::new(NodeId(2), NodeKind::SymbolInstance { symbol: "Bar".into(), xf: Affine::IDENTITY }); + let other = rect(3, Rect::new(0.0, 0.0, 10.0, 10.0)); + let members = [&instance, &other]; + let mut g = Node::new( + NodeId(4), + NodeKind::Group { children: vec![Arc::new(line), Arc::new(instance.clone()), Arc::new(other.clone())], clip: false }, + ); + g.extras_mut().objects_on_path = Some(Box::new(ObjectsOnPath::new(NodeId(1), &members, 7, 0.0))); + let symbols = d.symbol_boxes(); + assert!(place(&mut g, &symbols)); + let placed = g.children().and_then(|c| c.iter().find(|c| c.id == NodeId(2)).cloned()).unwrap(); + let b = placed.geometric_bounds_with(&symbols).unwrap(); + assert!((b.y1 - 300.0).abs() < 1e-9 && (b.center().x - 100.0).abs() < 1e-9, "the art's bottom middle on the start: {b:?}"); + } + + #[test] + fn a_member_saved_without_its_angle_reads_the_angle_of_its_frame() { + let m = Member { id: NodeId(2), frame: Affine::rotate(0.5), angle: 0.5 }; + let mut v = serde_json::to_value(m).unwrap(); + assert_eq!(serde_json::from_value::(v.clone()).unwrap(), m); + v.as_object_mut().unwrap().remove("angle"); + let back: Member = serde_json::from_value(v).unwrap(); + assert!((back.angle - 0.5).abs() < 1e-12, "{back:?}"); + } + + #[test] + fn a_group_without_its_path_is_a_plain_group() { + let a = rect(2, Rect::new(0.0, 0.0, 10.0, 10.0)); + let mut g = Node::new(NodeId(3), NodeKind::Group { children: vec![Arc::new(a.clone())], clip: false }); + g.extras_mut().objects_on_path = Some(Box::new(ObjectsOnPath::new(NodeId(1), &[&a], CENTER, 0.0))); + let d = crate::Document::new(100.0, 100.0); + assert!(place(&mut g, &d.symbol_boxes())); + assert!(!is_objects_on_path(&g)); + } +} diff --git a/crates/doc/src/pattern.rs b/crates/doc/src/pattern.rs index 6b9d902bab..1b587e70fa 100644 --- a/crates/doc/src/pattern.rs +++ b/crates/doc/src/pattern.rs @@ -467,6 +467,14 @@ impl RepeatKind { RepeatKind::Mirror { .. } => "Mirror Repeat", } } + /// How many instances [`repeat_transforms`] makes (with its clamps). + fn count(&self) -> usize { + match self { + RepeatKind::Radial { instances, .. } => (*instances).clamp(1, 1000) as usize, + RepeatKind::Grid { rows, cols, .. } => (*rows).clamp(1, 500) as usize * (*cols).clamp(1, 500) as usize, + RepeatKind::Mirror { .. } => 2, + } + } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -475,6 +483,23 @@ pub struct RepeatSpec { pub source: Vec>, } +/// Most instances a Repeat makes in all, those of the Repeats nested in its source included: as +/// many as one 500 × 500 grid, the budget [`PatternDef::offsets_covering`] also keeps. +const MAX_REPEAT_INSTANCES: usize = 250_000; + +/// Instances the Repeats in `nodes` make in all (0 when there are none). +fn nested_instances(nodes: &[Arc]) -> usize { + let mut sum = 0usize; + for n in nodes { + sum = sum.saturating_add(match (&n.kind, n.children()) { + (NodeKind::Repeat(r), _) => r.instances_in_all(), + (_, Some(c)) => nested_instances(c), + _ => 0, + }); + } + sum +} + /// Reflection across the line through `c` with direction angle `deg`. pub fn reflect_about(c: Point, deg: f64) -> Affine { let t = (2.0 * deg).to_radians(); @@ -536,7 +561,21 @@ impl RepeatSpec { crate::live::nodes_bounds(&self.source) } pub fn transforms(&self) -> Vec { - repeat_transforms(&self.kind, self.source_bounds()) + let mut v = repeat_transforms(&self.kind, self.source_bounds()); + // Each instance draws the Repeats in the source again, so nested ones multiply (a 500 × 500 + // grid of one is 62.5 billion instances): keep the first that fit the budget. + v.truncate(self.kept(nested_instances(&self.source))); + v + } + /// How many of its instances this Repeat keeps when each makes `nested` instances of the + /// Repeats in its source: as many as fit in [`MAX_REPEAT_INSTANCES`], at least one. + fn kept(&self, nested: usize) -> usize { + self.kind.count().min(MAX_REPEAT_INSTANCES / nested.max(1)).max(1) + } + /// Instances made in all, those of the Repeats nested in the source included. + fn instances_in_all(&self) -> usize { + let nested = nested_instances(&self.source); + self.kept(nested).saturating_mul(nested.max(1)) } /// Evaluated instances: one group of the (transformed) source per instance (ids 0). pub fn expand(&self) -> Vec { @@ -838,6 +877,35 @@ mod tests { assert!((angle.rem_euclid(180.0) - 0.0).abs() < 1e-9 || (angle.rem_euclid(180.0) - 180.0).abs() < 1e-9, "{angle}"); } + #[test] + fn nested_repeats_share_one_instance_budget() { + // Instances made in all, counted from the transforms without drawing any. + fn made(r: &RepeatSpec) -> usize { + let each: usize = r.source.iter().map(|s| if let NodeKind::Repeat(n) = &s.kind { made(n) } else { 1 }).sum(); + r.transforms().len().saturating_mul(each) + } + let grid = |source: Arc| { + let mut g = RepeatSpec::grid(vec![source], 0.0, 0.0); + if let RepeatKind::Grid { rows, cols, .. } = &mut g.kind { + *rows = 500; + *cols = 500; + } + g + }; + let repeat = |r: RepeatSpec| Arc::new(Node::new(NodeId(2), NodeKind::Repeat(r))); + // One grid keeps all its instances. + let inner = grid(sq(0.0, 0.0, 1.0)); + assert_eq!(made(&inner), 250_000); + // A 500 × 500 grid of it made 62.5 billion. + let outer = grid(repeat(inner.clone())); + assert!(made(&outer) <= 250_000, "{} instances", made(&outer)); + assert_eq!(outer.expand().len(), outer.transforms().len()); + assert!(made(&RepeatSpec::mirror(vec![repeat(inner)], 90.0, 5.0)) <= 250_000); + // Small nests are left as they are. + let small = RepeatSpec::mirror(vec![repeat(RepeatSpec::grid(vec![sq(0.0, 0.0, 10.0)], 1.0, 1.0))], 90.0, 5.0); + assert_eq!(made(&small), 18); + } + #[test] fn serde_roundtrip() { let mut def = PatternDef::new("Dots", vec![sq(0.0, 0.0, 10.0)]); diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs index ba8eb4b9f1..1d45f5d738 100644 --- a/crates/doc/src/selection.rs +++ b/crates/doc/src/selection.rs @@ -43,6 +43,11 @@ pub struct Selection { /// guides and objects can be selected together, in either order. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub guides: Vec, + /// A selected ruler guide that is the key object for Align instead of [`Self::key`] (an index + /// into [`Document::guides`], one of [`Self::guides`]): the objects line up on it. Never set + /// with `key`; [`Self::prune`] clears it when no object is selected to align to it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub key_guide: Option, } impl Selection { @@ -67,6 +72,11 @@ impl Selection { self.target = None; self.slices.clear(); self.guides.clear(); + self.key_guide = None; + } + /// Is there a key for Align: an object or a guide? + pub fn has_key(&self) -> bool { + self.key.is_some() || self.key_guide.is_some() } pub fn set(&mut self, ids: impl IntoIterator) { self.clear(); @@ -114,6 +124,9 @@ impl Selection { pub fn toggle_guide(&mut self, i: usize) { if let Some(k) = self.guides.iter().position(|g| *g == i) { self.guides.remove(k); + if self.key_guide == Some(i) { + self.key_guide = None; + } } else { self.guides.push(i); } @@ -162,13 +175,16 @@ impl Selection { refs.retain(|&(si, seg)| path.subpaths.get(si).is_some_and(|sp| seg < sp.segment_count())); !refs.is_empty() && self.objects.contains(id) && self.anchors.contains_key(id) }); - // The key object stays while another selected object lies outside it. + // Guides on a hidden or locked layer can't stay selected. + self.guides.retain(|i| doc.guides.get(*i).is_some_and(|g| doc.guide_editable(g))); + // The key object stays while another selected object lies outside it, or while ruler + // guides are selected for it to line up (#2143). let keep = self.key.and_then(|k| found.get(&k)).and_then(|p| doc.node_at(p)).is_some_and(|n| { let mut inside = BTreeSet::new(); n.walk(&mut |c| { inside.insert(c.id); }); - self.objects.iter().any(|o| !inside.contains(o)) + self.objects.iter().any(|o| !inside.contains(o)) || (self.objects.contains(&n.id) && !self.guides.is_empty()) }); if !keep { self.key = None; @@ -177,8 +193,10 @@ impl Selection { self.target = None; } self.slices.retain(|id| doc.is_slice(*id)); - // Guides on a hidden or locked layer can't stay selected. - self.guides.retain(|i| doc.guides.get(*i).is_some_and(|g| doc.guide_editable(g))); + // A key guide needs objects to line up on it, and stays selected. + if self.key.is_some() || self.objects.is_empty() || self.key_guide.is_some_and(|k| !self.guides.contains(&k)) { + self.key_guide = None; + } } /// Deselect the objects that are hidden or locked, themselves or through a group or layer /// around them (and so the key object when it is one): hidden or locked art can't stay diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index 132e0cba00..2bdd0f2888 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -107,9 +107,10 @@ fn bake_node(d: &mut Document, n: &Node) -> Option { let m = evaluate_container(&m).unwrap_or(m); return Some(bake_pieces(d, m)); } - // Type, images, symbol instances and live objects: reshaped through their outlines, and so is - // type whose own fills or strokes have geometry effects ([`has_item_geometry`]). Type that - // Transform effects only move and copy stays type, moved to each place. + // Type, images, symbol instances and live objects: reshaped through their outlines, and so are + // type whose own fills or strokes have geometry effects and images whose own fills or strokes + // paint a shape ([`has_item_geometry`]). Type that Transform effects only move and copy stays + // type, moved to each place. if needs_outline(n) && (has_geometry(&n.appearance.effects) || n.projection().is_some() || has_item_geometry(n)) { if let Some(m) = moved_type_group(n) { return Some(bake_pieces(d, m)); diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 12de8f8610..45b50d5f97 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -56,7 +56,7 @@ mod tests; mod tests_scale; use serde_json::{Map, Value, json}; -use vectorcraft_doc::{AppearanceItem, Effect, Node, NodeKind, StrokeLayer}; +use vectorcraft_doc::{Appearance, AppearanceItem, Effect, Node, NodeKind, StrokeLayer}; use vectorcraft_geom::{BezPath, FillRule, PathData, Rect}; pub use adjust::{ @@ -73,7 +73,7 @@ pub use live::{expand_live, expand_live_deep, expanded_live_group, text_outliner pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks}; pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace}; pub use raster::{RASTERIZE, RasterFx, Rasterize, outset, raster_effects}; -pub use reshape::{expand_outlined, has_gradient_copies, has_item_geometry, needs_outline, outline_art, outline_text, reshape}; +pub use reshape::{expand_outlined, has_gradient_copies, has_item_geometry, image_paint, needs_outline, outline_art, outline_text, reshape}; pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_options, validate_revolve}; pub use solids::{ EXTRUDE, INFLATE, ROTATE, ROTATION_PRESETS, SOLIDS, extrude_options, has_solid, inflate_options, is_three_d, solid_art, validate_solid, @@ -153,7 +153,9 @@ fn lengths_of(id: &str) -> Lengths { "texture.mosaicTiles" => always(&["tileSize"]), "texture.patchwork" => always(&["squareSize"]), "texture.stainedGlass" => always(&["cellSize"]), + "sketch.graphicPen" => always(&["strokeLength"]), "sketch.halftonePattern" => always(&["size"]), + "sketch.notePaper" => always(&["relief"]), RASTERIZE => always(&["addAround"]), _ => Lengths::default(), } @@ -362,6 +364,13 @@ pub fn effect_catalog() -> Vec { "{glowSize: -24..24 (5; above 0 the light areas glow, below 0 the dark ones; farther from 0 spreads the glow wider), glowBrightness: 0..50 (15; a stronger glow over dimmer greys), color: \"#rrggbb\" (\"#4da6ff\"; the glow's colour)} redraws the object in greys lit by a coloured glow, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.", json!({"glowSize": 5.0, "glowBrightness": 15.0, "color": "#4da6ff"}), ), + r( + "artistic.plasticWrap", + "Plastic Wrap…", + ARTISTIC, + "{highlightStrength: 0..20 (20; brighter specular highlights), detail: 0..15 (12; finer wrinkles in document space), smoothness: 1..15 (15; softer folds)} coats the object in shiny plastic, keeping its coverage. highlightStrength 0 leaves the art unchanged. Original visual approximation; chosen VectorCraft defaults.", + json!({"highlightStrength": 20.0, "detail": 12.0, "smoothness": 15.0}), + ), r( "artistic.posterEdges", "Poster Edges…", @@ -369,6 +378,27 @@ pub fn effect_catalog() -> Vec { "{edgeThickness: 0..10 (2; wider lines), edgeIntensity: 0..10 (1; darker lines, on fainter edges too), posterization: 0..6 (2; posterization + 2 levels per colour channel)} reduces the object's colours and draws black lines on its edges, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.", json!({"edgeThickness": 2.0, "edgeIntensity": 1.0, "posterization": 2.0}), ), + r( + "artistic.smudgeStick", + "Smudge Stick…", + ARTISTIC, + "{strokeLength: 0..10 (2; length of the short diagonal strokes), highlightArea: 0..20 (12; widens the area counted as light), intensity: 0..10 (10; how far the light areas are lightened)} smudges the dark areas along short diagonal strokes; the lighter areas become brighter and lose detail. Coverage is kept. Original visual approximation; chosen VectorCraft defaults.", + json!({"strokeLength": 2.0, "highlightArea": 12.0, "intensity": 10.0}), + ), + r( + "artistic.sponge", + "Sponge…", + ARTISTIC, + "{brushSize: 0..10 (2; size of the sponge's pores), definition: 0..25 (12; how strongly lighter and darker blobs contrast), smoothness: 1..15 (5; softer blob edges)} paints the object as if dabbed with a sponge, in highly textured areas of contrasting colour. Coverage is kept. Original visual approximation; chosen VectorCraft defaults.", + json!({"brushSize": 2.0, "definition": 12.0, "smoothness": 5.0}), + ), + r( + "artistic.watercolor", + "Watercolor…", + ARTISTIC, + "{brushDetail: 1..14 (9; the larger, the more detail stays), shadowIntensity: 0..10 (1; deepens the shadows), texture: 1..3 (1; paper grain, whole numbers)} paints the object in a watercolor style: detail simplified, colour saturated and darker where tones change at edges. Coverage is kept. Original visual approximation; chosen VectorCraft defaults.", + json!({"brushDetail": 9.0, "shadowIntensity": 1.0, "texture": 1.0}), + ), r( "blur.radial", "Radial Blur…", @@ -467,13 +497,83 @@ pub fn effect_catalog() -> Vec { "{amount: % 1..500 (50), radius: pt 0.1..250 (1; σ of the blur edges are found against), threshold: levels 0..255 (0; smaller differences are left alone)}", json!({"amount": 50.0, "radius": 1.0, "threshold": 0.0}), ), + r( + "sketch.basRelief", + "Bas Relief…", + SKETCH, + "{detail: 1..15 (13; the larger, the finer the features that stay), smoothness: 1..15 (3; rounds the carving), lightDirection: \"bottom\"|\"bottomLeft\"|\"left\"|\"topLeft\"|\"top\"|\"topRight\"|\"right\"|\"bottomRight\" (\"bottom\"; where the light comes from)} carves the object in low relief in black and white: surfaces facing the light turn white, those turned away black, flat areas grey. Coverage is kept. Original visual approximation; chosen VectorCraft defaults.", + json!({"detail": 13.0, "smoothness": 3.0, "lightDirection": "bottom"}), + ), + r( + "sketch.chalkCharcoal", + "Chalk & Charcoal…", + SKETCH, + "{chalkArea: 0..20 (6; chalk in light areas), charcoalArea: 0..20 (6; charcoal in dark areas), strokePressure: 0..5 (2)} redraws the object with chalk highlights and charcoal strokes on white paper, keeping its coverage. Original visual approximation from public documentation; slider ranges and defaults are VectorCraft choices, not verified proprietary values.", + json!({"chalkArea": 6.0, "charcoalArea": 6.0, "strokePressure": 2.0}), + ), + r( + "sketch.charcoal", + "Charcoal…", + SKETCH, + "{thickness: 1..7 (1; width of the bold edges and of the strokes' spacing), detail: 0..5 (1; the larger, the finer the edges), lightDarkBalance: 0..100 (50; how far into the lights the charcoal reaches)} redraws the object in black charcoal on white paper: bold edges and diagonal strokes over the midtones. Coverage is kept. Original visual approximation; chosen VectorCraft defaults.", + json!({"thickness": 1.0, "detail": 1.0, "lightDarkBalance": 50.0}), + ), + r( + "sketch.chrome", + "Chrome…", + SKETCH, + "{detail: 0..10 (4; finer surface texture), smoothness: 0..10 (4; softer relief before the highlights and shadows)} treats the object as polished chrome lit from the top left: bright highlights on high points and dark shadows in low ones, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.", + json!({"detail": 4.0, "smoothness": 4.0}), + ), + r( + "sketch.graphicPen", + "Graphic Pen…", + SKETCH, + "{strokeLength: pt 1..15 (5; the longest ink stroke), lightDarkBalance: 0..100 (50; more black when higher), strokeDirection: \"rightDiagonal\"|\"horizontal\"|\"leftDiagonal\"|\"vertical\" (\"rightDiagonal\")} redraws the object in fine linear black ink on white paper, with strokes denser in darker areas. Control names and ranges follow the public documentation; the defaults are unverified.", + json!({"strokeLength": 5.0, "lightDarkBalance": 50.0, "strokeDirection": "rightDiagonal"}), + ), r( "sketch.halftonePattern", "Halftone Pattern…", SKETCH, - "{size: pt 1..12 (1; how far apart the screen's dots, rings or lines are), contrast: 0..50 (5; 50 draws pure black and white), patternType: \"circle\"|\"dot\"|\"line\" (\"dot\"; rings round the object's centre, dots on a square grid, horizontal lines)} redraws the object in black ink on white paper through a halftone screen whose ink covers as much as the colour is dark, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.", + "{size: pt 1..12 (1; how far apart the screen's dots, rings or lines are), contrast: 0..50 (5; 50 draws pure black and white), patternType: \"circle\"|\"dot\"|\"line\" (\"dot\"; rings round the object's centre, dots on a square grid, horizontal lines)} redraws the object in black ink on white paper through a halftone screen whose ink covers as much as the colour is dark, keeping its coverage. Original visual approximation from the public Sketch effects reference; slider ranges follow the documented control names, numeric defaults are chosen for VectorCraft and are not verified against proprietary defaults (the public help pages give no numbers).", json!({"size": 1.0, "contrast": 5.0, "patternType": "dot"}), ), + r( + "sketch.notePaper", + "Note Paper…", + SKETCH, + "{imageBalance: 0..50 (25; lower tones darken the emboss, higher lighten it), graininess: 0..10 (0; fibrous paper texture), relief: 0..50 (4; emboss strength in points)} embosses the object's tones on warm paper, keeping its coverage. Original visual approximation from the public Sketch effects reference; slider ranges follow the documented control names, numeric defaults are chosen for VectorCraft and are not verified against proprietary defaults (the public help pages give no numbers).", + json!({"imageBalance": 25.0, "graininess": 0.0, "relief": 4.0}), + ), + r( + "sketch.photocopy", + "Photocopy…", + SKETCH, + "{detail: 1..24 (7; the larger, the finer the features that copy), darkness: 1..50 (25; the larger, the more of the dark copies)} copies the object in black on white: large dark areas copy only around their edges and midtones go to black or white. Coverage is kept. Original visual approximation; chosen VectorCraft defaults.", + json!({"detail": 7.0, "darkness": 25.0}), + ), + r( + "sketch.plaster", + "Plaster…", + SKETCH, + "{imageBalance: 1..50 (20; higher values sink more of the image), smoothness: 1..15 (8; higher values soften the relief), lightDirection: \"bottom\"|\"bottomLeft\"|\"left\"|\"topLeft\"|\"top\"|\"topRight\"|\"right\"|\"bottomRight\" (\"top\")} molds the object in relief plaster and lights it from that direction; dark areas are raised and light areas recessed, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.", + json!({"imageBalance": 20.0, "smoothness": 8.0, "lightDirection": "top"}), + ), + r( + "sketch.reticulation", + "Reticulation…", + SKETCH, + "{density: 0..50 (12; finer grain at higher values), foregroundLevel: 0..50 (6; pulls shadows toward black ink), backgroundLevel: 0..50 (6; pulls highlights toward white paper)} redraws the object in black ink on white paper through a high-contrast film-grain screen, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.", + json!({"density": 12.0, "foregroundLevel": 6.0, "backgroundLevel": 6.0}), + ), + r( + "sketch.stamp", + "Stamp…", + SKETCH, + "{lightDarkBalance: 0..50 (25; the larger, the more of the object prints black), smoothness: 1..50 (5; rounds the shapes)} simplifies the object to solid black and white, as a rubber stamp would print it. Coverage is kept. Original visual approximation; chosen VectorCraft defaults.", + json!({"lightDarkBalance": 25.0, "smoothness": 5.0}), + ), r( "stylize.glowingEdges", "Glowing Edges…", @@ -841,6 +941,12 @@ pub struct GeomContext<'a> { /// The seed of the Transform effect's Random: the object's id, so each object varies its own /// way and keeps its result on every redraw. pub seed: u64, + /// The object's appearance, which live-effect plug-ins are given read only (their fills and + /// strokes). + pub appearance: Option<&'a Appearance>, + /// The index in `appearance.items` of the fill or stroke whose own effects these are; `None`: + /// the object's effects. + pub item: Option, } impl<'a> GeomContext<'a> { @@ -850,15 +956,17 @@ impl<'a> GeomContext<'a> { NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. } => *rule, _ => FillRule::NonZero, }; - Self { stroke: n.appearance.stroke().filter(|s| !s.paint.is_none() && s.width > 0.0), rule, seed: n.id.0 } + let stroke = n.appearance.stroke().filter(|s| !s.paint.is_none() && s.width > 0.0); + Self { stroke, rule, seed: n.id.0, appearance: Some(&n.appearance), item: None } } /// The context of the effects on `item`, one of the same object's appearance items: a - /// stroke's own effects outline that stroke. + /// stroke's own effects outline that stroke, and a plug-in is told which item it is on. pub fn item(self, item: &'a AppearanceItem) -> Self { + let at = self.appearance.and_then(|a| a.items.iter().position(|i| std::ptr::eq(i, item))); match item { - AppearanceItem::Stroke(s) => Self { stroke: Some(s), ..self }, - AppearanceItem::Fill(_) => self, + AppearanceItem::Stroke(s) => Self { stroke: Some(s), item: at, ..self }, + AppearanceItem::Fill(_) => Self { item: at, ..self }, } } } @@ -897,7 +1005,8 @@ pub fn apply_geometry_bez(effects: &[Effect], path: &BezPath, bounds: Rect, ctx: pub(crate) fn apply_one(id: &str, p: &Value, path: &PathData, b: Rect, ctx: &GeomContext) -> PathData { use util::*; if let Some(plugin) = vectorcraft_plugins::effect::plugin_id(id) { - return vectorcraft_plugins::effect::apply(plugin, p, path, b, ctx.rule).unwrap_or_else(|| path.clone()); + let paints = vectorcraft_plugins::effect::Paints { appearance: ctx.appearance, item: ctx.item }; + return vectorcraft_plugins::effect::apply(plugin, p, path, b, ctx.rule, paints).unwrap_or_else(|| path.clone()); } match id { "distort.freeDistort" => distort::free_distort(path, b, p), diff --git a/crates/effects/src/pixel/artistic.rs b/crates/effects/src/pixel/artistic.rs index f18b1709a0..0d6764feb6 100644 --- a/crates/effects/src/pixel/artistic.rs +++ b/crates/effects/src/pixel/artistic.rs @@ -1,4 +1,4 @@ -//! Effect › Artistic (Cutout, Film Grain, Neon Glow, Poster Edges). Original filters built from +//! Effect › Artistic (Cutout, Film Grain, Neon Glow, Plastic Wrap, Poster Edges). Original filters built from //! public behaviour documentation: //! and //! . @@ -6,6 +6,8 @@ use super::edges::sobel; use super::pixelate::{Place, cell, rand}; + +const SALT_PLASTIC: u64 = 512; use super::texture::{luma, premultiply, straight}; use super::{PixelSpace, blur_plane}; use vectorcraft_geom::Point; @@ -239,6 +241,79 @@ pub(super) fn poster_edges(px: &mut [[u8; 4]], w: usize, h: usize, space: &Pixel } } +/// How far (document units) Plastic Wrap's softened relief is sampled at `smoothness` (1..15). +pub(super) fn plastic_reach(smoothness: f64) -> f64 { + 3.0 * (0.15 + 0.35 * smoothness.clamp(1.0, 15.0)) +} + +/// Plastic Wrap: the object under shiny plastic. Its tones form a relief; `detail` (0..15) adds +/// finer wrinkles in document space; `smoothness` (1..15) softens the relief; specular highlights +/// as strong as `highlight` (0..20) are screened over it. Coverage is kept. +pub(super) fn plastic_wrap(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, highlight: f64, detail: f64, smoothness: f64) { + if ![highlight, detail, smoothness].iter().all(|v| v.is_finite()) || !space.px.is_finite() || space.px <= 0.0 { + return; + } + let strength = (highlight / 20.0).clamp(0.0, 1.0) as f32; + if strength == 0.0 { + return; + } + let detail_amt = (detail / 15.0).clamp(0.0, 1.0) as f32; + let sigma = (0.15 + 0.35 * smoothness.clamp(1.0, 15.0)) / space.px; + let Some(place) = Place::new(space, w, h) else { return }; + let len = px.len(); + let mut height = vec![0.0f32; len]; + let alpha: Vec = px.iter().map(|p| f32::from(p[3]) / 255.0).collect(); + let cell_scale = 8.0 + 24.0 * (1.0 - detail_amt as f64); + let mut noise = CellNoise::default(); + place.each(px, |x, y, p| { + if p[3] == 0 { + return; + } + let i = y * w + x; + let l = luma(straight(*p)); + let q = place.at(x, y); + let nq = Point::new(q.x / cell_scale, q.y / cell_scale); + height[i] = l + detail_amt * 0.35 * noise.at(SALT_PLASTIC, nq) as f32; + }); + for (h, a) in height.iter_mut().zip(&alpha) { + *h *= *a; + } + blur_plane(&mut height, w, h, sigma); + let mut cov = alpha.clone(); + blur_plane(&mut cov, w, h, sigma); + for (h, c) in height.iter_mut().zip(&cov) { + *h = if *c > 1e-4 { *h / *c } else { 0.0 }; + } + const LIGHT: [f32; 3] = [0.35, -0.25, 0.9]; + let inv = (LIGHT[0] * LIGHT[0] + LIGHT[1] * LIGHT[1] + LIGHT[2] * LIGHT[2]).sqrt().max(1e-6); + let light = LIGHT.map(|v| v / inv); + let scale = (8.0 * space.px).max(1e-6) as f32; + let sample = |x: isize, y: isize| -> f32 { + if x < 0 || y < 0 || x >= w as isize || y >= h as isize { + return 0.0; + } + height[y as usize * w + x as usize] + }; + place.each(px, |x, y, p| { + if p[3] == 0 { + return; + } + let gx = sample(x as isize + 1, y as isize) - sample(x as isize - 1, y as isize); + let gy = sample(x as isize, y as isize + 1) - sample(x as isize, y as isize - 1); + let nx = -gx / scale; + let ny = -gy / scale; + let nz = 1.0; + let nlen = (nx * nx + ny * ny + nz * nz).sqrt().max(1e-6); + let ndotl = (nx / nlen * light[0] + ny / nlen * light[1] + nz / nlen * light[2]).max(0.0); + let spec = ndotl.powi(12) * strength; + if spec <= 1e-5 { + return; + } + let c = straight(*p).map(|v| 1.0 - (1.0 - v) * (1.0 - spec)); + *p = premultiply(c, f32::from(p[3]) / 255.0); + }); +} + /// How far (document units) Neon Glow's glow spreads at `size` (-24..24). pub(super) fn glow_spread(size: f64) -> f64 { 0.25 * size.abs().min(24.0) diff --git a/crates/effects/src/pixel/brushstrokes.rs b/crates/effects/src/pixel/brushstrokes.rs index 416a67de43..d496f294ed 100644 --- a/crates/effects/src/pixel/brushstrokes.rs +++ b/crates/effects/src/pixel/brushstrokes.rs @@ -64,9 +64,9 @@ impl StrokeDirection { } /// Along a right diagonal stroke, rising to the right (y down). -const RIGHT: Vec2 = Vec2::new(FRAC_1_SQRT_2, -FRAC_1_SQRT_2); +pub(super) const RIGHT: Vec2 = Vec2::new(FRAC_1_SQRT_2, -FRAC_1_SQRT_2); /// Along a left diagonal stroke, falling to the right. -const LEFT: Vec2 = Vec2::new(FRAC_1_SQRT_2, FRAC_1_SQRT_2); +pub(super) const LEFT: Vec2 = Vec2::new(FRAC_1_SQRT_2, FRAC_1_SQRT_2); /// The most samples a stroke averages, whatever its length. const MAX_SAMPLES: usize = 16; @@ -75,7 +75,7 @@ const MAX_SAMPLES: usize = 16; const JITTER: f64 = 0.25; /// How soft (points, the σ) the tones are that decide which strokes a pixel gets. -const TONE_SOFTNESS: f64 = 1.0; +pub(super) const TONE_SOFTNESS: f64 = 1.0; /// Dark Strokes' short dark strokes and long light ones (points). pub(super) const DARK_LENGTH: f64 = 3.0; @@ -86,7 +86,7 @@ const INK_SOFTNESS: f64 = 0.6; /// A pixel at 72 ppi (points): how far the neighbours of the Sobel operator and of sampling /// between pixels add to a filter's reach. -const MARGIN: f64 = 1.0; +pub(super) const MARGIN: f64 = 1.0; /// How far (document units) strokes `len` long reach: half their length, their random shift, the /// softening between their samples and the pixels a sample is taken between. @@ -137,18 +137,18 @@ pub(super) fn spray_shift(radius: f64) -> f64 { /// The object's colours averaged along strokes `len` long: [`MAX_SAMPLES`] at most, the object /// softened first when they lie more than a pixel apart. -struct Smear<'a> { +pub(super) struct Smear<'a> { /// Premultiplied colours (0..1). src: Vec<[f32; 4]>, w: usize, h: usize, place: &'a Place, - len: f64, + pub(super) len: f64, n: usize, } impl<'a> Smear<'a> { - fn new(px: &[[u8; 4]], w: usize, h: usize, place: &'a Place, len: f64) -> Self { + pub(super) fn new(px: &[[u8; 4]], w: usize, h: usize, place: &'a Place, len: f64) -> Self { let len = if len.is_finite() { len.max(0.0) } else { 0.0 }; let span = len / place.px; let n = if span.is_finite() { (span.ceil() as usize).saturating_add(1).clamp(1, MAX_SAMPLES) } else { MAX_SAMPLES }; @@ -218,7 +218,7 @@ impl<'a> Smear<'a> { } /// The stroke of pattern `salt` through `q` along `dir`, its rows `width` apart. - fn stroke(&self, salt: u64, q: Point, dir: Vec2, width: f64) -> [f32; 4] { + pub(super) fn stroke(&self, salt: u64, q: Point, dir: Vec2, width: f64) -> [f32; 4] { self.at(q + dir * stroke_shift(salt, q, dir, self.len, width), dir) } } @@ -242,37 +242,37 @@ fn stroke_shift(salt: u64, q: Point, dir: Vec2, len: f64, width: f64) -> f64 { } /// Smooth noise in [-1, 1) streaked along `dir`: blobs `along` long and `across` wide. -fn streak(salt: u64, q: Point, dir: Vec2, along: f64, across: f64) -> f64 { +pub(super) fn streak(salt: u64, q: Point, dir: Vec2, along: f64, across: f64) -> f64 { let (u, v) = frame(q, dir); 2.0 * value_noise(salt, u / along.max(1e-3), v / across.max(1e-3)) - 1.0 } /// The straight colour and coverage of premultiplied `pm` (0..1). -fn unpremultiply(pm: [f32; 4]) -> ([f32; 3], f32) { +pub(super) fn unpremultiply(pm: [f32; 4]) -> ([f32; 3], f32) { let a = pm[3].clamp(0.0, 1.0); if a > 1e-6 { ([pm[0], pm[1], pm[2]].map(|v| (v / a).clamp(0.0, 1.0)), a) } else { ([0.0; 3], 0.0) } } /// `a` + (`b` − `a`) × `t`, channel by channel. -fn mix(a: [f32; N], b: [f32; N], t: f32) -> [f32; N] { +pub(super) fn mix(a: [f32; N], b: [f32; N], t: f32) -> [f32; N] { std::array::from_fn(|k| a[k] + (b[k] - a[k]) * t) } /// A smooth step from 0 at `t` ≤ 0 to 1 at `t` ≥ 1. -fn ramp(t: f64) -> f64 { +pub(super) fn ramp(t: f64) -> f64 { let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; t * t * (3.0 - 2.0 * t) } /// Pixel `p` (premultiplied 0..255) as premultiplied 0..1. -fn unit(p: [u8; 4]) -> [f32; 4] { +pub(super) fn unit(p: [u8; 4]) -> [f32; 4] { p.map(|v| f32::from(v) / 255.0) } /// The object's edges after softening it by `sigma` (document units): about 1 across a step from /// black to white or from clear to opaque, the same at any resolution. Empty when the sizes don't /// match. -fn edges(px: &[[u8; 4]], w: usize, h: usize, place: &Place, sigma: f64) -> Vec { +pub(super) fn edges(px: &[[u8; 4]], w: usize, h: usize, place: &Place, sigma: f64) -> Vec { let mut tone: Vec = px.iter().map(|p| luma(straight(*p)) * f32::from(p[3]) / 255.0).collect(); let mut cover: Vec = px.iter().map(|p| f32::from(p[3]) / 255.0).collect(); let s = sigma / place.px; @@ -516,3 +516,40 @@ pub(super) fn sumi_e(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, *p = premultiply(out, f32::from(p[3]) / 255.0); }); } + +const SALT_GRAPHIC: u64 = 200; + +/// Graphic Pen: the object redrawn in fine linear ink strokes along `dir`, each `len` (1..15) +/// points long on white paper; `balance` (0..100) sets the tone threshold (higher draws more +/// black ink). +pub(super) fn graphic_pen(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, len: f64, balance: f64, dir: StrokeDirection) { + let Some(place) = Place::new(space, w, h) else { return }; + let len = if len.is_finite() { len.clamp(1.0, 15.0) } else { 1.0 }; + let smear = Smear::new(px, w, h, &place, len); + let tones = Tones::new(px, w, h, TONE_SOFTNESS / place.px); + let threshold = 1.0 - balance.clamp(0.0, 100.0) / 100.0; + let row = (0.2 * len).max(0.75); + let along = dir.along(); + place.each(px, |x, y, p| { + let a = f32::from(p[3]) / 255.0; + if a <= 0.0 { + return; + } + let q = place.at(x, y); + let (c, stroke_a) = unpremultiply(smear.stroke(SALT_GRAPHIC, q, along, row)); + let dark = (1.0 - tones.get(x, y)).max(f64::from(1.0 - luma(c)) * f64::from(stroke_a)); + if dark <= threshold { + *p = premultiply([1.0, 1.0, 1.0], a); + return; + } + let weight = ramp((dark - threshold) / (1.0 - threshold).max(1e-3)); + let u = frame(q, along).0; + let on_stroke = { + let t = (u / len).rem_euclid(1.0); + if t < 0.65 { 1.0 } else { 0.0 } + }; + let grain = 0.08 * streak(SALT_GRAPHIC + 1, q, along, 0.35 * len, 0.5); + let ink = (weight * on_stroke + grain).clamp(0.0, 1.0); + *p = premultiply([(1.0 - ink) as f32; 3], a); + }); +} diff --git a/crates/effects/src/pixel/mod.rs b/crates/effects/src/pixel/mod.rs index ee25c9ca60..051278eb11 100644 --- a/crates/effects/src/pixel/mod.rs +++ b/crates/effects/src/pixel/mod.rs @@ -1,7 +1,9 @@ -//! Photoshop-style raster effects (Effect › Artistic › Cutout, Film Grain, Neon Glow and Poster Edges, Blur › Radial Blur and Smart Blur, Brush Strokes › -//! Accented Edges, Angled Strokes, Crosshatch, Dark Strokes, Ink Outlines, Spatter, Sprayed Strokes -//! and Sumi-e, Distort › Diffuse Glow, Glass and Ocean Ripple, Pixelate › Color Halftone, -//! Crystallize, Mezzotint and Pointillize, Sharpen › Unsharp Mask, Sketch › Halftone Pattern, Stylize › +//! Photoshop-style raster effects (Effect › Artistic › Cutout, Film Grain, Neon Glow, Plastic Wrap and +//! Poster Edges, Smudge Stick, Sponge and Watercolor, Blur › Radial Blur and Smart Blur, Brush Strokes › Accented Edges, Angled Strokes, +//! Crosshatch, Dark Strokes, Ink Outlines, Spatter, Sprayed Strokes and Sumi-e, Distort › Diffuse +//! Glow, Glass and Ocean Ripple, Pixelate › Color Halftone, Crystallize, Mezzotint and Pointillize, +//! Sharpen › Unsharp Mask, Sketch › Chalk & Charcoal, Graphic Pen, Halftone Pattern, Note Paper, Plaster and +//! Reticulation, Stylize › //! Glowing Edges, Texture //! › Craquelure, Grain, Mosaic Tiles, Patchwork, Stained Glass and Texturizer, and Video › //! De-Interlace and NTSC Colors): filters over premultiplied RGBA8 pixels. @@ -19,9 +21,11 @@ mod brushstrokes; mod distort; mod edges; mod loaded; +mod paint; mod pixelate; mod sharpen; mod sketch; +mod sketch_ink; mod texture; mod video; @@ -39,11 +43,15 @@ pub use sketch::{HALFTONE_TYPES, HalftonePattern}; pub use texture::{GRAIN_TYPES, Grain, LIGHT_DIRECTIONS, Light, TEXTURES, Texture}; /// The Photoshop-style effect ids (all raster effects, see [`crate::is_raster`]). -pub const PIXEL_EFFECTS: [&str; 32] = [ +pub const PIXEL_EFFECTS: [&str; 46] = [ "artistic.cutout", "artistic.filmGrain", "artistic.neonGlow", + "artistic.plasticWrap", "artistic.posterEdges", + "artistic.smudgeStick", + "artistic.sponge", + "artistic.watercolor", "blur.radial", "blur.smart", "brushStrokes.accentedEdges", @@ -62,7 +70,17 @@ pub const PIXEL_EFFECTS: [&str; 32] = [ "pixelate.mezzotint", "pixelate.pointillize", "sharpen.unsharpMask", + "sketch.basRelief", + "sketch.chalkCharcoal", + "sketch.charcoal", + "sketch.chrome", + "sketch.graphicPen", "sketch.halftonePattern", + "sketch.notePaper", + "sketch.photocopy", + "sketch.plaster", + "sketch.reticulation", + "sketch.stamp", "stylize.glowingEdges", "texture.craquelure", "texture.grain", @@ -84,10 +102,23 @@ pub enum PixelFx { /// Artistic › Film Grain: monochrome grain in shadows and midtones, a wider bright /// highlight area (0..20), and tonal intensity (0..10), preserving coverage. FilmGrain { grain: f64, highlight: f64, intensity: f64 }, + /// Artistic › Smudge Stick: the dark areas smudged along short diagonal strokes `stroke` + /// (0..10) long, the light areas (widened by `highlight`, 0..20) smudged longer and lightened + /// by up to `intensity` (0..10). + SmudgeStick { stroke: f64, highlight: f64, intensity: f64 }, + /// Artistic › Sponge: soft blobs of lighter and darker colour about `brush` (0..10) large, + /// contrasting as `definition` (0..25) says, their edges as soft as `smoothness` (1..15). + Sponge { brush: f64, definition: f64, smoothness: f64 }, + /// Artistic › Watercolor: detail simplified by a brush of `detail` (1..14), edges saturated, + /// shadows deepened by `shadow` (0..10), `texture` (1..3) grains of paper showing. + Watercolor { detail: f64, shadow: f64, texture: u32 }, /// Artistic › Neon Glow: dimmed greys lit by `colour` (straight RGB, 0..1) glowing from the /// light areas (`size` above 0) or the dark ones (below 0), spread by |`size`| (-24..24), as /// strong as `brightness` (0..50). NeonGlow { size: f64, brightness: f64, colour: [f32; 3] }, + /// Artistic › Plastic Wrap: specular highlights as strong as `highlight` (0..20) on a relief + /// wrinkled by `detail` (0..15) and softened by `smoothness` (1..15). + PlasticWrap { highlight: f64, detail: f64, smoothness: f64 }, /// Artistic › Poster Edges: colours posterized to `posterization` + 2 levels (0..6) with black /// lines on the edges, as thick as `thickness` (0..10) and as dark as `intensity` (0..10). PosterEdges { thickness: f64, intensity: f64, posterization: f64 }, @@ -139,9 +170,38 @@ pub enum PixelFx { /// Sharpen › Unsharp Mask: colours pushed away from a Gaussian blur of σ = `radius` by `amount` /// (1 = 100 %), where they differ from it by at least `threshold` levels. UnsharpMask { amount: f64, radius: f64, threshold: f64 }, + /// Sketch › Chalk & Charcoal: chalk highlights in light areas and charcoal in dark ones; + /// `chalk` and `charcoal` (0..20) set how much, `pressure` (0..5) the stroke weight. + ChalkCharcoal { chalk: f64, charcoal: f64, pressure: f64 }, + /// Sketch › Chrome: polished chrome relief with `detail` (0..10) and `smoothness` (0..10). + Chrome { detail: f64, smoothness: f64 }, + /// Sketch › Graphic Pen: fine linear ink strokes along `dir`, each `length` (1..15) points long + /// on white paper; `balance` (0..100) sets how much of the tone range becomes black ink. + GraphicPen { length: f64, balance: f64, direction: StrokeDirection }, /// Sketch › Halftone Pattern: black ink on white paper through a `kind` screen of cells `size` /// (1..12) apart, its edges as hard as `contrast` (0..50) says. HalftonePattern { size: f64, contrast: f64, kind: HalftonePattern }, + /// Sketch › Note Paper: embossed tones on fibrous paper (`balance`, `graininess`, `relief`). + NotePaper { balance: f64, graininess: f64, relief: f64 }, + /// Sketch › Bas Relief: low relief lit from `light`, keeping the finer features as `detail` + /// (1..15) says and rounded by `smoothness` (1..15). + BasRelief { detail: f64, smoothness: f64, light: Light }, + /// Sketch › Charcoal: bold edges `thickness` (1..7) wide, as fine as `detail` (0..5) says, and + /// diagonal strokes over the midtones; `balance` (0..100) sets how far into the lights it reaches. + Charcoal { thickness: f64, detail: f64, balance: f64 }, + /// Sketch › Photocopy: black only where a pixel is darker than its surroundings, as fine as + /// `detail` (1..24) says, and as readily as `darkness` (1..50) says. + Photocopy { detail: f64, darkness: f64 }, + /// Sketch › Stamp: solid black and white, printing black as much as `balance` (0..50) says, + /// its shapes rounded by `smoothness` (1..50). + Stamp { balance: f64, smoothness: f64 }, + /// Sketch › Plaster: relief plaster lit from `light`; dark areas raised, light recessed; + /// `imageBalance` (1..50) shifts more of the image lower at higher values; `smoothness` (1..15) + /// softens the relief. + Plaster { image_balance: f64, smoothness: f64, light: Light }, + /// Sketch › Reticulation: black ink on white paper through a high-contrast film-grain screen; + /// `density` (0..50), `foreground` and `background` (0..50) pull tones before the grain. + Reticulation { density: f64, foreground: f64, background: f64 }, /// Stylize › Glowing Edges: bright coloured Sobel outlines on black. GlowingEdges { width: f64, brightness: f64, smoothness: f64 }, /// Pixelate › Color Halftone: each colour channel screened at its angle (`angles`° of channels @@ -242,6 +302,26 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option { highlight: num(p, "highlightArea", 0.0).clamp(0.0, 20.0), intensity: num(p, "intensity", 10.0).clamp(0.0, 10.0), }, + "artistic.smudgeStick" => PixelFx::SmudgeStick { + stroke: num(p, "strokeLength", 2.0).clamp(0.0, 10.0), + highlight: num(p, "highlightArea", 12.0).clamp(0.0, 20.0), + intensity: num(p, "intensity", 10.0).clamp(0.0, 10.0), + }, + "artistic.sponge" => PixelFx::Sponge { + brush: num(p, "brushSize", 2.0).clamp(0.0, 10.0), + definition: num(p, "definition", 12.0).clamp(0.0, 25.0), + smoothness: num(p, "smoothness", 5.0).clamp(1.0, 15.0), + }, + "artistic.watercolor" => PixelFx::Watercolor { + detail: num(p, "brushDetail", 9.0).clamp(1.0, 14.0), + shadow: num(p, "shadowIntensity", 1.0).clamp(0.0, 10.0), + texture: num(p, "texture", 1.0).clamp(1.0, 3.0).round() as u32, + }, + "artistic.plasticWrap" => PixelFx::PlasticWrap { + highlight: num(p, "highlightStrength", 20.0).clamp(0.0, 20.0), + detail: num(p, "detail", 12.0).clamp(0.0, 15.0), + smoothness: num(p, "smoothness", 15.0).clamp(1.0, 15.0), + }, "blur.radial" => PixelFx::RadialBlur { amount: num(p, "amount", 10.0).clamp(1.0, 100.0), zoom: text(p, "method", "spin").eq_ignore_ascii_case("zoom"), @@ -311,11 +391,53 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option { radius: num(p, "radius", 1.0).clamp(0.1, 250.0), threshold: num(p, "threshold", 0.0).clamp(0.0, 255.0), }, + "sketch.chalkCharcoal" => PixelFx::ChalkCharcoal { + chalk: num(p, "chalkArea", 6.0).clamp(0.0, 20.0), + charcoal: num(p, "charcoalArea", 6.0).clamp(0.0, 20.0), + pressure: num(p, "strokePressure", 2.0).clamp(0.0, 5.0), + }, + "sketch.chrome" => PixelFx::Chrome { detail: num(p, "detail", 4.0).clamp(0.0, 10.0), smoothness: num(p, "smoothness", 4.0).clamp(0.0, 10.0) }, + "sketch.graphicPen" => PixelFx::GraphicPen { + length: num(p, "strokeLength", 5.0).clamp(1.0, 15.0), + balance: num(p, "lightDarkBalance", 50.0).clamp(0.0, 100.0), + direction: StrokeDirection::parse(text(p, "strokeDirection", "rightDiagonal")), + }, "sketch.halftonePattern" => PixelFx::HalftonePattern { size: num(p, "size", 1.0).clamp(1.0, 12.0), contrast: num(p, "contrast", 5.0).clamp(0.0, 50.0), kind: HalftonePattern::parse(text(p, "patternType", "dot")), }, + "sketch.notePaper" => PixelFx::NotePaper { + balance: num(p, "imageBalance", 25.0).clamp(0.0, 50.0), + graininess: num(p, "graininess", 0.0).clamp(0.0, 10.0), + relief: num(p, "relief", 4.0).clamp(0.0, 50.0), + }, + "sketch.basRelief" => PixelFx::BasRelief { + detail: num(p, "detail", 13.0).clamp(1.0, 15.0), + smoothness: num(p, "smoothness", 3.0).clamp(1.0, 15.0), + light: Light::parse(text(p, "lightDirection", "bottom")), + }, + "sketch.charcoal" => PixelFx::Charcoal { + thickness: num(p, "thickness", 1.0).clamp(1.0, 7.0), + detail: num(p, "detail", 1.0).clamp(0.0, 5.0), + balance: num(p, "lightDarkBalance", 50.0).clamp(0.0, 100.0), + }, + "sketch.photocopy" => { + PixelFx::Photocopy { detail: num(p, "detail", 7.0).clamp(1.0, 24.0), darkness: num(p, "darkness", 25.0).clamp(1.0, 50.0) } + } + "sketch.stamp" => { + PixelFx::Stamp { balance: num(p, "lightDarkBalance", 25.0).clamp(0.0, 50.0), smoothness: num(p, "smoothness", 5.0).clamp(1.0, 50.0) } + } + "sketch.plaster" => PixelFx::Plaster { + image_balance: num(p, "imageBalance", 20.0).clamp(1.0, 50.0), + smoothness: num(p, "smoothness", 8.0).clamp(1.0, 15.0), + light: Light::parse(text(p, "lightDirection", "top")), + }, + "sketch.reticulation" => PixelFx::Reticulation { + density: num(p, "density", 12.0).clamp(0.0, 50.0), + foreground: num(p, "foregroundLevel", 6.0).clamp(0.0, 50.0), + background: num(p, "backgroundLevel", 6.0).clamp(0.0, 50.0), + }, "stylize.glowingEdges" => PixelFx::GlowingEdges { width: num(p, "edgeWidth", 2.0).clamp(1.0, 14.0), brightness: num(p, "edgeBrightness", 6.0).clamp(0.0, 20.0), @@ -381,7 +503,9 @@ impl PixelFx { PixelFx::SmartBlur { radius, .. } => radius, PixelFx::AccentedEdges { .. } => 0.0, // Strokes reach out of the object as far as they reach into it. - PixelFx::AngledStrokes { length, .. } | PixelFx::InkOutlines { length, .. } => brushstrokes::stroke_reach(length), + PixelFx::AngledStrokes { length, .. } | PixelFx::GraphicPen { length, .. } | PixelFx::InkOutlines { length, .. } => { + brushstrokes::stroke_reach(length) + } PixelFx::Crosshatch { length, .. } => brushstrokes::stroke_reach(length) + brushstrokes::rough(length), PixelFx::DarkStrokes { .. } => brushstrokes::stroke_reach(brushstrokes::LIGHT_LENGTH), PixelFx::Spatter { radius, .. } => brushstrokes::spatter_shift(radius), @@ -392,11 +516,21 @@ impl PixelFx { // Content shifted outwards reaches past the bounds by as much as the shift. PixelFx::Glass { distortion, .. } => distort::glass_shift(distortion), PixelFx::OceanRipple { size, magnitude } => distort::ripple_shift(size, magnitude), - PixelFx::UnsharpMask { .. } | PixelFx::HalftonePattern { .. } => 0.0, + PixelFx::UnsharpMask { .. } + | PixelFx::ChalkCharcoal { .. } + | PixelFx::Chrome { .. } + | PixelFx::HalftonePattern { .. } + | PixelFx::NotePaper { .. } + | PixelFx::Plaster { .. } + | PixelFx::Reticulation { .. } => 0.0, + PixelFx::BasRelief { .. } | PixelFx::Charcoal { .. } | PixelFx::Photocopy { .. } | PixelFx::Stamp { .. } => 0.0, PixelFx::GlowingEdges { width, smoothness, .. } => width.max(smoothness * 3.0), + // These three keep the object's coverage. + PixelFx::SmudgeStick { .. } | PixelFx::Sponge { .. } | PixelFx::Watercolor { .. } => 0.0, PixelFx::FilmGrain { .. } | PixelFx::Cutout { .. } | PixelFx::NeonGlow { .. } + | PixelFx::PlasticWrap { .. } | PixelFx::PosterEdges { .. } | PixelFx::ColorHalftone { .. } | PixelFx::Mezzotint { .. } @@ -420,9 +554,14 @@ impl PixelFx { PixelFx::RadialBlur { .. } => None, PixelFx::SmartBlur { radius, mode: SmartBlurMode::Normal, .. } => Some(radius), PixelFx::SmartBlur { radius, samples, .. } => Some(blur::edge_reach(radius, samples)), + PixelFx::SmudgeStick { stroke, .. } => Some(paint::smudge_reach(stroke)), + PixelFx::Sponge { brush, smoothness, .. } => Some(paint::sponge_reach(brush, smoothness)), + PixelFx::Watercolor { detail, .. } => Some(paint::watercolor_reach(detail)), PixelFx::AccentedEdges { width, smoothness, .. } => Some(brushstrokes::accent_reach(width, smoothness)), // The strokes, and the softened tones that choose them. - PixelFx::AngledStrokes { length, .. } => Some(brushstrokes::stroke_reach(length).max(brushstrokes::TONE_REACH)), + PixelFx::AngledStrokes { length, .. } | PixelFx::GraphicPen { length, .. } => { + Some(brushstrokes::stroke_reach(length).max(brushstrokes::TONE_REACH)) + } PixelFx::Crosshatch { length, .. } => { Some((brushstrokes::stroke_reach(length) + brushstrokes::rough(length)).max(brushstrokes::TONE_REACH)) } @@ -435,15 +574,27 @@ impl PixelFx { PixelFx::Glass { distortion, .. } => Some(distort::glass_shift(distortion)), PixelFx::OceanRipple { size, magnitude } => Some(distort::ripple_shift(size, magnitude)), PixelFx::UnsharpMask { radius, .. } => Some(3.0 * radius), + PixelFx::BasRelief { detail, smoothness, .. } => Some(sketch_ink::relief_reach(detail, smoothness)), + PixelFx::Charcoal { thickness, detail, .. } => Some(sketch_ink::charcoal_reach(thickness, detail)), + PixelFx::Photocopy { detail, .. } => Some(sketch_ink::copy_reach(detail)), + PixelFx::Stamp { smoothness, .. } => Some(sketch_ink::stamp_reach(smoothness)), PixelFx::GlowingEdges { width, smoothness, .. } => Some(width.max(smoothness * 3.0)), // The cells around the pixel's, and the cells around theirs. PixelFx::ColorHalftone { max_radius, .. } => Some(3.0 * std::f64::consts::SQRT_2 * max_radius), PixelFx::Crystallize { cell } => Some(1.5 * cell), - PixelFx::FilmGrain { .. } | PixelFx::Mezzotint { .. } | PixelFx::HalftonePattern { .. } => Some(0.0), + PixelFx::ChalkCharcoal { .. } => Some(sketch::CHALK_CHARCOAL_REACH), + PixelFx::Chrome { smoothness, .. } => Some(sketch::chrome_reach(smoothness)), + PixelFx::FilmGrain { .. } + | PixelFx::Mezzotint { .. } + | PixelFx::HalftonePattern { .. } + | PixelFx::NotePaper { .. } + | PixelFx::Reticulation { .. } => Some(0.0), + PixelFx::Plaster { smoothness, .. } => Some(sketch::plaster_reach(smoothness)), // Cutout's palette comes from the whole object. PixelFx::Cutout { .. } => None, // The softened tones around the pixel. PixelFx::NeonGlow { size, .. } => Some(3.0 * artistic::glow_spread(size)), + PixelFx::PlasticWrap { smoothness, .. } => Some(artistic::plastic_reach(smoothness)), // The edges' lines, spread round them. PixelFx::PosterEdges { thickness, .. } => Some(3.0 * (0.3 + 0.25 * thickness) + 1.0), // The dots' points, and the softened colour around them. @@ -468,6 +619,10 @@ impl PixelFx { match *self { PixelFx::Cutout { levels, simplicity, fidelity } => artistic::cutout(px, w, h, space, levels, simplicity, fidelity), PixelFx::FilmGrain { grain, highlight, intensity } => artistic::film_grain(px, w, h, space, grain, highlight, intensity), + PixelFx::SmudgeStick { stroke, highlight, intensity } => paint::smudge_stick(px, w, h, space, stroke, highlight, intensity), + PixelFx::Sponge { brush, definition, smoothness } => paint::sponge(px, w, h, space, brush, definition, smoothness), + PixelFx::Watercolor { detail, shadow, texture } => paint::watercolor(px, w, h, space, detail, shadow, texture), + PixelFx::PlasticWrap { highlight, detail, smoothness } => artistic::plastic_wrap(px, w, h, space, highlight, detail, smoothness), PixelFx::NeonGlow { size, brightness, colour } => artistic::neon_glow(px, w, h, space, size, brightness, colour), PixelFx::PosterEdges { thickness, intensity, posterization } => { artistic::poster_edges(px, w, h, space, thickness, intensity, posterization) @@ -493,7 +648,17 @@ impl PixelFx { } PixelFx::OceanRipple { size, magnitude } => distort::ocean_ripple(px, w, h, space, size, magnitude), PixelFx::UnsharpMask { amount, radius, threshold } => sharpen::unsharp(px, w, h, amount, to_px(radius), threshold), + PixelFx::ChalkCharcoal { chalk, charcoal, pressure } => sketch::chalk_charcoal(px, w, h, space, chalk, charcoal, pressure), + PixelFx::Chrome { detail, smoothness } => sketch::chrome(px, w, h, space, detail, smoothness), + PixelFx::GraphicPen { length, balance, direction } => brushstrokes::graphic_pen(px, w, h, space, length, balance, direction), PixelFx::HalftonePattern { size, contrast, kind } => sketch::halftone_pattern(px, w, h, space, size, contrast, kind), + PixelFx::NotePaper { balance, graininess, relief } => sketch::note_paper(px, w, h, space, balance, graininess, relief), + PixelFx::BasRelief { detail, smoothness, light } => sketch_ink::bas_relief(px, w, h, space, detail, smoothness, light), + PixelFx::Charcoal { thickness, detail, balance } => sketch_ink::charcoal(px, w, h, space, thickness, detail, balance), + PixelFx::Photocopy { detail, darkness } => sketch_ink::photocopy(px, w, h, space, detail, darkness), + PixelFx::Stamp { balance, smoothness } => sketch_ink::stamp(px, w, h, space, balance, smoothness), + PixelFx::Plaster { image_balance, smoothness, light } => sketch::plaster(px, w, h, space, image_balance, smoothness, light), + PixelFx::Reticulation { density, foreground, background } => sketch::reticulation(px, w, h, space, density, foreground, background), PixelFx::GlowingEdges { width, brightness, smoothness } => edges::glow(px, w, h, to_px(width), brightness, to_px(smoothness)), PixelFx::ColorHalftone { max_radius, angles } => pixelate::color_halftone(px, w, h, space, max_radius, angles), PixelFx::Crystallize { cell } => pixelate::crystallize(px, w, h, space, cell), @@ -742,3 +907,7 @@ pub fn gaussian_rgba(data: &mut [u8], w: usize, h: usize, sigma: f64) { #[cfg(test)] mod tests; +#[cfg(test)] +mod tests_paint; +#[cfg(test)] +mod tests_sketch; diff --git a/crates/effects/src/pixel/paint.rs b/crates/effects/src/pixel/paint.rs new file mode 100644 index 0000000000..a078fb9f98 --- /dev/null +++ b/crates/effects/src/pixel/paint.rs @@ -0,0 +1,173 @@ +//! Effect › Artistic › Smudge Stick, Sponge and Watercolor. Original filters built from public +//! behaviour documentation: and +//! (Smudge Stick smudges the +//! dark areas with short diagonal strokes and brightens the light ones, Sponge paints highly +//! textured areas of contrasting colour, Watercolor simplifies detail with a medium brush loaded +//! with water and saturates the colour where tones change at edges). Visual approximations, not +//! reproductions of a proprietary algorithm; the ranges and defaults are chosen for VectorCraft. +//! +//! All three keep the object's coverage, so they paint nothing outside it. Their patterns lie in +//! document space around the object's centre, as the Brush Strokes' and Texture filters' do. + +use super::blur; +use super::brushstrokes::{MARGIN, RIGHT, Smear, TONE_SOFTNESS, edges, mix, ramp, streak, stroke_reach, unpremultiply}; +use super::pixelate::Place; +use super::texture::{Tones, luma, premultiply, smooth_noise, straight}; +use super::{PixelSpace, Px16, gaussian, to16}; + +const SALT_SMUDGE: u64 = 320; +const SALT_SPONGE: u64 = 328; +const SALT_WATER: u64 = 336; + +/// The length (points) of Smudge Stick's short strokes for Stroke Length `stroke` (0..10); the +/// light areas are smudged with strokes twice as long. +fn smudge_length(stroke: f64) -> f64 { + 1.0 + 1.5 * stroke.clamp(0.0, 10.0) +} + +/// How far (document units) Smudge Stick reaches for Stroke Length `stroke`: its strokes and the +/// softened tones that choose them. +pub(super) fn smudge_reach(stroke: f64) -> f64 { + stroke_reach(2.0 * smudge_length(stroke)).max(3.0 * TONE_SOFTNESS + MARGIN) +} + +/// The σ (points) Sponge softens the object by, for Brush Size `brush` (0..10) and Smoothness +/// `smoothness` (1..15). +fn sponge_softness(brush: f64, smoothness: f64) -> f64 { + (0.15 + 0.04 * smoothness.clamp(1.0, 15.0)) * sponge_pore(brush) +} + +/// The size (points) of Sponge's pores for Brush Size `brush` (0..10). +fn sponge_pore(brush: f64) -> f64 { + 2.0 + 1.5 * brush.clamp(0.0, 10.0) +} + +/// How far (document units) Sponge reaches: the softened colours around a pixel. +pub(super) fn sponge_reach(brush: f64, smoothness: f64) -> f64 { + 3.0 * sponge_softness(brush, smoothness) + MARGIN +} + +/// The radius (points) of the brush that simplifies detail for Brush Detail `detail` (1..14): the +/// less detail, the wider the brush. +fn water_brush(detail: f64) -> f64 { + 0.5 * (15.0 - detail.clamp(1.0, 14.0)) +} + +/// The σ (points) of the softening that finds Watercolor's edges. +const WATER_EDGE: f64 = 0.6; + +/// How far (document units) Watercolor reaches for Brush Detail `detail`. +pub(super) fn watercolor_reach(detail: f64) -> f64 { + water_brush(detail) + 3.0 * WATER_EDGE + MARGIN +} + +/// Smudge Stick: the dark areas smudged along short diagonal strokes `stroke` (0..10) long, the +/// light areas smudged with longer strokes and lightened towards white as strongly as `intensity` +/// (0..10) says, so they lose their detail; `highlight` (0..20) widens the area counted as light. +pub(super) fn smudge_stick(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, stroke: f64, highlight: f64, intensity: f64) { + if ![stroke, highlight, intensity].iter().all(|v| v.is_finite()) { + return; + } + let Some(place) = Place::new(space, w, h) else { return }; + let len = smudge_length(stroke); + let (short, long) = (Smear::new(px, w, h, &place, len), Smear::new(px, w, h, &place, 2.0 * len)); + let tones = Tones::new(px, w, h, TONE_SOFTNESS / place.px); + // Tones above the threshold count as light; a wider highlight area lowers it. + let threshold = 0.9 - 0.5 * (highlight / 20.0).clamp(0.0, 1.0); + let lift = (0.7 * intensity / 10.0).clamp(0.0, 0.7) as f32; + let row = (0.25 * len).max(1.0); + place.each(px, |x, y, p| { + if p[3] == 0 { + return; + } + let q = place.at(x, y); + let own = straight(*p); + let paint = |smear: &Smear, salt: u64| { + let (c, a) = unpremultiply(smear.stroke(salt, q, RIGHT, row)); + if a > 0.0 { c } else { own } + }; + // Bristle marks along the dark strokes. + let bristle = (1.0 + 0.08 * streak(SALT_SMUDGE + 2, q, RIGHT, len, 0.5)) as f32; + let dark = paint(&short, SALT_SMUDGE).map(|v| v * bristle); + let light = paint(&long, SALT_SMUDGE + 1); + let t = ramp((tones.get(x, y) - threshold) / 0.2 + 0.5) as f32; + let bright = light.map(|v| v + (1.0 - v) * lift); + *p = premultiply(mix(dark, bright, t), f32::from(p[3]) / 255.0); + }); +} + +/// Sponge: the object as if dabbed with a sponge, soft blobs of lighter and darker colour about +/// `brush` (0..10) large; `definition` (0..25) sets how strongly they contrast and `smoothness` +/// (1..15) how soft their edges are. +pub(super) fn sponge(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, brush: f64, definition: f64, smoothness: f64) { + if ![brush, definition, smoothness].iter().all(|v| v.is_finite()) { + return; + } + let Some(place) = Place::new(space, w, h) else { return }; + let mut soft: Vec = to16(px); + gaussian(&mut soft, w, sponge_softness(brush, smoothness) / place.px); + let pore = sponge_pore(brush); + let edge = 0.12 + 0.03 * smoothness.clamp(1.0, 15.0); + let amount = (definition / 25.0).clamp(0.0, 1.0); + let gain = 1.0 + 1.2 * amount; + place.each(px, |x, y, p| { + if p[3] == 0 { + return; + } + let alpha = f32::from(p[3]) / 255.0; + let own = straight(*p); + let (c, a) = unpremultiply(soft.get(y * w + x).map_or([0.0; 4], |s| s.map(|v| f32::from(v) / 65535.0))); + let c = if a > 0.0 { c } else { own }; + let q = place.at(x, y); + let n = 0.65 * smooth_noise(SALT_SPONGE, q, pore) + 0.35 * smooth_noise(SALT_SPONGE + 1, q, 0.45 * pore); + // -1 inside a dark pore, 1 on a light bridge between pores. + let blob = 2.0 * ramp(0.5 + n / (2.0 * edge)) - 1.0; + let l = f64::from(luma(c)); + let target = (0.5 + (l + 0.55 * amount * blob - 0.5) * gain).clamp(0.0, 1.0); + // Darker towards black, lighter towards white: the hue stays. + let out = if target <= l { + let k = if l > 1e-3 { (target / l) as f32 } else { 0.0 }; + c.map(|v| v * k) + } else { + let k = ((target - l) / (1.0 - l).max(1e-3)).clamp(0.0, 1.0) as f32; + c.map(|v| v + (1.0 - v) * k) + }; + *p = premultiply(out, alpha); + }); +} + +/// Watercolor: the object's detail simplified by a brush whose size `detail` (1..14) sets (the +/// larger, the more detail stays), the colour saturated and its pigment pooled where tones change +/// at edges, the shadows deepened as strongly as `shadow` (0..10) says, and `texture` (1..3) +/// grains of paper showing through. +pub(super) fn watercolor(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, detail: f64, shadow: f64, texture: u32) { + if ![detail, shadow].iter().all(|v| v.is_finite()) { + return; + } + let Some(place) = Place::new(space, w, h) else { return }; + let coverage: Vec = px.iter().map(|p| p[3]).collect(); + // Simplify: average within areas of similar colour, keeping the bolder edges; a coarser brush + // (less detail) also merges colours further apart. + blur::smart(px, w, h, water_brush(detail) / place.px, 20.0 + 6.0 * (14.0 - detail.clamp(1.0, 14.0)), 7); + let found = edges(px, w, h, &place, WATER_EDGE); + let shadow = shadow.clamp(0.0, 10.0); + let paper = 0.02 * f64::from(texture.clamp(1, 3)); + let grain = 1.0 + 0.5 * f64::from(texture.clamp(1, 3)); + place.each(px, |x, y, p| { + let alpha = coverage.get(y * w + x).copied().unwrap_or(0); + if alpha == 0 { + *p = [0; 4]; + return; + } + let c = straight(*p); + let e = (2.0 * f64::from(found.get(y * w + x).copied().unwrap_or(0.0))).clamp(0.0, 1.0) as f32; + let l = luma(c); + // Saturated colour and darker pigment where the tones change. + let c = c.map(|v| (l + (v - l) * (1.0 + 0.9 * e)) * (1.0 - 0.12 * e)); + let deep = ((1.0 - l / 0.5).clamp(0.0, 1.0) * 0.07 * shadow as f32).min(0.8); + let q = place.at(x, y); + let n = 0.6 * smooth_noise(SALT_WATER, q, grain) + 0.4 * smooth_noise(SALT_WATER + 1, q, 0.5 * grain); + let n = (paper * n) as f32; + *p = premultiply(c.map(|v| v * (1.0 - deep) + n), f32::from(alpha) / 255.0); + }); +} diff --git a/crates/effects/src/pixel/sketch.rs b/crates/effects/src/pixel/sketch.rs index 7f9f7cd040..9f04b12770 100644 --- a/crates/effects/src/pixel/sketch.rs +++ b/crates/effects/src/pixel/sketch.rs @@ -1,12 +1,42 @@ -//! Effect › Sketch › Halftone Pattern. Original filter built from public behaviour documentation: +//! Effect › Sketch (Chalk & Charcoal, Chrome, Halftone Pattern, Note Paper, Plaster and Reticulation; Graphic Pen lives in +//! [`super::brushstrokes`]). Original filters built from public behaviour documentation: //! (Sketch effects redraw in -//! black and white; Halftone Pattern simulates a halftone screen while keeping the range of tones) -//! and (only Size depends on the raster -//! resolution). A visual approximation, not a reproduction of a proprietary algorithm. +//! black and white) and the public Photoshop Elements Artistic filters guide. Visual +//! approximations, not proprietary reproductions. -use super::pixelate::Place; -use super::texture::{luma, premultiply, straight}; -use super::{PixelSpace, pick}; +use std::f64::consts::{FRAC_1_SQRT_2, TAU}; + +use vectorcraft_geom::Vec2; + +use super::edges::sobel; +use super::pixelate::{Place, cell, rand, value_noise}; +use super::texture::{Light, Tones, luma, premultiply, smooth_noise, straight}; +use super::{PixelSpace, blur_plane, pick}; + +const SALT_CHALK: u64 = 216; +const SALT_CHROME: u64 = 0xC40_4D45; +const EDGE_SOFT: f64 = 0.8; +const TONE_SOFT: f64 = 1.0; +/// Light from the top left (document axes, y down), as on polished relief surfaces. +const CHROME_LIGHT: Vec2 = Vec2::new(-FRAC_1_SQRT_2, -FRAC_1_SQRT_2); + +/// How far (document units) Chalk & Charcoal samples softened tones and edges. +pub(super) const CHALK_CHARCOAL_REACH: f64 = 3.0 * TONE_SOFT + 1.0 + 3.0 * EDGE_SOFT; + +fn ramp(t: f64) -> f64 { + t.clamp(0.0, 1.0) +} + +fn tone_edges(px: &[[u8; 4]], w: usize, h: usize, place: &Place, sigma: f64) -> Vec { + let mut tone: Vec = px.iter().map(|p| luma(straight(*p)) * f32::from(p[3]) / 255.0).collect(); + let mut cover: Vec = px.iter().map(|p| f32::from(p[3]) / 255.0).collect(); + let s = sigma / place.px; + blur_plane(&mut tone, w, h, s); + blur_plane(&mut cover, w, h, s); + let norm = (s.max(0.8) * TAU.sqrt() / 8.0) as f32; + let norm = if norm.is_finite() { norm } else { 0.0 }; + sobel(&tone, w, h).iter().zip(sobel(&cover, w, h)).map(|(t, c)| t.max(c) * norm).collect() +} /// Halftone Pattern's screens, in its Pattern Type menu's order: (label, parameter value). pub const HALFTONE_TYPES: [(&str, &str); 3] = [("Circle", "circle"), ("Dot", "dot"), ("Line", "line")]; @@ -69,3 +99,261 @@ pub(super) fn halftone_pattern(px: &mut [[u8; 4]], w: usize, h: usize, space: &P *p = premultiply([(1.0 - ink) as f32; 3], f32::from(p[3]) / 255.0); }); } + +/// Note Paper: the object embossed on fibrous paper. `balance` (0..50) shifts tones toward +/// highlights or shadows around the middle; `graininess` (0..10) adds paper fibre; `relief` +/// (0..50, points) is how strongly the tones stand out in the light. Coverage is kept. +pub(super) fn note_paper(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, balance: f64, graininess: f64, relief: f64) { + if !(balance.is_finite() && graininess.is_finite() && relief.is_finite()) { + return; + } + let Some(place) = Place::new(space, w, h) else { return }; + let height: Vec = px + .iter() + .map(|p| { + if p[3] == 0 { + 0.0 + } else { + let mut l = f64::from(luma(straight(*p))); + l += (balance - 25.0) / 125.0; + l.clamp(0.0, 1.0) as f32 + } + }) + .collect(); + let sample = |x: i32, y: i32| -> f32 { + if x < 0 || y < 0 || x >= w as i32 || y >= h as i32 { + return 0.0; + } + height.get(y as usize * w + x as usize).copied().unwrap_or(0.0) + }; + let emboss = relief / 50.0; + let grain = graininess / 10.0; + let light = (-0.6_f64, -0.6, 0.8); + let ln = (light.0 * light.0 + light.1 * light.1 + light.2 * light.2).sqrt().max(1e-9); + place.each(px, |x, y, p| { + if p[3] == 0 { + return; + } + let xi = x as i32; + let yi = y as i32; + let h0 = height.get(y * w + x).copied().unwrap_or(0.0); + let dx = (sample(xi + 1, yi) - sample(xi - 1, yi)) as f64; + let dy = (sample(xi, yi + 1) - sample(xi, yi - 1)) as f64; + let dz = emboss * 0.12; + let nx = -dx; + let ny = -dy; + let nz = dz; + let nn = (nx * nx + ny * ny + nz * nz).sqrt().max(1e-9); + let shade = ((nx * light.0 + ny * light.1 + nz * light.2) / (nn * ln) * 0.5 + 0.5).clamp(0.0, 1.0); + let tone = (0.35 + 0.65 * f64::from(h0)) * shade; + let q = place.at(x, y); + let fibre = if grain > 0.0 { value_noise(0x4e4f_5450, q.x * 0.35, q.y * 0.35) * grain * 0.18 } else { 0.0 }; + let v = (tone + fibre).clamp(0.0, 1.0) as f32; + *p = premultiply([v; 3], f32::from(p[3]) / 255.0); + }); +} + +/// Chalk & Charcoal: light areas get chalky highlights and dark areas charcoal strokes and grain; +/// `chalk` and `charcoal` (0..20) set how strongly, `pressure` (0..5) the stroke weight. Black +/// chalk and charcoal on white paper, coverage kept. +pub(super) fn chalk_charcoal(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, chalk: f64, charcoal: f64, pressure: f64) { + if !(chalk.is_finite() && charcoal.is_finite() && pressure.is_finite()) { + return; + } + let scale = (pressure.clamp(0.0, 5.0) / 5.0).clamp(0.0, 1.0); + let chalk_amt = (0.05 * chalk.clamp(0.0, 20.0) * scale).clamp(0.0, 1.0); + let charcoal_amt = (0.05 * charcoal.clamp(0.0, 20.0) * scale).clamp(0.0, 1.0); + if chalk_amt <= 0.0 && charcoal_amt <= 0.0 { + return; + } + let Some(place) = Place::new(space, w, h) else { return }; + let tones = Tones::new(px, w, h, TONE_SOFT / place.px); + let edges = tone_edges(px, w, h, &place, EDGE_SOFT); + place.each(px, |x, y, p| { + if p[3] == 0 { + return; + } + let q = place.at(x, y); + let tone = tones.get(x, y); + let dark = (1.0 - tone).clamp(0.0, 1.0); + let light = tone.clamp(0.0, 1.0); + let edge = f64::from(edges.get(y * w + x).copied().unwrap_or(0.0)); + let charcoal_stroke = value_noise(SALT_CHALK + 1, q.x * 1.1, q.y * 0.12); + let charcoal_grain = value_noise(SALT_CHALK, q.x * 0.35, q.y * 0.35); + let charcoal_mask = ramp((dark - 0.3) / 0.22) + * charcoal_amt + * (0.35 + 0.65 * edge) + * (0.45 + 0.55 * ramp(charcoal_stroke * 2.2 - 0.55)) + * (0.6 + 0.4 * charcoal_grain); + let chalk_grain = value_noise(SALT_CHALK + 2, q.x * 0.45 + 7.0, q.y * 0.45); + let chalk_mask = ramp((light - 0.5) / 0.22) * chalk_amt * (0.55 + 0.45 * chalk_grain); + let down = (0.9 * charcoal_mask).clamp(0.0, 1.0) as f32; + let up = (0.8 * chalk_mask).clamp(0.0, 1.0) as f32; + let mut grey = luma(straight(*p)); + grey *= 1.0 - down; + grey += (1.0 - grey) * up; + *p = premultiply([grey, grey, grey], f32::from(p[3]) / 255.0); + }); +} + +/// How far (document units) Chrome reaches for `smoothness` (0..10): 3 σ of the height-field blur +/// plus the Sobel neighbours. +pub(super) fn chrome_reach(smoothness: f64) -> f64 { + let smoothness = smoothness.clamp(0.0, 10.0); + 3.0 * (0.4 + 0.55 * smoothness) + 1.0 +} + +/// Chrome: the object as a polished chrome surface lit from the top left. `detail` (0..10) adds +/// finer relief; `smoothness` (0..10) softens the height field before the highlights and shadows +/// are drawn. Coverage is kept. +pub(super) fn chrome(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, detail: f64, smoothness: f64) { + if w == 0 || h == 0 { + return; + } + let detail = detail.clamp(0.0, 10.0); + let smoothness = smoothness.clamp(0.0, 10.0); + let Some(place) = Place::new(space, w, h) else { return }; + let sigma = (0.4 + smoothness * 0.55) / place.px.max(1e-9); + let cell = (14.0 - detail * 1.2).max(1.5); + let bump = (detail / 10.0) * 0.4; + let strength = 2.5 + detail * 0.35; + let mut height: Vec = Vec::with_capacity(w * h); + let mut alpha: Vec = Vec::with_capacity(w * h); + for y in 0..h { + for x in 0..w { + let p = px[y * w + x]; + let a = f32::from(p[3]) / 255.0; + alpha.push(a); + if a <= 0.0 { + height.push(0.0); + continue; + } + let q = place.at(x, y); + let base = f64::from(luma(straight(p))); + let n = if bump > 0.0 { bump * smooth_noise(SALT_CHROME, q, cell) } else { 0.0 }; + height.push((base + n).clamp(0.0, 1.0) as f32); + } + } + blur_plane(&mut height, w, h, sigma); + blur_plane(&mut alpha, w, h, sigma); + let tone: Vec = height.iter().zip(&alpha).map(|(h, a)| if *a > 1e-4 { f64::from(*h / *a).clamp(0.0, 1.0) } else { 0.0 }).collect(); + let px_unit = place.px.max(1e-9); + place.each(px, |x, y, p| { + if p[3] == 0 { + return; + } + let at = |dx: isize, dy: isize| { + let (xx, yy) = ((x as isize + dx).clamp(0, w as isize - 1) as usize, (y as isize + dy).clamp(0, h as isize - 1) as usize); + tone[yy * w + xx] + }; + let h0 = tone[y * w + x]; + let gx = 0.5 * (at(1, 0) - at(-1, 0)) / px_unit; + let gy = 0.5 * (at(0, 1) - at(0, -1)) / px_unit; + let face = -(gx * CHROME_LIGHT.x + gy * CHROME_LIGHT.y); + let spec = (face * strength + (h0 - 0.5) * 1.5).tanh(); + let grey = (0.5 + 0.5 * spec).clamp(0.0, 1.0); + *p = premultiply([grey as f32; 3], f32::from(p[3]) / 255.0); + }); +} + +/// Colour `c` lit by `s`: darkened towards black below 0, lightened towards white above. +fn lit(c: [f32; 3], s: f64) -> [f32; 3] { + let s = if s.is_finite() { s.clamp(-1.0, 1.0) as f32 } else { 0.0 }; + c.map(|v| if s < 0.0 { v * (1.0 + s) } else { v + (1.0 - v) * s }) +} + +/// How a surface whose height rises along `slope` faces a light from `toward`. +fn facing(slope: Vec2, toward: Vec2) -> f64 { + -slope.dot(toward) +} + +/// The σ (document units) of Plaster's height blur at `smoothness` (1..15). +fn plaster_sigma_pt(smoothness: f64) -> f64 { + let smoothness = smoothness.clamp(1.0, 15.0); + 0.15 + 0.85 * (smoothness - 1.0) / 14.0 +} + +/// How far (document units) Plaster's softened relief reaches at `smoothness` (1..15). +pub(super) fn plaster_reach(smoothness: f64) -> f64 { + if !smoothness.is_finite() { + return 3.0 * plaster_sigma_pt(8.0) + 0.5; + } + 3.0 * plaster_sigma_pt(smoothness) + 0.5 +} + +/// Plaster: the object molded in relief plaster and lit from `light`. Dark areas are raised and +/// light areas recessed; `imageBalance` (1..50) shifts more of the image lower at higher values; +/// `smoothness` (1..15) softens the relief. Coverage is kept. +pub(super) fn plaster(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, image_balance: f64, smoothness: f64, light: Light) { + if !(image_balance.is_finite() && smoothness.is_finite() && space.px.is_finite() && space.px > 0.0) + || w == 0 + || h == 0 + || w.checked_mul(h) != Some(px.len()) + { + return; + } + let image_balance = image_balance.clamp(1.0, 50.0); + let smoothness = smoothness.clamp(1.0, 15.0); + let bias = (image_balance - 1.0) / 49.0; + let mut height: Vec = px + .iter() + .map(|p| { + let a = f32::from(p[3]) / 255.0; + let dark = (1.0 - luma(straight(*p))) * a; + (dark - bias as f32 * 0.65).clamp(0.0, 1.0) + }) + .collect(); + blur_plane(&mut height, w, h, plaster_sigma_pt(smoothness) / space.px); + let Some(place) = Place::new(space, w, h) else { return }; + let step = (0.35f64).max(0.5 * place.px); + let strength = 0.55; + let toward = light.toward(); + let at = |x: usize, y: usize, dx: i32, dy: i32| { + let (xx, yy) = ((x as i32 + dx).clamp(0, w as i32 - 1) as usize, (y as i32 + dy).clamp(0, h as i32 - 1) as usize); + height[yy * w + xx] + }; + place.each(px, |x, y, p| { + if p[3] == 0 { + return; + } + let h = height[y * w + x]; + let (left, right, up, down) = (at(x, y, -1, 0), at(x, y, 1, 0), at(x, y, 0, -1), at(x, y, 0, 1)); + let slope = Vec2::new(f64::from(right - left), f64::from(down - up)) / (2.0 * step); + let ridge = f64::from(h - 0.25 * (left + right + up + down)) / step; + let shade = strength * (facing(slope, toward) + ridge); + *p = premultiply(lit(straight(*p), shade), f32::from(p[3]) / 255.0); + }); +} + +/// Reticulation: the object redrawn in black ink on white paper through a high-contrast film-grain +/// screen. `density` (0..50) sets how fine the grain is; `foreground` and `background` (0..50 each) +/// pull shadows toward black and highlights toward white before the grain decides ink. Coverage is +/// kept. +pub(super) fn reticulation(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, density: f64, foreground: f64, background: f64) { + if !(density.is_finite() && foreground.is_finite() && background.is_finite()) { + return; + } + let Some(place) = Place::new(space, w, h) else { return }; + // Finer grain at higher density: cells from about 11 pt down to 1 pt. + let cell_size = 1.0 + (50.0 - density.clamp(0.0, 50.0)) * 0.2; + let fg = foreground.clamp(0.0, 50.0) / 50.0; + let bg = background.clamp(0.0, 50.0) / 50.0; + let spread = 0.12 + 0.38 * (density.clamp(0.0, 50.0) / 50.0); + const SALT: u64 = 0x5245_7469; + place.each(px, |x, y, p| { + if p[3] == 0 { + return; + } + let q = place.at(x, y); + let dark = f64::from(1.0 - luma(straight(*p))).clamp(0.0, 1.0); + let tone = (dark + fg * (1.0 - dark) * 0.65 - bg * dark * 0.65).clamp(0.0, 1.0); + let coarse = value_noise(SALT, q.x / cell_size, q.y / cell_size); + let fine = match (cell(q.x), cell(q.y)) { + (Some(i), Some(j)) => rand(SALT + 1, i, j, 2), + _ => 0.5, + }; + let grain = 0.55 * coarse + 0.45 * fine; + let ink = if tone + (grain - 0.5) * spread > 0.5 { 1.0 } else { 0.0 }; + *p = premultiply([(1.0 - ink) as f32; 3], f32::from(p[3]) / 255.0); + }); +} diff --git a/crates/effects/src/pixel/sketch_ink.rs b/crates/effects/src/pixel/sketch_ink.rs new file mode 100644 index 0000000000..2bd626e408 --- /dev/null +++ b/crates/effects/src/pixel/sketch_ink.rs @@ -0,0 +1,209 @@ +//! Effect › Sketch › Bas Relief, Charcoal, Photocopy and Stamp. Original filters built from public +//! behaviour documentation: and +//! (the Sketch effects +//! redraw the object in the foreground and background colours, black on white here; Bas Relief +//! carves low relief lit from a direction, Charcoal draws bold edges and sketches the midtones in +//! diagonal strokes, Photocopy copies only the edges of large dark areas and takes the midtones to +//! black or white, Stamp simplifies the image to solid black and white as a rubber stamp would). +//! Visual approximations, not reproductions of a proprietary algorithm; the ranges and defaults +//! are chosen for VectorCraft. +//! +//! All four keep the object's coverage, so they paint nothing outside it. Their sizes are in +//! document points, whatever the raster's resolution. + +use std::f64::consts::FRAC_1_SQRT_2; + +use super::pixelate::{Place, cell, value_noise}; +use super::texture::{Light, Tones, premultiply}; +use super::{PixelSpace, blur_plane}; + +const SALT_STROKES: u64 = 440; + +/// A pixel's size (points) at 72 ppi: how far the neighbours of a gradient add to a filter's reach. +const MARGIN: f64 = 1.0; + +/// Redraw `p` as ink `ink` (0..1) of black on white paper, keeping its coverage. +fn paint(p: &mut [u8; 4], ink: f64) { + let v = if ink.is_finite() { (1.0 - ink).clamp(0.0, 1.0) as f32 } else { 1.0 }; + *p = premultiply([v; 3], f32::from(p[3]) / 255.0); +} + +/// A smooth step from 0 at `t` ≤ 0 to 1 at `t` ≥ 1 (0 when `t` is not a number). +fn ramp(t: f64) -> f64 { + let t = if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 }; + t * t * (3.0 - 2.0 * t) +} + +/// The tone at (`x`, `y`) and its gradient per pixel, from central differences. +fn gradient(tones: &Tones, x: usize, y: usize) -> (f64, f64, f64) { + let gx = 0.5 * (tones.get(x + 1, y) - tones.get(x.saturating_sub(1), y)); + let gy = 0.5 * (tones.get(x, y + 1) - tones.get(x, y.saturating_sub(1))); + (tones.get(x, y), gx, gy) +} + +/// The σ (points) Bas Relief softens the object by, for Detail `detail` (1..15) and Smoothness +/// `smoothness` (1..15). +fn relief_softness(detail: f64, smoothness: f64) -> f64 { + 0.2 + 0.15 * smoothness.clamp(1.0, 15.0) + 0.1 * (15.0 - detail.clamp(1.0, 15.0)) +} + +/// How far (document units) Bas Relief reaches: the softened tones and their neighbours. +pub(super) fn relief_reach(detail: f64, smoothness: f64) -> f64 { + 3.0 * relief_softness(detail, smoothness) + MARGIN +} + +/// Bas Relief: the object carved in low relief and lit from `light`. Surfaces facing the light turn +/// white, those turned away black, flat areas grey with a hint of the object's own tones; `detail` +/// (1..15) keeps finer features and `smoothness` (1..15) rounds the carving. +pub(super) fn bas_relief(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, detail: f64, smoothness: f64, light: Light) { + if !(detail.is_finite() && smoothness.is_finite()) { + return; + } + let Some(place) = Place::new(space, w, h) else { return }; + let sigma = relief_softness(detail, smoothness); + let tones = Tones::new(px, w, h, sigma / place.px); + let toward = light.toward(); + place.each(px, |x, y, p| { + if p[3] == 0 { + return; + } + let (tone, slope) = tones.slope(x, y, &place); + // A step from black to white, softened by σ, rises 0.4 per σ at its steepest. + let lit = -slope.dot(toward) * sigma; + paint(p, 1.0 - (0.5 + 0.2 * (tone - 0.5) + 2.5 * lit)); + }); +} + +/// The σ (points) Charcoal softens the object by to find its edges, for Detail `detail` (0..5). +fn charcoal_softness(detail: f64) -> f64 { + 0.25 + 0.25 * (5.0 - detail.clamp(0.0, 5.0)) + 0.25 +} + +/// The σ (points) that thickens Charcoal's edges, for Thickness `thickness` (1..7). +fn charcoal_thickening(thickness: f64) -> f64 { + 0.35 * thickness.clamp(1.0, 7.0) +} + +/// The distance (points) between the strokes sketching Charcoal's midtones. +fn charcoal_spacing(thickness: f64) -> f64 { + 1.5 + 0.5 * thickness.clamp(1.0, 7.0) +} + +/// How far (document units) Charcoal reaches: the edges, their thickening and the strokes' tones. +pub(super) fn charcoal_reach(thickness: f64, detail: f64) -> f64 { + (3.0 * (charcoal_softness(detail) + charcoal_thickening(thickness)) + 2.0 * MARGIN).max(2.0 * charcoal_spacing(thickness) + MARGIN) +} + +/// Charcoal: bold, `thickness` (1..7) wide edges, as fine as `detail` (0..5) says, and the +/// midtones sketched in diagonal strokes; `balance` (0..100) sets how far into the lights the +/// charcoal reaches (50 is even). +pub(super) fn charcoal(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, thickness: f64, detail: f64, balance: f64) { + if !(thickness.is_finite() && detail.is_finite() && balance.is_finite()) { + return; + } + let Some(place) = Place::new(space, w, h) else { return }; + let sigma = charcoal_softness(detail); + let spacing = charcoal_spacing(thickness); + let bias = (balance.clamp(0.0, 100.0) - 50.0) / 100.0 * 0.8; + // The edges: how much the softened tones change across σ, 1 for a step from black to white. + let edge_tones = Tones::new(px, w, h, sigma / place.px); + let mut edge: Vec = (0..w * h) + .map(|k| { + let (_, gx, gy) = gradient(&edge_tones, k % w, k / w); + let contrast = gx.hypot(gy) / place.px * sigma / 0.4; + let weakest = 0.35 - 0.2 * bias / 0.4; + ramp((contrast - weakest) / 0.3) as f32 + }) + .collect(); + blur_plane(&mut edge, w, h, charcoal_thickening(thickness) / place.px); + // The strokes' tones are softer than the edges', so the strokes don't follow every speck. + let tones = Tones::new(px, w, h, 0.5 * spacing / place.px); + place.each(px, |x, y, p| { + if p[3] == 0 { + return; + } + let bold = edge.get(y * w + x).map_or(0.0, |e| ((f64::from(*e) - 0.3) / 0.3).clamp(0.0, 1.0)); + let dark = 1.0 - tones.get(x, y); + let share = ((dark + bias - 0.2) / 0.6).clamp(0.0, 1.0); + let q = place.at(x, y); + // Across the strokes, which run rising to the right, and along them. + let (across, along) = ((q.x + q.y) * FRAC_1_SQRT_2 / spacing, (q.x - q.y) * FRAC_1_SQRT_2 / spacing); + let stroke = match (share > 0.0, cell(across)) { + (true, Some(line)) => { + let f = across - line as f64; + // Each stroke breaks and swells along its length. + let swell = (0.6 + 0.8 * value_noise(SALT_STROKES, along / 6.0, line as f64)).clamp(0.0, 1.2); + let reach = (share * swell).min(1.0); + let soft = 2.0 * place.px / spacing; + (((reach - (2.0 * f - 1.0).abs()) / soft + 0.5).clamp(0.0, 1.0)) * f64::from(reach > 0.0) + } + _ => 0.0, + }; + paint(p, bold.max(stroke)); + }); +} + +/// The σ (points) of Photocopy's narrow softening for Detail `detail` (1..24): the less detail, +/// the wider. +fn copy_softness(detail: f64) -> f64 { + 0.15 * (25.0 - detail.clamp(1.0, 24.0)) +} + +/// How much wider Photocopy's second softening is than its first. +const COPY_WIDER: f64 = 3.0; + +/// How far (document units) Photocopy reaches: the wide softening. +pub(super) fn copy_reach(detail: f64) -> f64 { + 3.0 * COPY_WIDER * copy_softness(detail) + MARGIN +} + +/// Photocopy: black where a pixel is darker than its surroundings, white elsewhere. Large dark +/// areas copy only around their edges and midtones go to black or white. `detail` (1..24) keeps +/// finer features and `darkness` (1..50) copies more of the dark. +pub(super) fn photocopy(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, detail: f64, darkness: f64) { + if !(detail.is_finite() && darkness.is_finite()) { + return; + } + let Some(place) = Place::new(space, w, h) else { return }; + let sigma = copy_softness(detail) / place.px; + let narrow = Tones::new(px, w, h, sigma); + let wide = Tones::new(px, w, h, COPY_WIDER * sigma); + // How much darker than its surroundings a pixel must be to print. + let threshold = 0.02 + 0.10 * (1.0 - (darkness.clamp(1.0, 50.0) - 1.0) / 49.0); + let soft = 0.02; + place.each(px, |x, y, p| { + if p[3] == 0 { + return; + } + paint(p, ((wide.get(x, y) - narrow.get(x, y) - threshold) / soft + 0.5).clamp(0.0, 1.0)); + }); +} + +/// The σ (points) Stamp softens the object by for Smoothness `smoothness` (1..50). +fn stamp_softness(smoothness: f64) -> f64 { + 0.1 * smoothness.clamp(1.0, 50.0) +} + +/// How far (document units) Stamp reaches: the softened tones and their neighbours. +pub(super) fn stamp_reach(smoothness: f64) -> f64 { + 3.0 * stamp_softness(smoothness) + MARGIN +} + +/// Stamp: the object as solid black and white, like a rubber stamp. `balance` (0..50) sets how much +/// of the object prints black and `smoothness` (1..50) rounds the shapes. +pub(super) fn stamp(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, balance: f64, smoothness: f64) { + if !(balance.is_finite() && smoothness.is_finite()) { + return; + } + let Some(place) = Place::new(space, w, h) else { return }; + let tones = Tones::new(px, w, h, stamp_softness(smoothness) / place.px); + let threshold = 0.2 + 0.6 * balance.clamp(0.0, 50.0) / 50.0; + place.each(px, |x, y, p| { + if p[3] == 0 { + return; + } + let (tone, gx, gy) = gradient(&tones, x, y); + // A one pixel wide edge, whatever the softening. + paint(p, ((threshold - tone) / gx.hypot(gy).max(0.01) + 0.5).clamp(0.0, 1.0)); + }); +} diff --git a/crates/effects/src/pixel/tests.rs b/crates/effects/src/pixel/tests.rs index 361c507332..7d45556c5f 100644 --- a/crates/effects/src/pixel/tests.rs +++ b/crates/effects/src/pixel/tests.rs @@ -1998,6 +1998,47 @@ fn brush_strokes_follow_the_object_at_any_resolution() { } } +/// Chalk & Charcoal of `p` over `w` × `h` pixels of `src`, laid out by `s`. +fn chalk_charcoal(p: serde_json::Value, src: &[u8], w: usize, h: usize, s: &PixelSpace) -> Vec { + let mut out = src.to_vec(); + fx("sketch.chalkCharcoal", p).apply(&mut out, w, h, s); + out +} + +#[test] +fn chalk_charcoal_params_take_defaults_and_stay_in_range() { + assert_eq!(fx("sketch.chalkCharcoal", json!({})), PixelFx::ChalkCharcoal { chalk: 6.0, charcoal: 6.0, pressure: 2.0 }); + assert_eq!( + fx("sketch.chalkCharcoal", json!({"chalkArea": 1e9, "charcoalArea": -2, "strokePressure": 99})), + PixelFx::ChalkCharcoal { chalk: 20.0, charcoal: 0.0, pressure: 5.0 } + ); + let doc = crate::effect_info("sketch.chalkCharcoal").unwrap().params; + assert!(doc.contains("chalkArea") && doc.contains("charcoalArea") && doc.contains("strokePressure"), "{doc}"); + let f = fx("sketch.chalkCharcoal", json!({"strokePressure": 5})); + assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0); + assert!(f.reach().unwrap() > 0.0); +} + +#[test] +fn chalk_charcoal_draws_in_black_and_white_only() { + let (w, h) = (48, 48); + let src = image(w, h, |x, y| { + let c = [[230u8, 20, 20], [20, 200, 40], [30, 60, 220], [240, 220, 30]][(x / 12) % 4]; + let a: u16 = if y < 24 { 255 } else { 128 }; + [c[0], c[1], c[2]].map(|v| (u16::from(v) * a / 255) as u8).into_iter().chain([a as u8]).collect::>().try_into().unwrap() + }); + let out = chalk_charcoal(json!({"chalkArea": 12, "charcoalArea": 12, "strokePressure": 4}), &src, w, h, &space(w, h)); + for (p, q) in out.as_chunks::<4>().0.iter().zip(src.as_chunks::<4>().0) { + assert_eq!(p[3], q[3], "coverage kept"); + if p[3] == 0 { + continue; + } + assert_eq!(p[0], p[1]); + assert_eq!(p[1], p[2]); + } + assert_ne!(out, src); +} + /// Halftone Pattern of `p` over `w` × `h` pixels of `src`, laid out by `s`. fn halftone(p: serde_json::Value, src: &[u8], w: usize, h: usize, s: &PixelSpace) -> Vec { let mut out = src.to_vec(); @@ -2010,6 +2051,38 @@ fn period(values: &[u8]) -> usize { (1..values.len()).find(|p| values.iter().zip(&values[*p..]).all(|(a, b)| a == b)).unwrap_or(values.len()) } +#[test] +fn graphic_pen_params_take_defaults_and_stay_in_range() { + use super::STROKE_DIRECTIONS; + assert_eq!(fx("sketch.graphicPen", json!({})), PixelFx::GraphicPen { length: 5.0, balance: 50.0, direction: StrokeDirection::RightDiagonal }); + assert_eq!( + fx("sketch.graphicPen", json!({"strokeLength": 0, "lightDarkBalance": 200, "strokeDirection": "VERTICAL"})), + PixelFx::GraphicPen { length: 1.0, balance: 100.0, direction: StrokeDirection::Vertical } + ); + let doc = crate::effect_info("sketch.graphicPen").unwrap().params; + assert!(STROKE_DIRECTIONS.iter().all(|(_, v)| doc.contains(&format!("\"{v}\""))), "{doc}"); + let f = fx("sketch.graphicPen", json!({"strokeLength": 15})); + assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), brushstrokes::stroke_reach(15.0)); + assert_eq!(f.reach(), Some(brushstrokes::stroke_reach(15.0).max(brushstrokes::TONE_REACH))); + assert_eq!( + fx("sketch.graphicPen", json!({"strokeLength": 99})), + PixelFx::GraphicPen { length: 15.0, balance: 50.0, direction: StrokeDirection::RightDiagonal } + ); +} + +/// Graphic Pen on a mid-grey field draws both black ink and white paper. +#[test] +fn graphic_pen_draws_ink_and_paper_on_grey() { + let (w, h) = (48, 48); + let src = image(w, h, |_, _| grey(32)); + let mut out = src.clone(); + fx("sketch.graphicPen", json!({"strokeLength": 4, "lightDarkBalance": 50})).apply(&mut out, w, h, &space(w, h)); + let lumas: Vec = out.as_chunks::<4>().0.iter().map(|p| p[0]).collect(); + let (min, max) = lumas.iter().fold((255u8, 0u8), |(lo, hi), l| (lo.min(*l), hi.max(*l))); + assert!(min < 80 && max > 200, "min {min} max {max}"); + assert_ne!(out, src, "the filter should change the raster"); +} + #[test] fn halftone_pattern_params_take_defaults_and_stay_in_range() { assert_eq!(fx("sketch.halftonePattern", json!({})), PixelFx::HalftonePattern { size: 1.0, contrast: 5.0, kind: HalftonePattern::Dot }); @@ -2033,6 +2106,44 @@ fn halftone_pattern_params_take_defaults_and_stay_in_range() { assert_eq!(f.reach(), Some(0.0)); } +#[test] +fn note_paper_params_take_defaults_and_stay_in_range() { + assert_eq!(fx("sketch.notePaper", json!({})), PixelFx::NotePaper { balance: 25.0, graininess: 0.0, relief: 4.0 }); + assert_eq!( + fx("sketch.notePaper", json!({"imageBalance": -1, "graininess": 20, "relief": 100})), + PixelFx::NotePaper { balance: 0.0, graininess: 10.0, relief: 50.0 } + ); + let doc = crate::effect_info("sketch.notePaper").unwrap().params; + assert!(doc.contains("imageBalance") && doc.contains("graininess") && doc.contains("relief"), "{doc}"); + let f = fx("sketch.notePaper", json!({"relief": 12})); + assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0); + assert_eq!(f.reach(), Some(0.0)); +} + +/// Note Paper embosses a horizontal gradient and graininess adds fibre. +#[test] +fn note_paper_embosses_a_gradient_and_grain_changes_pixels() { + let (w, h) = (32, 32); + let src = image(w, h, |x, _| grey((x * 255 / (w - 1)) as u8)); + let flat = { + let mut out = src.clone(); + fx("sketch.notePaper", json!({"relief": 0, "graininess": 0})).apply(&mut out, w, h, &space(w, h)); + out + }; + let embossed = { + let mut out = src.clone(); + fx("sketch.notePaper", json!({"relief": 50, "graininess": 0})).apply(&mut out, w, h, &space(w, h)); + out + }; + assert_ne!(flat, embossed, "relief changes the emboss"); + let grainy = { + let mut out = src.clone(); + fx("sketch.notePaper", json!({"relief": 0, "graininess": 10})).apply(&mut out, w, h, &space(w, h)); + out + }; + assert_ne!(flat, grainy, "graininess adds fibre"); +} + /// Line's rows repeat every Size points: Size pixels at 72 ppi, twice as many at 144 ppi. #[test] fn halftone_line_period_is_the_size_at_any_resolution() { @@ -2077,6 +2188,41 @@ fn halftone_pattern_type_changes_the_pattern() { } } +/// Plaster of `p` over `w` × `h` pixels of `src`, laid out by `s`. +fn plaster(p: serde_json::Value, src: &[u8], w: usize, h: usize, s: &PixelSpace) -> Vec { + let mut out = src.to_vec(); + fx("sketch.plaster", p).apply(&mut out, w, h, s); + out +} + +#[test] +fn plaster_params_take_defaults_and_stay_in_range() { + use super::texture::Light; + assert_eq!(fx("sketch.plaster", json!({})), PixelFx::Plaster { image_balance: 20.0, smoothness: 8.0, light: Light::Top }); + assert_eq!( + fx("sketch.plaster", json!({"imageBalance": 0, "smoothness": 1e9, "lightDirection": "bottomRight"})), + PixelFx::Plaster { image_balance: 1.0, smoothness: 15.0, light: Light::BottomRight } + ); + assert_eq!(fx("sketch.plaster", json!({"lightDirection": "nonsense"})), fx("sketch.plaster", json!({}))); + let doc = crate::effect_info("sketch.plaster").unwrap().params; + assert!(doc.contains("\"bottomRight\""), "{doc}"); + let f = fx("sketch.plaster", json!({"smoothness": 24})); + assert_eq!(f.reach(), Some(super::sketch::plaster_reach(15.0))); +} + +/// Plaster changes the image and different light directions give different results. +#[test] +fn plaster_light_direction_shifts_shading() { + let (w, h) = (48, 32); + let src = image(w, h, |x, y| grey((16 + (x + y) % 200) as u8)); + let s = space(w, h); + let base = plaster(json!({"imageBalance": 20, "smoothness": 6, "lightDirection": "top"}), &src, w, h, &s); + assert_ne!(base, src, "plaster changes opaque pixels"); + let left = plaster(json!({"lightDirection": "left"}), &src, w, h, &s); + let right = plaster(json!({"lightDirection": "right"}), &src, w, h, &s); + assert_ne!(left, right, "light direction changes the relief shading"); +} + #[test] fn halftone_contrast_sharpens_the_screen() { let (w, h) = (64, 32); @@ -2114,6 +2260,89 @@ fn halftone_draws_in_black_and_white_only() { } } +fn chrome(p: serde_json::Value, src: &[u8], w: usize, h: usize, s: &PixelSpace) -> Vec { + let mut out = src.to_vec(); + fx("sketch.chrome", p).apply(&mut out, w, h, s); + out +} + +/// Reticulation of `p` over `w` × `h` pixels of `src`, laid out by `s`. +fn reticulation(p: serde_json::Value, src: &[u8], w: usize, h: usize, s: &PixelSpace) -> Vec { + let mut out = src.to_vec(); + fx("sketch.reticulation", p).apply(&mut out, w, h, s); + out +} + +#[test] +fn chrome_params_take_defaults_and_stay_in_range() { + assert_eq!(fx("sketch.chrome", json!({})), PixelFx::Chrome { detail: 4.0, smoothness: 4.0 }); + assert_eq!(fx("sketch.chrome", json!({"detail": -1, "smoothness": 99})), PixelFx::Chrome { detail: 0.0, smoothness: 10.0 }); + assert_eq!(fx("sketch.chrome", json!({"detail": "x"})), fx("sketch.chrome", json!({}))); + let doc = crate::effect_info("sketch.chrome").unwrap().params; + assert!(doc.contains("detail") && doc.contains("smoothness"), "{doc}"); + let f = fx("sketch.chrome", json!({})); + assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0); + assert_eq!(f.reach(), Some(sketch::chrome_reach(4.0))); + assert_eq!(fx("sketch.chrome", json!({"smoothness": 10})).reach(), Some(sketch::chrome_reach(10.0))); +} + +/// Chrome redraws in greyscale, keeps coverage, and more detail changes the pattern. +#[test] +fn chrome_draws_polished_greyscale_relief() { + let (w, h) = (64, 64); + let src = image(w, h, |x, y| { + let t = ((x + y) * 4) as u8; + [t, t / 2, 255 - t, 255] + }); + let soft = chrome(json!({"detail": 0, "smoothness": 8}), &src, w, h, &space(w, h)); + let sharp = chrome(json!({"detail": 10, "smoothness": 0}), &src, w, h, &space(w, h)); + assert_ne!(soft, sharp); + for out in [&soft, &sharp] { + for (p, q) in out.as_chunks::<4>().0.iter().zip(src.as_chunks::<4>().0) { + assert_eq!(p[3], q[3], "coverage kept"); + assert!(p[0] == p[1] && p[1] == p[2], "greyscale {p:?}"); + } + assert!(share(out, |p| p[0] > 10 && p[0] < 245) > 0.05, "midtones"); + } +} + +#[test] +fn reticulation_params_take_defaults_and_stay_in_range() { + assert_eq!(fx("sketch.reticulation", json!({})), PixelFx::Reticulation { density: 12.0, foreground: 6.0, background: 6.0 }); + assert_eq!( + fx("sketch.reticulation", json!({"density": -5, "foregroundLevel": 99, "backgroundLevel": -1})), + PixelFx::Reticulation { density: 0.0, foreground: 50.0, background: 0.0 } + ); + let f = fx("sketch.reticulation", json!({})); + assert_eq!(f.outset(Rect::new(0.0, 0.0, 100.0, 50.0)), 0.0); + assert_eq!(f.reach(), Some(0.0)); +} + +#[test] +fn reticulation_draws_in_black_and_white_only() { + let (w, h) = (48, 48); + let src = image(w, h, |x, y| { + let c = [[230u8, 20, 20], [20, 200, 40], [30, 60, 220], [240, 220, 30]][(x / 12) % 4]; + let a: u16 = if y < 24 { 255 } else { 128 }; + [c[0], c[1], c[2]].map(|v| (u16::from(v) * a / 255) as u8).into_iter().chain([a as u8]).collect::>().try_into().unwrap() + }); + let out = reticulation(json!({}), &src, w, h, &space(w, h)); + for (p, q) in out.as_chunks::<4>().0.iter().zip(src.as_chunks::<4>().0) { + assert_eq!(p[3], q[3], "coverage kept"); + assert!(p[0] == p[1] && p[1] == p[2] && (p[0] == 0 || p[0] == p[3]), "{p:?} from {q:?}"); + } + assert!(share(&out, |p| p[0] == 0) > 0.05 && share(&out, |p| p[0] == p[3]) > 0.05, "ink and paper"); +} + +#[test] +fn reticulation_density_changes_the_grain() { + let (w, h) = (64, 64); + let src = image(w, h, |_, _| grey(128)); + let low = reticulation(json!({"density": 5}), &src, w, h, &space(w, h)); + let high = reticulation(json!({"density": 45}), &src, w, h, &space(w, h)); + assert_ne!(low, high); +} + /// The distinct colours of the covered pixels. fn colours(d: &[u8]) -> std::collections::BTreeSet<[u8; 4]> { d.as_chunks::<4>().0.iter().filter(|p| p[3] > 0).copied().collect() @@ -2148,7 +2377,12 @@ fn artistic_params_take_defaults_and_stay_in_range() { fx("artistic.neonGlow", json!({"glowSize": -1e308, "glowBrightness": 80, "color": "#ff0000"})), PixelFx::NeonGlow { size: -24.0, brightness: 50.0, colour: [1.0, 0.0, 0.0] } ); - for id in ["artistic.cutout", "artistic.neonGlow", "artistic.posterEdges"] { + assert_eq!(fx("artistic.plasticWrap", json!({})), PixelFx::PlasticWrap { highlight: 20.0, detail: 12.0, smoothness: 15.0 }); + assert_eq!( + fx("artistic.plasticWrap", json!({"highlightStrength": -1, "detail": 99, "smoothness": 0})), + PixelFx::PlasticWrap { highlight: 0.0, detail: 15.0, smoothness: 1.0 } + ); + for id in ["artistic.cutout", "artistic.neonGlow", "artistic.plasticWrap", "artistic.posterEdges"] { assert_eq!(fx(id, json!({})).outset(Rect::new(0.0, 0.0, 40.0, 30.0)), 0.0, "{id} keeps the object's shape"); } } @@ -2166,6 +2400,7 @@ fn artistic_filters_leave_invalid_coordinate_spaces_alone() { let filters = [ PixelFx::Cutout { levels: 4.0, simplicity: 4.0, fidelity: 2.0 }, PixelFx::NeonGlow { size: 5.0, brightness: 15.0, colour }, + PixelFx::PlasticWrap { highlight: 20.0, detail: 12.0, smoothness: 15.0 }, PixelFx::PosterEdges { thickness: 2.0, intensity: 1.0, posterization: 2.0 }, ]; for f in &filters { @@ -2196,6 +2431,26 @@ fn artistic_filters_leave_invalid_coordinate_spaces_alone() { assert!(changed.is_empty(), "directly constructed non-finite parameters and invalid spaces are harmless: {changed:?}"); } +#[test] +fn plastic_wrap_adds_specular_highlights_and_keeps_coverage() { + let (w, h) = (48, 32); + let src = image(w, h, |x, y| grey((((x + y) * 5) % 200 + 30) as u8)); + let mut none = src.clone(); + fx("artistic.plasticWrap", json!({"highlightStrength": 0})).apply(&mut none, w, h, &space(w, h)); + assert_eq!(none, src); + let mut out = src.clone(); + fx("artistic.plasticWrap", json!({})).apply(&mut out, w, h, &space(w, h)); + assert!(out != src, "defaults brighten some pixels"); + assert!(out.as_chunks::<4>().0.iter().zip(src.as_chunks::<4>().0).all(|(o, s)| o[3] == s[3])); + let mut weak = src.clone(); + let mut strong = src.clone(); + fx("artistic.plasticWrap", json!({"highlightStrength": 4})).apply(&mut weak, w, h, &space(w, h)); + fx("artistic.plasticWrap", json!({"highlightStrength": 20})).apply(&mut strong, w, h, &space(w, h)); + let lift = + |a: &[u8], b: &[u8]| a.as_chunks::<4>().0.iter().zip(b.as_chunks::<4>().0).map(|(o, s)| i32::from(o[0]) - i32::from(s[0])).sum::(); + assert!(lift(&strong, &src) > lift(&weak, &src), "stronger highlights lift more"); +} + #[test] fn cutout_paints_a_few_flat_colours_and_keeps_coverage() { let (w, h) = (64, 24); diff --git a/crates/effects/src/pixel/tests_paint.rs b/crates/effects/src/pixel/tests_paint.rs new file mode 100644 index 0000000000..e84e587c9a --- /dev/null +++ b/crates/effects/src/pixel/tests_paint.rs @@ -0,0 +1,189 @@ +//! Artistic › Smudge Stick, Sponge and Watercolor. + +use serde_json::json; +use vectorcraft_doc::Effect; +use vectorcraft_geom::{Affine, Point}; + +use super::*; +use crate::{RasterFx, raster_effects}; + +/// A `w` × `h` raster whose pixels are document points (origin top-left), of an object that fills it. +fn space(w: usize, h: usize) -> PixelSpace { + let (w, h) = (w as f64, h as f64); + PixelSpace { + to_doc: Affine::IDENTITY, + px: 1.0, + center: Point::new(w / 2.0, h / 2.0), + channels: Channels::Rgb, + line: 1.0, + extent: 0.5 * w.hypot(h), + } +} + +fn image(w: usize, h: usize, f: impl Fn(usize, usize) -> [u8; 4]) -> Vec { + (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).flat_map(|(x, y)| f(x, y)).collect() +} + +fn fx(id: &str, p: serde_json::Value) -> PixelFx { + let e = Effect { id: id.into(), params: p, visible: true }; + match raster_effects(&[e]).first() { + Some(RasterFx::Pixel(p)) => p.clone(), + other => panic!("{id}: {other:?}"), + } +} + +fn run(id: &str, p: serde_json::Value, src: &[u8], w: usize, h: usize) -> Vec { + let mut out = src.to_vec(); + fx(id, p).apply(&mut out, w, h, &space(w, h)); + out +} + +fn grey(v: u8) -> [u8; 4] { + [v, v, v, 255] +} + +/// The mean of channel 0 over the columns `x0..x1`. +fn mean(d: &[u8], w: usize, x0: usize, x1: usize) -> f64 { + let rows = d.len() / 4 / w; + let sum: f64 = (0..rows).flat_map(|y| (x0..x1).map(move |x| (x, y))).map(|(x, y)| f64::from(d[(y * w + x) * 4])).sum(); + sum / (rows * (x1 - x0)) as f64 +} + +/// The summed difference between horizontal neighbours of channel 0 over columns `x0..x1`. +fn roughness(d: &[u8], w: usize, x0: usize, x1: usize) -> f64 { + let rows = d.len() / 4 / w; + (0..rows) + .flat_map(|y| (x0..x1 - 1).map(move |x| (x, y))) + .map(|(x, y)| (f64::from(d[(y * w + x) * 4]) - f64::from(d[(y * w + x + 1) * 4])).abs()) + .sum() +} + +fn spread(d: &[u8]) -> f64 { + let v: Vec = d.as_chunks::<4>().0.iter().map(|p| f64::from(p[0])).collect(); + let m = v.iter().sum::() / v.len() as f64; + (v.iter().map(|x| (x - m).powi(2)).sum::() / v.len() as f64).sqrt() +} + +/// No panic and the coverage kept on tiny, huge and non-finite spaces and parameters. +fn survives(id: &str, params: &[serde_json::Value]) { + let (w, h) = (9, 7); + let src = image(w, h, |x, y| [(x * 25) as u8, (y * 30) as u8, 90, if x == 0 { 0 } else { 255 }]); + let tiny = PixelSpace { px: 1e-9, ..space(w, h) }; + let huge = PixelSpace { px: 1e9, center: Point::new(f64::MAX, -1e300), ..space(w, h) }; + let nan = PixelSpace { px: f64::NAN, ..space(w, h) }; + for p in params { + for s in [tiny, huge, nan, space(w, h)] { + let mut out = src.clone(); + fx(id, p.clone()).apply(&mut out, w, h, &s); + assert_eq!(out.len(), src.len()); + } + } + // A size that doesn't match, and an empty raster, do nothing. + let mut odd = vec![1u8; 10]; + fx(id, json!({})).apply(&mut odd, 3, 3, &space(3, 3)); + assert_eq!(odd, vec![1u8; 10]); + fx(id, json!({})).apply(&mut [], 0, 0, &space(1, 1)); +} + +#[test] +fn smudge_stick_smudges_the_dark_and_lightens_the_light() { + assert_eq!(fx("artistic.smudgeStick", json!({})), PixelFx::SmudgeStick { stroke: 2.0, highlight: 12.0, intensity: 10.0 }); + assert_eq!( + fx("artistic.smudgeStick", json!({"strokeLength": 1e308, "highlightArea": -5, "intensity": "x"})), + PixelFx::SmudgeStick { stroke: 10.0, highlight: 0.0, intensity: 10.0 } + ); + // A fine checkerboard of dark tones on the left, of light tones on the right, and a half + // transparent bottom. + let (w, h) = (64, 48); + let src = image(w, h, |x, y| { + let on = (x + y) % 2 == 0; + let v = match (x < 32, on) { + (true, true) => 20, + (true, false) => 70, + (false, true) => 190, + (false, false) => 240, + }; + if y < 40 { grey(v) } else { [v / 2, v / 2, v / 2, 128] } + }); + let out = run("artistic.smudgeStick", json!({}), &src, w, h); + assert_eq!(out, run("artistic.smudgeStick", json!({}), &src, w, h), "draws the same twice"); + assert!(out.as_chunks::<4>().0.iter().zip(src.as_chunks::<4>().0).all(|(o, s)| o[3] == s[3]), "coverage kept"); + // The dark detail is smudged away, the light areas brighter. + assert!(roughness(&out, w, 4, 28) < 0.5 * roughness(&src, w, 4, 28)); + assert!(mean(&out, w, 36, 60) > mean(&src, w, 36, 60) + 10.0); + // Intensity 0 leaves the light areas unlightened. + let flat = run("artistic.smudgeStick", json!({"intensity": 0}), &src, w, h); + assert!(mean(&flat, w, 36, 60) < mean(&out, w, 36, 60) - 5.0); + survives( + "artistic.smudgeStick", + &[json!({}), json!({"strokeLength": 1e308, "highlightArea": 1e308, "intensity": 1e308}), json!({"strokeLength": "NaN"})], + ); +} + +#[test] +fn sponge_dabs_contrasting_blobs_and_keeps_the_hue() { + assert_eq!(fx("artistic.sponge", json!({})), PixelFx::Sponge { brush: 2.0, definition: 12.0, smoothness: 5.0 }); + assert_eq!( + fx("artistic.sponge", json!({"brushSize": -1, "definition": 1e308, "smoothness": 0})), + PixelFx::Sponge { brush: 0.0, definition: 25.0, smoothness: 1.0 } + ); + let (w, h) = (80, 60); + let flat = image(w, h, |_, y| if y < 50 { [200, 90, 60, 255] } else { [100, 45, 30, 128] }); + let out = run("artistic.sponge", json!({"definition": 25}), &flat, w, h); + assert_eq!(out, run("artistic.sponge", json!({"definition": 25}), &flat, w, h), "draws the same twice"); + assert!(out.as_chunks::<4>().0.iter().zip(flat.as_chunks::<4>().0).all(|(o, s)| o[3] == s[3]), "coverage kept"); + // A flat colour breaks up into lighter and darker blobs of the same hue. + let top = &out[..w * 50 * 4]; + assert!(spread(top) > 15.0, "{}", spread(top)); + assert!(top.as_chunks::<4>().0.iter().all(|p| p[0] >= p[1] && p[1] >= p[2]), "red stays the strongest channel"); + // Definition 0 leaves a flat colour as it is; more definition, more contrast. + let none = run("artistic.sponge", json!({"definition": 0}), &flat, w, h); + assert!(spread(&none[..w * 50 * 4]) < 1.0); + let some = run("artistic.sponge", json!({"definition": 8}), &flat, w, h); + assert!(spread(&some[..w * 50 * 4]) < spread(top)); + survives("artistic.sponge", &[json!({}), json!({"brushSize": 1e308, "definition": 1e308, "smoothness": 1e308}), json!({"brushSize": "NaN"})]); +} + +#[test] +fn watercolor_simplifies_detail_and_saturates_edges() { + assert_eq!(fx("artistic.watercolor", json!({})), PixelFx::Watercolor { detail: 9.0, shadow: 1.0, texture: 1 }); + assert_eq!( + fx("artistic.watercolor", json!({"brushDetail": 99, "shadowIntensity": -1, "texture": 2.6})), + PixelFx::Watercolor { detail: 14.0, shadow: 0.0, texture: 3 } + ); + // Noisy grey on the left, a step from light red to dark blue on the right, a transparent row. + let (w, h) = (64, 48); + let src = image(w, h, |x, y| { + if y >= 44 { + return [0; 4]; + } + if x < 32 { + grey(if (x * 7 + y * 13) % 5 < 2 { 90 } else { 150 }) + } else if x < 48 { + [200, 120, 120, 255] + } else { + [60, 70, 110, 255] + } + }); + let few = run("artistic.watercolor", json!({"brushDetail": 1}), &src, w, h); + let many = run("artistic.watercolor", json!({"brushDetail": 14}), &src, w, h); + assert_eq!(few, run("artistic.watercolor", json!({"brushDetail": 1}), &src, w, h), "draws the same twice"); + assert!(few.as_chunks::<4>().0.iter().zip(src.as_chunks::<4>().0).all(|(o, s)| o[3] == s[3]), "coverage kept, nothing painted outside"); + assert!(roughness(&few, w, 4, 28) < 0.5 * roughness(&src, w, 4, 28), "less detail, simpler"); + assert!(roughness(&few, w, 4, 28) < roughness(&many, w, 4, 28)); + // Colour is saturated where the tones change, and shadows deepen with Shadow Intensity. + let chroma = |d: &[u8], x: usize, y: usize| { + let i = (y * w + x) * 4; + f64::from(d[i].max(d[i + 1]).max(d[i + 2])) - f64::from(d[i].min(d[i + 1]).min(d[i + 2])) + }; + assert!(chroma(&few, 47, 20) > chroma(&src, 47, 20) || chroma(&few, 48, 20) > chroma(&src, 48, 20)); + assert!(mean(&run("artistic.watercolor", json!({"shadowIntensity": 10}), &src, w, h), w, 4, 28) < mean(&few, w, 4, 28)); + // Texture adds paper grain to a flat colour. + let flat = image(w, h, |_, _| grey(128)); + let (t1, t3) = (run("artistic.watercolor", json!({"texture": 1}), &flat, w, h), run("artistic.watercolor", json!({"texture": 3}), &flat, w, h)); + assert!(spread(&t3) > spread(&t1) && spread(&t1) > 0.2); + survives( + "artistic.watercolor", + &[json!({}), json!({"brushDetail": -1e308, "shadowIntensity": 1e308, "texture": 1e308}), json!({"brushDetail": "NaN"})], + ); +} diff --git a/crates/effects/src/pixel/tests_sketch.rs b/crates/effects/src/pixel/tests_sketch.rs new file mode 100644 index 0000000000..d97cc89f8f --- /dev/null +++ b/crates/effects/src/pixel/tests_sketch.rs @@ -0,0 +1,181 @@ +//! Sketch › Bas Relief, Charcoal, Photocopy and Stamp. + +use serde_json::json; +use vectorcraft_doc::Effect; +use vectorcraft_geom::{Affine, Point, Rect}; + +use super::*; +use crate::{RasterFx, raster_effects}; + +/// A `w` × `h` raster whose pixels are document points (origin top-left), of an object that fills it. +fn space(w: usize, h: usize) -> PixelSpace { + let (w, h) = (w as f64, h as f64); + PixelSpace { + to_doc: Affine::IDENTITY, + px: 1.0, + center: Point::new(w / 2.0, h / 2.0), + channels: Channels::Rgb, + line: 1.0, + extent: 0.5 * w.hypot(h), + } +} + +fn image(w: usize, h: usize, f: impl Fn(usize, usize) -> [u8; 4]) -> Vec { + (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).flat_map(|(x, y)| f(x, y)).collect() +} + +fn fx(id: &str, p: serde_json::Value) -> PixelFx { + let e = Effect { id: id.into(), params: p, visible: true }; + match raster_effects(&[e]).first() { + Some(RasterFx::Pixel(p)) => p.clone(), + other => panic!("{id}: {other:?}"), + } +} + +fn run(id: &str, p: serde_json::Value, src: &[u8], w: usize, h: usize) -> Vec { + let mut out = src.to_vec(); + fx(id, p).apply(&mut out, w, h, &space(w, h)); + out +} + +fn grey(v: u8) -> [u8; 4] { + [v, v, v, 255] +} + +/// Channel 0 of pixel (`x`, `y`). +fn at(d: &[u8], w: usize, x: usize, y: usize) -> u8 { + d[(y * w + x) * 4] +} + +/// How many pixels of channel 0 are darker than 128. +fn black(d: &[u8]) -> usize { + d.as_chunks::<4>().0.iter().filter(|p| p[0] < 128).count() +} + +/// No panic and the coverage kept on tiny, huge and non-finite spaces and parameters. +fn survives(id: &str, params: &[serde_json::Value]) { + let (w, h) = (9, 7); + let src = image(w, h, |x, y| [(x * 25) as u8, (y * 30) as u8, 90, if x == 0 { 0 } else { 255 }]); + let tiny = PixelSpace { px: 1e-9, ..space(w, h) }; + let huge = PixelSpace { px: 1e9, center: Point::new(f64::MAX, -1e300), ..space(w, h) }; + let nan = PixelSpace { px: f64::NAN, ..space(w, h) }; + for p in params { + for s in [tiny, huge, nan, space(w, h)] { + let mut out = src.clone(); + fx(id, p.clone()).apply(&mut out, w, h, &s); + assert_eq!(out.len(), src.len()); + let alphas = |d: &[u8]| d.as_chunks::<4>().0.iter().map(|p| p[3]).collect::>(); + if s.px == 1.0 { + assert_eq!(alphas(&out), alphas(&src), "{id}: coverage kept"); + } + } + } + // A size that doesn't match, and an empty raster, do nothing. + let mut odd = vec![1u8; 10]; + fx(id, json!({})).apply(&mut odd, 3, 3, &space(3, 3)); + assert_eq!(odd, vec![1u8; 10]); + fx(id, json!({})).apply(&mut [], 0, 0, &space(1, 1)); +} + +#[test] +fn photocopy_copies_the_edges_of_dark_areas() { + assert_eq!(fx("sketch.photocopy", json!({})), PixelFx::Photocopy { detail: 7.0, darkness: 25.0 }); + assert_eq!(fx("sketch.photocopy", json!({"detail": 1e308, "darkness": -5})), PixelFx::Photocopy { detail: 24.0, darkness: 1.0 }); + let (w, h) = (64, 16); + let src = image(w, h, |x, _| grey(if x < 32 { 30 } else { 230 })); + let out = run("sketch.photocopy", json!({"detail": 20}), &src, w, h); + // Black just on the dark side of the edge; white in the dark area's middle and in the light. + assert!(at(&out, w, 30, 8) < 64, "edge {}", at(&out, w, 30, 8)); + assert!(at(&out, w, 6, 8) > 192, "dark area {}", at(&out, w, 6, 8)); + assert!(at(&out, w, 50, 8) > 192, "light area {}", at(&out, w, 50, 8)); + assert_eq!(out, run("sketch.photocopy", json!({"detail": 20}), &src, w, h), "deterministic"); + // A higher Darkness copies more. + let more = run("sketch.photocopy", json!({"detail": 20, "darkness": 50}), &src, w, h); + let less = run("sketch.photocopy", json!({"detail": 20, "darkness": 1}), &src, w, h); + assert!(black(&more) >= black(&less)); + survives("sketch.photocopy", &[json!({}), json!({"detail": 1e308, "darkness": "NaN"}), json!({"detail": -1e308, "darkness": [1]})]); +} + +#[test] +fn stamp_prints_solid_black_and_white() { + assert_eq!(fx("sketch.stamp", json!({})), PixelFx::Stamp { balance: 25.0, smoothness: 5.0 }); + assert_eq!(fx("sketch.stamp", json!({"lightDarkBalance": 1e308, "smoothness": -1})), PixelFx::Stamp { balance: 50.0, smoothness: 1.0 }); + let (w, h) = (64, 8); + let src = image(w, h, |x, _| grey((x * 4) as u8)); + let few = run("sketch.stamp", json!({"lightDarkBalance": 0}), &src, w, h); + let many = run("sketch.stamp", json!({"lightDarkBalance": 50}), &src, w, h); + assert!(black(&many) > black(&few), "{} vs {}", black(&many), black(&few)); + // Pure black and white, but for the one pixel wide edges. + let mixed = many.as_chunks::<4>().0.iter().filter(|p| p[0] != 0 && p[0] != 255).count(); + assert!(mixed * 10 < many.len() / 4, "{mixed} grey pixels"); + assert_eq!(at(&many, w, 0, 4), 0); + assert_eq!(at(&many, w, 63, 4), 255); + survives( + "sketch.stamp", + &[json!({}), json!({"lightDarkBalance": "NaN", "smoothness": 1e308}), json!({"lightDarkBalance": -1e308, "smoothness": null})], + ); +} + +#[test] +fn charcoal_draws_bold_edges_and_sketches_the_midtones() { + assert_eq!(fx("sketch.charcoal", json!({})), PixelFx::Charcoal { thickness: 1.0, detail: 1.0, balance: 50.0 }); + assert_eq!( + fx("sketch.charcoal", json!({"thickness": 1e308, "detail": -5, "lightDarkBalance": "x"})), + PixelFx::Charcoal { thickness: 7.0, detail: 0.0, balance: 50.0 } + ); + let (w, h) = (64, 48); + // Black on the left, white on the right: a bold line at the edge, nothing in the white. + let step = image(w, h, |x, _| grey(if x < 32 { 0 } else { 255 })); + let out = run("sketch.charcoal", json!({}), &step, w, h); + assert!((28..36).any(|x| at(&out, w, x, 24) < 64), "edge"); + assert!((48..64).all(|x| at(&out, w, x, 24) == 255), "white stays white"); + // A midtone is sketched in strokes, more of it the more the balance reaches into the lights. + let mid = image(w, h, |_, _| grey(128)); + let sketched = run("sketch.charcoal", json!({}), &mid, w, h); + let (n, total) = (black(&sketched), w * h); + assert!(n > total / 50 && n < total * 9 / 10, "{n} of {total}"); + let darker = run("sketch.charcoal", json!({"lightDarkBalance": 100}), &mid, w, h); + let lighter = run("sketch.charcoal", json!({"lightDarkBalance": 0}), &mid, w, h); + assert!(black(&darker) > black(&lighter)); + assert_eq!(sketched, run("sketch.charcoal", json!({}), &mid, w, h), "deterministic"); + let white = image(w, h, |_, _| grey(255)); + assert_eq!(black(&run("sketch.charcoal", json!({"lightDarkBalance": 0}), &white, w, h)), 0); + survives( + "sketch.charcoal", + &[json!({}), json!({"thickness": 1e308, "detail": "NaN", "lightDarkBalance": [1]}), json!({"thickness": -1e308, "detail": 1e308})], + ); +} + +#[test] +fn bas_relief_lights_the_surfaces_facing_the_light() { + assert_eq!(fx("sketch.basRelief", json!({})), PixelFx::BasRelief { detail: 13.0, smoothness: 3.0, light: Light::Bottom }); + assert_eq!( + fx("sketch.basRelief", json!({"detail": 0, "smoothness": 1e308, "lightDirection": "Top"})), + PixelFx::BasRelief { detail: 1.0, smoothness: 15.0, light: Light::Top } + ); + // Dark above, light below: the edge is lit from one side and shaded from the other. + let (w, h) = (16, 48); + let src = image(w, h, |_, y| grey(if y < 24 { 20 } else { 235 })); + let below = run("sketch.basRelief", json!({"lightDirection": "bottom"}), &src, w, h); + let above = run("sketch.basRelief", json!({"lightDirection": "top"}), &src, w, h); + let edge = (0..h).map(|y| (y, i32::from(at(&below, w, 8, y)) - i32::from(at(&above, w, 8, y)))).max_by_key(|(_, d)| d.abs()); + assert!(edge.is_some_and(|(_, d)| d.abs() > 100), "{edge:?}"); + // Flat areas are grey. + for y in [2, 45] { + let v = at(&below, w, 8, y); + assert!((90..190).contains(&v), "flat {v}"); + } + survives( + "sketch.basRelief", + &[json!({}), json!({"detail": "NaN", "smoothness": 1e308, "lightDirection": 3}), json!({"detail": -1e308, "smoothness": null})], + ); +} + +#[test] +fn sketch_filters_reach_beyond_nothing_they_do_not_paint() { + for id in ["sketch.basRelief", "sketch.charcoal", "sketch.photocopy", "sketch.stamp"] { + let f = fx(id, json!({})); + assert_eq!(f.outset(Rect::new(0.0, 0.0, 50.0, 50.0)), 0.0, "{id} keeps the object's coverage"); + assert!(f.reach().is_some_and(|r| r.is_finite() && r > 0.0), "{id} reach"); + } +} diff --git a/crates/effects/src/pixel/texture.rs b/crates/effects/src/pixel/texture.rs index c3ef214d71..18c95681d8 100644 --- a/crates/effects/src/pixel/texture.rs +++ b/crates/effects/src/pixel/texture.rs @@ -128,7 +128,7 @@ impl Light { } /// The unit vector towards the light (document axes, y down). - fn toward(self) -> Vec2 { + pub(super) fn toward(self) -> Vec2 { let d = FRAC_1_SQRT_2; match self { Light::Bottom => Vec2::new(0.0, 1.0), @@ -269,7 +269,7 @@ impl Tones { } /// The tone at pixel (`x`, `y`) and its slope per document unit along the document's axes. - fn slope(&self, x: usize, y: usize, place: &Place) -> (f64, Vec2) { + pub(super) fn slope(&self, x: usize, y: usize, place: &Place) -> (f64, Vec2) { let gx = 0.5 * (self.get(x + 1, y) - self.get(x.saturating_sub(1), y)); let gy = 0.5 * (self.get(x, y + 1) - self.get(x, y.saturating_sub(1))); // Per pixel → per document unit: through the transpose of the document → pixel map. diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index e0c469718b..ce844a0765 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -7,12 +7,14 @@ //! warp bends a line of type as a whole. An image is clipped by its reshaped frame. Raster effects //! (shadows, glows, blur, feather) stay on the result for the renderer and exporters. Type without //! inline graphics whose own fills or strokes have geometry effects is outlined too: each of those -//! effects reshapes the whole outline that its fill or stroke paints. +//! effects reshapes the whole outline that its fill or stroke paints. An image's own fills and +//! strokes paint only the shape that a Convert to Shape or Outline Object effect on them gives +//! them ([`image_rows`]). use std::sync::Arc; use vectorcraft_doc::{Appearance, AppearanceItem, Effect, Node, NodeKind}; -use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes}; +use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Rect, Shape, shapes}; use crate::{GeomContext, apply_one, is_geometry, merged_params}; @@ -44,11 +46,75 @@ pub fn has_gradient_copies(n: &Node) -> bool { } /// Is `n` type without inline graphics that has a fill or stroke of its own that paints and has a -/// visible geometry effect? Such an effect reshapes the whole outline that its fill or stroke +/// visible geometry effect, or an image with a fill or stroke of its own that paints a shape +/// ([`image_rows`])? On type, such an effect reshapes the whole outline that its fill or stroke /// paints ([`outline_text`], which leaves inline graphics out). pub fn has_item_geometry(n: &Node) -> bool { - let NodeKind::Text(t) = &n.kind else { return false }; - t.runs.iter().all(|r| r.inline.is_none()) && n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) + match &n.kind { + NodeKind::Text(t) => { + t.runs.iter().all(|r| r.inline.is_none()) && n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects())) + } + NodeKind::Image(_) => n.appearance.items.iter().any(shapes_image), + _ => false, + } +} + +/// Does effect `e` give an image's fill or stroke a shape to paint (a visible Convert to Shape or +/// Outline Object)? +fn gives_shape(e: &Effect) -> bool { + e.visible + && matches!(e.id.as_str(), "convertToShape.rectangle" | "convertToShape.roundedRectangle" | "convertToShape.ellipse" | "path.outlineObject") +} + +/// Does `item`, a fill or stroke of an image, paint something: does it paint and carry an effect +/// that gives it a shape ([`gives_shape`])? +fn shapes_image(item: &AppearanceItem) -> bool { + crate::paints(item) && item.effects().iter().any(gives_shape) +} + +/// The fills and strokes of `items` (an image's own) that paint something ([`shapes_image`]), each +/// without the effects before its first Convert to Shape or Outline Object. Convert to Shape sizes +/// its shape from the image's box, and Outline Object gives the image's frame. The others paint +/// nothing. +fn image_rows(items: &[AppearanceItem]) -> Vec { + items + .iter() + .filter(|i| shapes_image(i)) + .map(|i| { + let mut i = i.clone(); + let fx = i.effects_mut(); + let first = fx.iter().position(gives_shape).unwrap_or(0); + fx.drain(..first); + i + }) + .collect() +} + +/// The shapes that the image `n`'s own fills and strokes paint ([`image_rows`]), each with its fill +/// rule and the fill or stroke that paints it: the paths (or compound paths) along its frame that +/// [`reshape`] makes, with each fill's or stroke's geometry effects applied as the renderer applies +/// them. Empty for anything but an image with such fills or strokes. +pub fn image_paint(n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { + if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) { + return vec![]; + } + let Some(art) = reshape(n, None) else { return vec![] }; + let mut out = vec![]; + art.walk(&mut |c| { + let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &c.kind else { return }; + let Some(g) = c.stroke_path() else { return }; + let ctx = GeomContext::of(c); + for item in c.appearance.items.iter().filter(|i| crate::paints(i)) { + let fx = item.effects(); + let shape = if crate::has_geometry(fx) && !g.elements().is_empty() { + crate::apply_geometry_bez(fx, &g, g.bounding_box(), &ctx.item(item)) + } else { + g.clone() + }; + out.push((shape, *rule, item.clone())); + } + }); + out } /// The glyph outlines of type `t` in text space with its underline and strikethrough bars: one @@ -186,11 +252,13 @@ pub(crate) fn outline_nested_text(n: &mut Node, clipping: bool) { /// `n` (see [`needs_outline`]) with its object-level geometry effects and its perspective applied: /// its [`outline_art`] reshaped as one piece, or for an image the image clipped by its reshaped -/// frame. Type's own fills and strokes keep their effects on its whole outline. The result is a -/// group with `n`'s id, name, visibility, transparency, opacity mask and remaining (raster) -/// effects; `None` when `n` has no visible geometry effect, no perspective and is not type with -/// a geometry effect on a fill or stroke of its own ([`has_item_geometry`]), or has no art (a -/// symbol instance without `symbol_art`). +/// frame. Type's own fills and strokes keep their effects on its whole outline. An image's own +/// fills and strokes that paint a shape ([`image_rows`]) become paths along its frame below and +/// above it, reshaped with it, and keep their effects from their first Convert to Shape or Outline +/// Object on. The result is a group with `n`'s id, name, visibility, transparency, opacity mask +/// and remaining (raster) effects; `None` when `n` has no visible geometry effect, no perspective +/// and is not type or an image with a fill or stroke of its own that [`has_item_geometry`] counts, +/// or has no art (a symbol instance without `symbol_art`). pub fn reshape(n: &Node, symbol_art: Option<&Node>) -> Option { if (geometry_effects(n).is_empty() && n.projection().is_none() && !has_item_geometry(n)) || !(needs_outline(n) || has_gradient_copies(n)) { return None; @@ -200,14 +268,17 @@ pub fn reshape(n: &Node, symbol_art: Option<&Node>) -> Option { /// `n` (see [`needs_outline`], or a path with [`has_gradient_copies`]) as plain art for Expand /// Appearance: [`reshape`]d when it has -/// geometry effects, else type with fills or strokes of its own outlined, in the same form. `None` -/// when it has neither. +/// geometry effects, else type with fills or strokes of its own outlined, or an image with fills +/// or strokes of its own that paint a shape, in the same form. `None` when it has none of these. pub fn expand_outlined(n: &Node, symbol_art: Option<&Node>) -> Option { // A path whose Transform effect copies it with a gradient: each copy an object of its own. if has_gradient_copies(n) { return as_art(n, symbol_art); } - let own_paint = matches!(n.kind, NodeKind::Text(_)) && !n.appearance.items.is_empty(); + let own_paint = match n.kind { + NodeKind::Text(_) => !n.appearance.items.is_empty(), + _ => has_item_geometry(n), + }; if !needs_outline(n) || (geometry_effects(n).is_empty() && !own_paint) { return None; } @@ -220,12 +291,28 @@ pub(crate) fn as_art(n: &Node, symbol_art: Option<&Node>) -> Option { let mut art = match &n.kind { NodeKind::Image(im) => { let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf); - let mut clip = Node::path(n.id, frame, Appearance::default()); - if let NodeKind::Path { clipping, .. } = &mut clip.kind { - *clipping = true; - } let image = Node::new(n.id, n.kind.clone()); - Node::new(n.id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(image)], clip: true }) + let clipped = || { + let mut clip = Node::path(n.id, frame.clone(), Appearance::default()); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + Node::new(n.id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(image.clone())], clip: true }) + }; + // The fills and strokes that paint a shape, as paths along the frame below and above + // the image. + let (below, above) = n.appearance.split_contents(); + let (below, above) = (image_rows(below), image_rows(above)); + if below.is_empty() && above.is_empty() { + clipped() + } else { + let rows = |items: Vec| { + (!items.is_empty()).then(|| Arc::new(Node::path(n.id, frame.clone(), Appearance { items, ..Default::default() }))) + }; + // Without geometry effects, the image is not clipped. + let image = if fx.is_empty() { image.clone() } else { clipped() }; + Node::group(n.id, rows(below).into_iter().chain([Arc::new(image)]).chain(rows(above)).collect()) + } } _ => outline_art(n, symbol_art)?, }; @@ -234,7 +321,8 @@ pub(crate) fn as_art(n: &Node, symbol_art: Option<&Node>) -> Option { if let Some(h) = n.projection() { project_leaves(&mut art, &h); } - // The art is a group with `n`'s id (a clip group for an image). + // The art is a group with `n`'s id (for an image without fills or strokes that paint, a clip + // group). let mut out = art; out.name = n.name.clone(); out.visible = n.visible; diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index d28ab56e50..d4c461f073 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -212,8 +212,12 @@ fn region(path: &PathData, rule: FillRule, item: &AppearanceItem) -> (PathData, } /// The 3D art of one effect `fx` on `path` (already through the effects before it). -/// Extrude & Bevel and Inflate build a solid from the outline, painted with the top visible fill -/// (or, without one, the top stroke); Rotate turns every fill and stroke, each in its own paint. +/// Rotate turns every fill and stroke, each in its own paint. Extrude & Bevel and Inflate build a +/// solid from the path for the top visible fill and one from the outline of each visible stroke, +/// each in its own paint. When every one is opaque with normal blending and no colored light makes +/// a surface one composite or masks it, their faces are drawn in one back-to-front order (where +/// depths tie, as for the caps turned toward the viewer, in the order of the appearance); +/// otherwise each solid is a surface of its own, in that order. fn art_for(n: &Node, fx: &Effect, path: &PathData, rule: FillRule, items: &[&AppearanceItem]) -> Option>> { let b = path.bounds()?; let p = crate::merged_params(&fx.id, &fx.params); @@ -229,12 +233,72 @@ fn art_for(n: &Node, fx: &Effect, path: &PathData, rule: FillRule, items: &[&App } return Some(out); } - let item = items.iter().rev().find(|i| matches!(i, AppearanceItem::Fill(_))).or_else(|| items.last())?; - let (paint, opacity, blend) = paint_of(item); - // A loaded file or a shape edited past the limits keeps drawing its source path instead of - // failing the frame; commands validate the same evaluator and report its errors. - let f = facets(&fx.id, path, rule, b, &p).ok()?; - Some(vec![Arc::new(surface(n, f, &paint, opacity, blend, colored))]) + let top_fill = items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_))); + let parts: Vec<(&AppearanceItem, PathData, FillRule)> = items + .iter() + .enumerate() + .filter(|(k, i)| Some(*k) == top_fill || matches!(i, AppearanceItem::Stroke(_))) + .map(|(_, i)| { + let (area, rule) = region(path, rule, i); + (*i, area, rule) + }) + .collect(); + // The solids share the bounds of all their shapes: one center to turn, twist and taper about, + // and Inflate's grid reaches over the strokes' outlines. + let bounds = parts.iter().filter_map(|(_, area, _)| area.bounds()).reduce(|a, c| a.union(c)).unwrap_or(b); + let built = if fx.id == INFLATE { + // One eye for every puff, as far away as the highest needs. + let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, area, rule)| (area, *rule)).collect(); + vectorcraft_three_d::inflate_together(&shapes, bounds, inflate_options(&p), view_options(&p)) + } else { + parts.iter().map(|(_, area, rule)| facets(&fx.id, area, *rule, bounds, &p)).collect() + }; + let mut solids = vec![]; + for ((item, _, _), f) in parts.iter().zip(built) { + let item: &AppearanceItem = item; + match f { + Ok(f) => solids.push((item, f)), + // A stroke's outline past the limits is left out; the fill's solid still draws. + Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {} + // A loaded file or a shape edited past the limits keeps drawing its source path + // instead of failing the frame; commands validate the same evaluator and report its + // errors. + Err(_) => return None, + } + } + if solids.is_empty() { + return None; + } + let opaque = solids.iter().all(|(item, _)| { + let (_, opacity, blend) = paint_of(item); + opacity >= 1.0 && blend == BlendMode::Normal + }); + let surfaces: Vec<(Vec, Node)> = solids + .into_iter() + .map(|(item, f)| { + let depths: Vec = f.iter().map(|f| f.depth).collect(); + let (paint, opacity, blend) = paint_of(item); + (depths, surface(n, f, &paint, opacity, blend, colored)) + }) + .collect(); + // One order takes a plain group of faces from each solid, one face for each facet. With + // colored lights a surface can instead be one clipped composite of all its facets, or carry an + // opacity mask, and then it stays whole. + let plain = surfaces.iter().all(|(depths, s)| { + s.extras().mask.is_none() && matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len()) + }); + if !opaque || !plain { + return Some(surfaces.into_iter().map(|(_, s)| Arc::new(s)).collect()); + } + let mut faces = vec![]; + for (depths, s) in surfaces { + if let NodeKind::Group { children, .. } = s.kind { + faces.extend(depths.into_iter().zip(children)); + } + } + // A stable sort: faces at the same depth keep the order of the appearance. + faces.sort_by(|a, b| a.0.total_cmp(&b.0)); + Some(vec![Arc::new(Node::group(n.id, faces.into_iter().map(|(_, face)| face).collect()))]) } fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData { diff --git a/crates/effects/src/tests_solids.rs b/crates/effects/src/tests_solids.rs index 335c0b8b69..61b5a7f575 100644 --- a/crates/effects/src/tests_solids.rs +++ b/crates/effects/src/tests_solids.rs @@ -1,6 +1,6 @@ use serde_json::json; use vectorcraft_doc::{Document, NodeId}; -use vectorcraft_geom::{Affine, BezPath}; +use vectorcraft_geom::{Affine, BezPath, Point, Shape}; use super::*; @@ -44,7 +44,8 @@ fn every_solid_draws_shaded_faces_and_leaves_the_source_editable() { let art = solid_art(&n).unwrap_or_else(|| panic!("{id}")); assert_eq!(n.path_data(), Some(&source), "{id}"); assert!(!faces(&art).is_empty(), "{id}"); - // The faces are the fill's red, shaded: never brighter, never another hue. + // The faces are the fill's red or the stroke's black, shaded: never brighter, never another + // hue. for f in faces(&art) { let [r, g, b] = fill_rgb(f); assert!(r <= 0.8 + 1e-6 && (g * 4.0 - r).abs() < 1e-4 && (b * 8.0 - r).abs() < 1e-4 || id == ROTATE, "{id}: {r} {g} {b}"); @@ -76,12 +77,229 @@ fn rotate_turns_every_fill_and_stroke_and_the_solids_use_the_top_fill() { n.appearance.effects[0].params = json!({"rotationX": 0, "rotationY": 60, "rotationZ": 0}); let b = solid_art(&n).unwrap().children().unwrap()[1].visual_bounds().unwrap(); assert!((b.width() - 104.0 * 0.5 - 0.75).abs() < 1e-6, "{b:?}"); - // Extrude & Bevel paints one surface with the top fill. + // Extrude & Bevel draws the fill's solid and the stroke's, both opaque, as one surface. let mut n = square_node(); n.appearance.effects.push(fx(EXTRUDE, json!({}))); assert_eq!(solid_art(&n).unwrap().children().unwrap().len(), 1); } +const BLUE: Color = Color::Rgb { r: 0.1, g: 0.3, b: 0.9 }; + +/// `b` with a red fill and a 6 pt blue stroke above it, on the path. +fn stroked(b: &BezPath) -> Node { + Node::path(NodeId(1), PathData::from_bezpath(b), Appearance::basic(Paint::solid(RED), Paint::solid(BLUE), 6.0)) +} + +/// A `width` × 100 pt rectangle at (100, 100), stroked. +fn stroked_rect(width: f64) -> Node { + let mut b = BezPath::new(); + b.move_to((100.0, 100.0)); + b.line_to((100.0 + width, 100.0)); + b.line_to((100.0 + width, 200.0)); + b.line_to((100.0, 200.0)); + b.close_path(); + stroked(&b) +} + +/// Is `face` in the stroke's blue (rather than the fill's red)? +fn blue(face: &Node) -> bool { + let [r, _, b] = fill_rgb(face); + b > r +} + +/// The bounds of the faces' own paths (without their seam strokes). +fn extent(faces: &[&Node]) -> Rect { + faces.iter().filter_map(|f| f.path_data()?.bounds()).reduce(|a, b| a.union(b)).unwrap() +} + +fn assert_rect(r: Rect, x0: f64, y0: f64, x1: f64, y1: f64) { + assert!([r.x0 - x0, r.y0 - y0, r.x1 - x1, r.y1 - y1].iter().all(|d| d.abs() < 1e-6), "{r:?}"); +} + +/// Extrude & Bevel and Inflate build a solid from each stroke's outline as well as from the path +/// for the fill: seen straight on, the stroke's faces reach 3 pt (half its width) outside the +/// fill's, and they are drawn in the stroke's paint. +#[test] +fn a_stroke_builds_a_solid_from_its_outline_beside_the_fill() { + for id in [EXTRUDE, INFLATE] { + let mut n = stroked_rect(100.0); + n.appearance.effects.push(fx(id, json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0}))); + let art = solid_art(&n).unwrap(); + let (strokes, fills): (Vec<&Node>, Vec<&Node>) = faces(&art).into_iter().partition(|f| blue(f)); + assert!(!strokes.is_empty(), "{id}: the stroke draws"); + assert_rect(extent(&fills), 100.0, 100.0, 200.0, 200.0); + assert_rect(extent(&strokes), 97.0, 97.0, 203.0, 203.0); + // Its own blue, shaded: never brighter, never another hue. + for f in &strokes { + let [r, g, b] = fill_rgb(f); + assert!(b <= 0.9 + 1e-6 && (r * 9.0 - b).abs() < 1e-4 && (g * 3.0 - b).abs() < 1e-4, "{id}: {r} {g} {b}"); + } + } +} + +/// Turned, the extrusion's walls show in both paints, and the front caps, which nothing of either +/// solid can hide, are drawn last: the fill's, then the stroke's above it, equally lit. Without +/// depth the two flat shapes are drawn in the same order. A stroke below the fill has its cap +/// drawn below the fill's. +#[test] +fn the_front_caps_are_drawn_last_in_the_order_of_the_appearance() { + // A triangle wider than deep, so the near ends of the walls lie nearer than the middle of the + // caps; the mean of its outline's points is not the mean of the stroke's. + let mut b = BezPath::new(); + b.move_to((100.0, 100.0)); + b.line_to((400.0, 100.0)); + b.line_to((100.0, 200.0)); + b.close_path(); + for params in [json!({}), json!({"depth": 120, "bevel": "rounded"}), json!({"depth": 0})] { + let mut n = stroked(&b); + n.appearance.effects.push(fx(EXTRUDE, params.clone())); + n.appearance.items.reverse(); + let art = solid_art(&n).unwrap(); + let [.., stroke_cap, fill_cap] = faces(&art)[..] else { panic!("{params}: two caps") }; + assert!(blue(stroke_cap) && !blue(fill_cap), "{params}: the stroke below"); + n.appearance.items.reverse(); + let art = solid_art(&n).unwrap(); + let faces = faces(&art); + let flat = params["depth"] == json!(0); + assert!(if flat { faces.len() == 2 } else { faces.len() > 4 }, "{params}: {} faces", faces.len()); + let [.., fill_cap, stroke_cap] = faces.as_slice() else { panic!("{params}: two caps") }; + assert!(!blue(fill_cap) && blue(stroke_cap), "{params}"); + // The stroke's cap is a ring: its outline and the hole the fill shows through. + assert_eq!(stroke_cap.path_data().unwrap().subpaths.len(), 2, "{params}"); + assert_eq!(fill_cap.path_data().unwrap().subpaths.len(), 1, "{params}"); + let shade = |f: &Node, i: usize, of: f32| fill_rgb(f)[i] / of; + assert!((shade(fill_cap, 0, 0.8) - shade(stroke_cap, 2, 0.9)).abs() < 1e-5, "{params}: one plane, one light"); + if !flat { + assert!(faces.iter().filter(|f| blue(f)).count() > 2 && faces.iter().filter(|f| !blue(f)).count() > 1, "{params}: walls of both"); + } + } +} + +/// A stroked open path builds a ribbon, the stroke's outline, not the area the path would enclose +/// if it were closed: for an L of two 100 pt legs, a 6 pt band with butt ends and a mitered corner. +#[test] +fn a_stroked_open_path_builds_a_ribbon() { + let mut b = BezPath::new(); + b.move_to((100.0, 100.0)); + b.line_to((200.0, 100.0)); + b.line_to((200.0, 200.0)); + for id in [EXTRUDE, INFLATE] { + let mut n = Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(Paint::None, Paint::solid(BLUE), 6.0)); + n.appearance.effects.push(fx(id, json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "volume": 0}))); + let art = solid_art(&n).unwrap(); + let faces = faces(&art); + assert!(faces.iter().all(|f| blue(f)), "{id}"); + assert_rect(extent(&faces), 100.0, 97.0, 203.0, 200.0); + let area: f64 = faces.iter().map(|f| f.path_data().unwrap().to_bezpath().area().abs()).sum(); + // 6 × 200 less the 3 × 3 the legs share, plus the 3 × 3 miter. + assert!((area - 1200.0).abs() < 1e-6, "{id}: {area}"); + } +} + +/// A stroke whose outline takes more points than a solid takes is left out, and the fill's solid +/// still draws. +#[test] +fn a_stroke_past_the_limits_is_left_out() { + // 1,500 corners: within the 2,048 points of the fill's solid, but not the stroke's outline. + let points: Vec = (0..1500) + .map(|k| { + let (s, c) = (k as f64 * std::f64::consts::TAU / 1500.0).sin_cos(); + let r = if k % 2 == 0 { 100.0 } else { 96.0 }; + Point::new(200.0 + r * c, 200.0 + r * s) + }) + .collect(); + let path = PathData::single(vectorcraft_geom::SubPath::polyline(&points, true)); + for id in [EXTRUDE, INFLATE] { + let mut n = Node::path(NodeId(1), path.clone(), Appearance::basic(Paint::solid(RED), Paint::solid(BLUE), 2.0)); + n.appearance.effects.push(fx(id, json!({}))); + let art = solid_art(&n).unwrap_or_else(|| panic!("{id}: the fill's solid draws")); + assert!(!faces(&art).is_empty() && faces(&art).iter().all(|f| !blue(f)), "{id}"); + } +} + +/// At no volume Inflate's front is flat: turned, the fill's cells are all drawn before the stroke's, +/// whatever their depths, as the extrusion's caps are. When the fill puffs, a stroke too narrow to +/// puff on the grid stays flat and keeps its depths: the fill's puff is drawn over its far side. +#[test] +fn a_flat_inflate_draws_the_strokes_front_above_the_fills() { + // On the 100 pt square's grid (cells 101 / 48 pt apart from 99.5) no grid point falls inside a + // 1 pt stroke, so the stroke stays flat. + for (volume, width, length) in [(0.0, 6.0, 300.0), (50.0, 1.0, 100.0)] { + let mut n = stroked_rect(length); + if let Some(AppearanceItem::Stroke(s)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) { + s.width = width; + } + n.appearance.effects.push(fx(INFLATE, json!({ "volume": volume }))); + let art = solid_art(&n).unwrap(); + let faces = faces(&art); + let first_blue = faces.iter().position(|f| blue(f)).unwrap(); + let last_red = faces.iter().rposition(|f| !blue(f)).unwrap(); + assert_eq!(last_red < first_blue, volume == 0.0, "{volume}: red at {last_red}, blue from {first_blue} of {}", faces.len()); + } +} + +/// With Perspective one eye sees the fill's puff and the stroke's, however much higher one rises: +/// seen from behind, the back of a stroke aligned outside meets the fill's back exactly. +#[test] +fn inflate_sees_the_fill_and_the_stroke_from_one_eye() { + let mut n = stroked_rect(100.0); + if let Some(AppearanceItem::Stroke(s)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) { + s.align = vectorcraft_doc::StrokeAlign::Outside; + } + let params = json!({"volume": 100, "depth": 100, "perspectiveAngle": 120, "rotationX": 15, "rotationY": 160, "rotationZ": 0}); + n.appearance.effects.push(fx(INFLATE, params)); + let art = solid_art(&n).unwrap(); + let [.., fill_back, stroke_back] = faces(&art)[..] else { panic!("two backs") }; + assert!(!blue(fill_back) && blue(stroke_back)); + let fill = fill_back.path_data().unwrap().bounds().unwrap(); + // The ring's inner contour: the smaller of its two. + let rims = stroke_back.path_data().unwrap().subpaths.iter().filter_map(|s| PathData::new(vec![s.clone()]).bounds()); + let hole = rims.reduce(|a, b| a.intersect(b)).unwrap(); + assert_rect(hole, fill.x0, fill.y0, fill.x1, fill.y1); +} + +/// A stroke with its own transparency or blending is a surface of its own above the fill's, so its +/// opacity applies to the stroke as a whole. +#[test] +fn a_translucent_stroke_is_a_surface_of_its_own() { + for (opacity, blend) in [(0.5, BlendMode::Normal), (1.0, BlendMode::Multiply)] { + let mut n = stroked_rect(100.0); + if let Some(AppearanceItem::Stroke(s)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) { + s.opacity = opacity; + s.blend = blend; + } + n.appearance.effects.push(fx(EXTRUDE, json!({}))); + let art = solid_art(&n).unwrap(); + let surfaces = art.children().unwrap(); + assert_eq!(surfaces.len(), 2); + assert_eq!((surfaces[0].opacity, surfaces[0].blend), (1.0, BlendMode::Normal)); + assert_eq!((surfaces[1].opacity, surfaces[1].blend), (opacity, blend)); + assert!(surfaces[0].children().unwrap().iter().all(|f| !blue(f)) && surfaces[1].children().unwrap().iter().all(|f| blue(f))); + } +} + +/// With a light that is not white, a fill in a gradient with transparent stops is drawn with an +/// opacity mask over its whole surface: the fill's solid and the stroke's stay surfaces of their +/// own, and the mask stays on the fill's. Under a white light the same object is one surface. +#[test] +fn a_masked_surface_under_a_colored_light_stays_whole() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let mut half = GradientStop::new(1.0, RED); + half.opacity = 0.5; + let gradient = GradientPaint::new(Gradient { kind: GradientKind::Linear, stops: vec![GradientStop::new(0.0, RED), half] }); + for (lights, surfaces) in [(json!({"lights": [{"color": "#ff8080"}]}), 2), (json!({}), 1)] { + let mut n = stroked_rect(100.0); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))) { + f.paint = Paint::Gradient(Box::new(gradient.clone())); + } + n.appearance.effects.push(fx(EXTRUDE, lights.clone())); + let art = solid_art(&n).unwrap(); + let drawn = art.children().unwrap(); + assert_eq!(drawn.len(), surfaces, "{lights}"); + assert_eq!(drawn[0].extras().mask.is_some(), surfaces == 2, "{lights}"); + } +} + #[test] fn transparency_stays_on_the_whole_surface_and_items_take_their_own_effect() { let mut n = square_node(); @@ -230,9 +448,9 @@ fn effects_before_it_shape_the_solid_and_effects_after_it_bend_the_result() { let mut n = square_node(); n.appearance.effects.push(fx("path.offsetPath", json!({"offset": 20}))); n.appearance.effects.push(fx(EXTRUDE, json!({"rotationX": 0, "rotationY": 0, "rotationZ": 0, "perspectiveAngle": 0}))); - // Straight on, the extrusion shows its front: the offset square. + // Straight on, the extrusion shows its front: the offset square and its 4 pt stroke. let b = solid_art(&n).unwrap().visual_bounds().unwrap(); - assert!((b.width() - 140.0 - 0.75).abs() < 1e-6, "{b:?}"); + assert!((b.width() - 144.0 - 0.75).abs() < 1e-6, "{b:?}"); n.appearance.effects.push(fx("distort.twist", json!({"angle": 30}))); let art = solid_art(&n).unwrap(); assert!(art.appearance.effects.iter().any(|e| e.id == "distort.twist"), "applied to the result as a whole"); @@ -316,6 +534,9 @@ fn colored_solid_inflate_batches_channels_and_clips_once_per_surface() { } let (groups, clips, paths) = count(&art); assert!(paths > 1000, "exercise a tessellated surface"); - assert_eq!(clips, 1); - assert_eq!(groups, 7, "group count must not grow with triangle count"); + // The fill's solid and the stroke's, each one composite with its own clip. + let surfaces = art.children().unwrap().len(); + assert_eq!(surfaces, 2); + assert_eq!(clips, surfaces); + assert_eq!(groups, 1 + 6 * surfaces, "group count must not grow with triangle count"); } diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 7c9f6337cf..84dc1f3c04 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -15,7 +15,9 @@ //! layer's own fills and strokes paint its members' geometry and its effects apply to them as one //! piece; the Contents row (type: Characters) is the slot that says which of its fills and strokes //! paint below the members and which above ([`Appearance::contents_at`], moved by -//! `appearance.moveItem {from: "contents"}`). +//! `appearance.moveItem {from: "contents"}`). An image's own fills and strokes paint only the +//! shape that a Convert to Shape or Outline Object effect on them gives them, below or above the +//! image as its Contents row says; new ones go right below that row. use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Paint}; @@ -36,7 +38,7 @@ pub fn specs() -> Vec { "Add New Fill", ["Window", "Appearance"], None, - "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack (a copy of its top fill; type without one: its characters' fill; else the default fill)", + "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row (a copy of its top fill; type without one: its characters' fill; else the default fill)", has_doc, |s, p| add_item(s, p, true) ), @@ -45,7 +47,7 @@ pub fn specs() -> Vec { "Add New Stroke", ["Window", "Appearance"], None, - "{ids?|id?, target?} add a stroke on top of each selected object's own stack (a copy of its top stroke, else the default stroke)", + "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row (a copy of its top stroke, else the default stroke)", has_doc, |s, p| add_item(s, p, false) ), @@ -408,6 +410,9 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result { fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result { let ids = require_targets(s, p, if fill { "appearance.addFill" } else { "appearance.addStroke" })?; let defaults = s.paint.clone(); + // Where the new item went in on the active item's object, when it is an image. + let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied()); + let mut inserted = None; s.edit(if fill { "Add New Fill" } else { "Add New Stroke" }, |d, _| { for id in &ids { if let Some(n) = d.node_mut(*id) { @@ -429,11 +434,23 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result { } else { AppearanceItem::Stroke(StrokeLayer::new(paint, n.appearance.stroke_width().max(1.0))) }; - n.appearance.items.push(item); + if matches!(n.kind, NodeKind::Image(_)) { + // On an image it goes right below the Contents row (the image). + let k = n.appearance.contents_at(); + n.appearance.items.insert(k, item); + n.appearance.set_contents_at(k + 1); + if active == Some(*id) { + inserted = Some(k); + } + } else { + n.appearance.items.push(item); + } } } Ok(()) })?; + // The rows above the new item move up by one. + s.remap_appearance_item(&ids, |a| Some(a + usize::from(inserted.is_some_and(|k| k <= a)))); ok() } @@ -478,7 +495,7 @@ fn transfer(s: &mut Session, p: &Value) -> Result { if let (Some(f), Some(t)) = (src.geometric_bounds(), to.geometric_bounds()) { ap.rebase_gradients(f, t); } - // Only groups, layers and type have a Contents (Characters) row to keep a slot for. + // Only groups, layers, type and images have a Contents (Characters) row to keep a slot for. if to.contents_label().is_none() { ap.contents_index = None; } @@ -717,7 +734,7 @@ fn move_contents(s: &mut Session, ids: &[NodeId], to: usize) -> Result { n.appearance.set_contents_at(to); slot.get_or_insert(n.appearance.contents_at()); } - slot.ok_or_else(|| bad("appearance.moveItem", "only groups, layers and type have a Contents (Characters) row"))?; + slot.ok_or_else(|| bad("appearance.moveItem", "only groups, layers, type and images have a Contents (Characters) row"))?; Ok(count_changed(d, &before, ids)) })?; Ok(json!({ "contents": slot })) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index ba69114081..61e9949935 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -89,7 +89,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°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest), rotation_relative_to_path. art: width 1..1000%, scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour)}}, newName? (trimmed; blank: the name 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°, roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180°, modes: [fixed|random|pressure for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest), rotation_relative_to_path. art: width 1..1000%, 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. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour)}}, newName? (trimmed; blank: the name is kept)} edit a brush definition (strokes using it update) → {name}", has_doc, brush_options ), diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 5dae8205a5..23a6b9dfad 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -21,7 +21,7 @@ use vectorcraft_color::Swatch; use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, PatternDef, Symbol, TextStyleDef}; use vectorcraft_geom::Rect; -pub use flavours::{BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture}; +pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture}; pub(crate) use resources::SwatchChoices; use super::*; diff --git a/crates/engine/src/cmd/clipboard/flavours.rs b/crates/engine/src/cmd/clipboard/flavours.rs index 725b8c5d99..e4ff731404 100644 --- a/crates/engine/src/cmd/clipboard/flavours.rs +++ b/crates/engine/src/cmd/clipboard/flavours.rs @@ -30,6 +30,10 @@ pub const EMF: &str = "image/emf"; /// An EPS (or other PostScript) picture: what drawing and typesetting apps copy as vector art /// beside, or instead of, a PDF (#1499). pub const EPS: &str = "application/postscript"; +/// A `.ai` or `.ait` file whose bytes are a PDF, copied in a file manager ([`file_flavour`]): Paste +/// reads it as `document.open` does, from its editing data. The type is VectorCraft's own: no +/// system clipboard carries it, and Paste asks for [`PDF`] to get it. +pub const AI: &str = "application/x-ai"; /// What Paste reads from other apps, best first: vector art before text, text before bitmaps /// (word processors offer a picture of copied text too). pub const PASTE_ORDER: [&str; 6] = [SVG, PDF, EPS, EMF, TEXT, BITMAP]; @@ -71,8 +75,9 @@ pub const FILE_HEAD: usize = 4096; /// What a file copied in a file manager pastes as, if one of `mimes` (`image/*`: any bitmap): /// SVG, PDF, EPS, a Windows metafile or a bitmap (its own `image/…` type), told from its first -/// [`FILE_HEAD`] bytes and its name. A `.ai` or `.ait` file pastes as PDF when its bytes are a -/// PDF and as EPS when they are PostScript. The file's bytes are that flavour's data. +/// [`FILE_HEAD`] bytes and its name. A `.ai` or `.ait` file is [`AI`] when its bytes are a PDF (it +/// pastes when PDF is asked for) and EPS when they are PostScript. The file's bytes are that +/// flavour's data. pub fn file_flavour(name: &str, head: &[u8], mimes: &[&str]) -> Option<&'static str> { let f = fileio::detect(name, head)?; let (asked, mime) = match f.id { @@ -83,7 +88,7 @@ pub fn file_flavour(name: &str, head: &[u8], mimes: &[&str]) -> Option<&'static "pdf" => (PDF, PDF), "ps" => (EPS, EPS), "eps" => (EPS, EPS), - "ai" | "ait" if head.starts_with(b"%PDF") => (PDF, PDF), + "ai" | "ait" if head.starts_with(b"%PDF") => (PDF, AI), "ai" | "ait" if vectorcraft_pdf::is_postscript(head) => (EPS, EPS), "emf" | "wmf" => (EMF, EMF), _ if f.raster => (BITMAP, f.mime), @@ -122,6 +127,13 @@ pub struct Flavour { const COPY_PNG_SIDE: f64 = 4096.0; /// Most bytes of text `clipboard.importText` takes. const MAX_TEXT: usize = 1 << 20; +/// Most bytes of images the SVG markup may embed and still go out as plain text. A paste reads the +/// clipboard's text first (eframe reads it on every paste key; on Linux and macOS it is the one +/// format the app writes, and checking that the clipboard still holds our copy reads it again), so +/// a placed photo in it made each paste move megabytes of base64 through the system clipboard on +/// the UI thread, and on a GNOME desktop the app stopped responding (#2213). A copy with more image +/// data than this offers its SVG under its own type and its PNG, not as text. +const COPY_TEXT_IMAGE_BYTES: usize = 1 << 20; pub fn specs() -> Vec { vec![ @@ -157,7 +169,7 @@ pub fn specs() -> Vec { "Clipboard Formats", [], None, - "{} → {flavours: [mime…]} what Copy offers other apps for the current clipboard, best first, by the Clipboard Handling preferences: text/plain (a type-only copy's text, else the SVG markup with copyAsSvg), image/svg+xml (copyAsSvg), application/pdf (copyAsPdf), image/png (always; PDF and PNG only for objects with an area); the app publishes them on Copy and Cut", + "{} → {flavours: [mime…]} what Copy offers other apps for the current clipboard, best first, by the Clipboard Handling preferences: text/plain (a type-only copy's text, else the SVG markup with copyAsSvg when the images it embeds total at most 1 MiB), image/svg+xml (copyAsSvg), application/pdf (copyAsPdf), image/png (always; PDF and PNG only for objects with an area); the app publishes them on Copy and Cut", always, flavours ), @@ -184,7 +196,7 @@ pub fn specs() -> Vec { "Load PDF into Clipboard", [], None, - "{dataBase64, page?: 1, password? (an encrypted PDF), center?: [x, y]} replace the clipboard with the objects of one PDF page (with the images, patterns and swatches they use), centred on `center` (default: the first artboard) → {count, warnings}; then run edit.paste", + "{dataBase64, page?: 1, password? (an encrypted PDF), editingData?: false (true: the data is a .ai or .ait file, read as document.open reads it; when document.open would use its editing data, every object of that data comes in, each layer's objects in stacking order and a hidden layer's objects hidden; else page `page`), center?: [x, y]} replace the clipboard with the objects of one PDF page, or of a .ai file's editing data (with the images, patterns and swatches they use), centred on `center` (default: the first artboard) → {count, warnings}; then run edit.paste", has_doc, import_pdf ), @@ -202,7 +214,7 @@ pub fn specs() -> Vec { "Load EPS into Clipboard", [], None, - "{dataBase64 (EPS or other PostScript bytes), center?: [x, y]} replace the clipboard with the picture's objects as document.open reads an EPS (editable paths, type and images, with the images, patterns and swatches they use), centred on `center` (default: the first artboard) → {count, warnings}; then run edit.paste", + "{dataBase64 (EPS or other PostScript bytes), center?: [x, y]} replace the clipboard with the picture's objects as document.open reads an EPS (editable paths, type and images, with the images, patterns and swatches they use; a hidden layer's objects hidden), centred on `center` (default: the first artboard) → {count, warnings}; then run edit.paste", has_doc, import_eps ), @@ -263,12 +275,17 @@ impl Clipboard { fileio::encode_with_warnings(&doc, "pdf", &json!({ "preserveEditing": false })).map(Some) } + /// Bytes of the encoded images the objects show (what their SVG embeds as base64). + fn image_bytes(&self) -> usize { + self.images.values().fold(0usize, |sum, b| sum.saturating_add(b.bytes.len())) + } + /// The MIME types of [`Self::flavours`], without making them. pub fn flavour_types(&self, svg: bool, pdf: bool) -> Vec<&'static str> { if self.is_empty() { return vec![]; } - let text = svg || self.nodes.iter().all(type_only); + let text = (svg && self.image_bytes() <= COPY_TEXT_IMAGE_BYTES) || self.nodes.iter().all(type_only); // Art without an area (a lone guide-like line) has no page or picture. let area = self.bounds().is_some_and(|b| b.width() > 0.0 && b.height() > 0.0); [(TEXT, text), (SVG, svg), (PDF, pdf && area), (PNG, area)].into_iter().filter_map(|(m, on)| on.then_some(m)).collect() @@ -452,8 +469,19 @@ fn import_eps(s: &mut Session, p: &Value) -> Result { /// Replace the clipboard with the objects of the picture `bytes`, read as the file `name` is /// opened (command `cmd`). fn import_picture(s: &mut Session, p: &Value, cmd: &str, name: &str, bytes: &[u8]) -> Result { - let mut loaded = fileio::load(name, bytes).map_err(|e| bad(cmd, e.to_string()))?; + let loaded = fileio::load(name, bytes).map_err(|e| bad(cmd, e.to_string()))?; + import_loaded(s, p, cmd, loaded) +} + +/// Replace the clipboard with every object of `loaded`, a file read as `document.open` reads it +/// (command `cmd`). The layers are left out, and the objects of a hidden layer come in hidden. +fn import_loaded(s: &mut Session, p: &Value, cmd: &str, mut loaded: fileio::Loaded) -> Result { loaded.doc.drop_edit_modes(); + for layer in loaded.doc.layers.iter_mut().filter(|l| !l.visible) { + for object in std::sync::Arc::make_mut(layer).children_mut().into_iter().flatten() { + std::sync::Arc::make_mut(object).visible = false; + } + } let clip = Clipboard::from_document(&loaded.doc); if clip.is_empty() { return Err(bad(cmd, "the picture has no objects")); @@ -469,7 +497,19 @@ fn import_pdf(s: &mut Session, p: &Value) -> Result { None | Some(Value::Null) => 1, Some(v) => v.as_u64().filter(|n| (1..=100_000).contains(n)).ok_or_else(|| bad(C, "page must be a whole number from 1"))? as usize, }; + let editing = match p.get("editingData").filter(|v| !v.is_null()) { + None => false, + Some(v) => v.as_bool().ok_or_else(|| bad(C, "editingData must be true or false"))?, + }; let opts = fileio::LoadOptions { password: str_param(p, "password").map(str::to_string), ..Default::default() }; + // A copied .ai file pastes every object of its editing data, as document.open reads the file. + // When document.open would not use that copy, the file pastes its page, as a PDF does. + if editing + && let Ok(loaded) = fileio::load_with("Clipboard.ai", &bytes, &opts) + && (loaded.editing_data || loaded.restored) + { + return import_loaded(s, p, C, loaded); + } let (mut doc, warnings) = fileio::page_document(&bytes, page - 1, &opts).map_err(|e| bad(C, e.to_string()))?; doc.drop_edit_modes(); let clip = Clipboard::from_document(&doc); diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index d0f0d16143..e4660bf67a 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -408,6 +408,7 @@ fn expandable(n: &Node) -> bool { !n.appearance.items.is_empty() || !n.appearance.effects.is_empty() || children.iter().any(|c| expandable(c)) } NodeKind::Text(_) => !n.appearance.items.is_empty() || !n.appearance.effects.is_empty(), + NodeKind::Image(_) => effects::has_item_geometry(n) || !n.appearance.effects.is_empty(), _ => !n.appearance.effects.is_empty(), } } diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 3fec18331f..ebeacf63a4 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -290,7 +290,7 @@ fn expand_fills(d: &mut Document, l: &Node, to: GradientTo) -> Option { for item in &l.appearance.items { // Items that paint nothing go; a gradient that can't be expanded stays. let art = gradient_fill(item).and_then(|(f, g)| { - let (fl, path, bounds) = fill_shape(l, f, &path, bounds)?; + let (fl, path, bounds) = fill_shape(l, item, &path, bounds)?; gradient_art(d, &fl, &path, bounds, f, g, to) }); let Some(art) = art else { @@ -363,15 +363,16 @@ fn reshaped(l: &Node) -> Option { Some(m) } -/// Path `l` (outline `path`, box `bounds`) as fill `f` paints it on the canvas, with its outline -/// and box: when the fill has visible geometry effects, `l` with the outline they make of `path` -/// as a plain path, and that outline's box. -fn fill_shape(l: &Node, f: &FillLayer, path: &PathData, bounds: Rect) -> Option<(Node, PathData, Rect)> { +/// Path `l` (outline `path`, box `bounds`) as its fill `item` paints it on the canvas, with its +/// outline and box: when the fill has visible geometry effects, `l` with the outline they make of +/// `path` as a plain path, and that outline's box. +fn fill_shape(l: &Node, item: &AppearanceItem, path: &PathData, bounds: Rect) -> Option<(Node, PathData, Rect)> { use vectorcraft_render::effects::{GeomContext, apply_geometry_with, has_geometry}; - if !has_geometry(&f.effects) { + if !has_geometry(item.effects()) { return Some((l.clone(), path.clone(), bounds)); } - let outline = apply_geometry_with(&f.effects, path, bounds, &GeomContext::of(l)); + // In the fill's context, as drawing runs them: a plug-in effect is told which fill it is on. + let outline = apply_geometry_with(item.effects(), path, bounds, &GeomContext::of(l).item(item)); let b = outline.bounds()?; Some((with_path(l, outline.clone()), outline, b)) } @@ -432,7 +433,7 @@ fn expand_patterns(d: &mut Document, l: &Node) -> Option { for item in &l.appearance.items { let fill = pattern_fill(d, item).map(|(f, def, xf)| (f, def.clone(), xf)); let tiles = fill.and_then(|(f, def, xf)| { - let (fl, _, bounds) = fill_shape(l, f, &path, bounds)?; + let (fl, _, bounds) = fill_shape(l, item, &path, bounds)?; let t = pattern_tiles(d, &def, xf, bounds); (!t.is_empty()).then_some((f, fl, t)) }); diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 8dda63ee4a..ae705ca483 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -411,6 +411,9 @@ pub fn encode_all(doc: &Document, format: &str, p: &Value) -> Result { /// [`encode_all`] of `doc` as it is. fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result { let f = super::writable(C, Some(format), None)?; + if let Some(plugin) = vectorcraft_plugins::export::by_format(f.id) { + return plugin_file(doc, &plugin, f, p); + } let failed = vectorcraft_render::decode_failures(); let mut enc = encode_files(doc, f, p)?; // Baking, flattening and drawing stop early when cancelled and leave a truncated result. @@ -432,6 +435,32 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result { Ok(enc) } +/// The file exporter plug-in `plugin` writes of `doc` in its format `f` +/// ([`vectorcraft_plugins::export`]). The plug-in is given the native file's JSON +/// ([`vectorcraft_format::json_part`]) and `p`'s `params`, for the file `p`'s `path` names (else +/// one named after the document) with that path's extension when the plug-in lists it, else its +/// first. Its warnings come back with the file. +fn plugin_file(doc: &Document, plugin: &vectorcraft_plugins::Plugin, f: &Format, p: &Value) -> Result { + use vectorcraft_plugins::{Error, export}; + let doc = &*doc.without_edit_modes(); + let file = vectorcraft_format::save_with(doc, &vectorcraft_format::SaveOptions::default()).map_err(|e| EngineError::Other(e.to_string()))?; + let path = p.get("path").and_then(Value::as_str); + let listed = path.map(super::extension).and_then(|e| f.extensions.iter().copied().find(|x| *x == e)); + let extension = listed.or(f.extensions.first().copied()).unwrap_or_default(); + let name = super::file_stem(path.unwrap_or(&super::default_name(doc, extension))); + let params = p.get("params").cloned().unwrap_or(Value::Null); + let target = export::Target { extension, name: &name }; + let out = export::run(plugin, vectorcraft_format::json_part(&file), ¶ms, target).map_err(|e| match e { + Error::Cancelled => EngineError::Cancelled, + Error::Params(why) => bad(C, why), + e => EngineError::Other(e.to_string()), + })?; + // The plug-in's output, so reported as its other output errors are. + let invalid = || EngineError::Other(Error::Output("`dataBase64` is not valid base64".into()).to_string()); + let bytes = vectorcraft_format::base64_decode(&out.data_base64).ok_or_else(invalid)?; + Ok(Encoded { warnings: out.warnings, ..Encoded::one(bytes) }) +} + /// [`encode_all`] without the font substitution warning. fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result { let doc = &*doc.without_edit_modes(); diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index f50728c43c..748843179d 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -26,6 +26,9 @@ pub struct Loaded { /// Only a stand-in picture of the file (an Affinity document whose native data couldn't be /// read): Open shows it with its warning; Place, templates and libraries refuse it. pub preview_only: bool, + /// A PDF, or a `.ai` or `.ait` that holds a PDF, read through the editor's own copy of its art + /// that it carries (its layers), not from its PDF part alone. + pub editing_data: bool, } impl Loaded { @@ -159,17 +162,17 @@ pub fn load(name: &str, bytes: &[u8]) -> Result { /// of its art, which it carries: its layers and hidden objects as they were, and the art outside /// its artboard (its PDF part has only what is on the artboards), as an EPS of the editor is read. /// Anything else as it was. `unit`: the size in points of a unit of the PDF part's user space (its -/// first page's `UserUnit`). -fn through_editing_data(bytes: &[u8], opts: &LoadOptions, doc: Document, warnings: Vec, unit: f64) -> (Document, Vec) { +/// first page's `UserUnit`) → (document, warnings, whether its layers were read). +fn through_editing_data(bytes: &[u8], opts: &LoadOptions, doc: Document, warnings: Vec, unit: f64) -> (Document, Vec, bool) { if opts.pages.is_some() || !opts.layers || !opts.editing_data { - return (doc, warnings); + return (doc, warnings, false); } - let Some(private) = vectorcraft_pdf::illustrator_data(bytes, opts.password.as_deref()) else { return (doc, warnings) }; + let Some(private) = vectorcraft_pdf::illustrator_data(bytes, opts.password.as_deref()) else { return (doc, warnings, false) }; let outlined = opts.text_as == vectorcraft_pdf::TextAs::Outlines; let (doc, mut warnings, read) = vectorcraft_eps::layered_ai(&private, doc, warnings, outlined, opts.trust_editing_data, unit); // The layers weren't read (or couldn't be): the notes of reading the PDF part still hold. if !read { - return (doc, warnings); + return (doc, warnings, false); } // The layers' text objects hold type and the stroked paths around it, which can include stroked // glyphs the PDF part kept as outlines: without any such glyph in the document, the warnings on @@ -180,7 +183,7 @@ fn through_editing_data(bytes: &[u8], opts: &LoadOptions, doc: Document, warning // The layers hold the art that the PDF part leaves out or, in a PDF, that the import clipped // to the page. warnings.retain(|w| w != vectorcraft_pdf::OFF_ARTBOARD_NOTE && w != vectorcraft_pdf::PAST_PAGE_NOTE); - (doc, warnings) + (doc, warnings, true) } /// A `.ai` saved without PDF compatibility (its PDF part is a placeholder page) from the editor's @@ -212,6 +215,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result let title = file_name(name); let mut converted = false; let mut preview_only = false; + let mut editing_data = false; let (mut doc, mut warnings, restored) = match format.id { // EPS, .ps and PostScript .ai: the document our EPS files carry, else the PostScript read. _ if matches!(format.id, "eps" | "ps") || vectorcraft_pdf::is_postscript(bytes) => { @@ -246,13 +250,20 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result // Pages of text alone: the editing copy alone where it reads, as for a file // saved without its PDF part (#1387: else the page, which is the art). let alone = r.only_text.then(|| from_editing_data_alone(bytes, opts)).flatten().and_then(|read| read.ok()); - Ok(alone.unwrap_or_else(|| through_editing_data(bytes, opts, r.document, r.warnings, r.user_unit))) + let (doc, warnings, read) = match alone { + Some((doc, warnings)) => (doc, warnings, true), + None => through_editing_data(bytes, opts, r.document, r.warnings, r.user_unit), + }; + editing_data = read; + Ok((doc, warnings)) } // Saved without its PDF part: the editing copy is all the file has (`pages` that // name every page read it as the whole file). Err(e) if e.to_string() == vectorcraft_pdf::PdfError::PlaceholderOnly.to_string() => { let whole = LoadOptions { pages: None, ..opts.clone() }; - from_editing_data_alone(bytes, if every_page(bytes, opts) { &whole } else { opts }).unwrap_or(Err(e)) + from_editing_data_alone(bytes, if every_page(bytes, opts) { &whole } else { opts }) + .unwrap_or(Err(e)) + .inspect(|_| editing_data = true) } Err(e) => Err(e), })? @@ -298,7 +309,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result doc.title = title; } warnings.extend(doc.images.values().filter_map(|b| too_large_note(&b.bytes))); - Ok(Loaded { doc, format, warnings, restored, converted, preview_only }) + Ok(Loaded { doc, format, warnings, restored, converted, preview_only, editing_data }) } /// Import SVG text, reading the files its images link to (relative links from `folder`, the SVG's diff --git a/crates/engine/src/cmd/fileio/mod.rs b/crates/engine/src/cmd/fileio/mod.rs index a827e93d9a..c360fd813d 100644 --- a/crates/engine/src/cmd/fileio/mod.rs +++ b/crates/engine/src/cmd/fileio/mod.rs @@ -127,7 +127,7 @@ pub fn specs() -> Vec { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate), selectedOnly?: false (the selected objects alone, in their layers), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: 72 (raster formats: pixels per inch, stored in the file; wins over scale), scale?: 1 (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: 72 (raster formats: pixels per inch, stored in the file; wins over scale), scale?: 1 (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path", has_doc, export::export ), @@ -199,7 +199,7 @@ pub fn specs() -> Vec { "File Formats", [], None, - "{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}}], readable: [id…], writable: [id…], openExtensions: [ext…], unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as DWG and PICT, with what to use instead)}", + "{} → {formats: [{id, label, extensions, mime, read, write, raster, options: {name: {type, default, description}}, plugin?: the id of the exporter plug-in that adds the format (its id is plugin.; see plugin.list)}], readable: [id…], writable: [id…], openExtensions: [ext…], unsupported: [{id, label, extensions, hint}] (formats asked for that can be neither opened nor written, such as DWG and PICT, with what to use instead)}", always, formats ), @@ -661,7 +661,7 @@ pub const FORMATS: &[Format] = &[ Format { id: "psd", label: "PSD", extensions: &["psd"], mime: "image/x-psd", read: true, write: true, raster: true, options: PSD_OPTIONS }, // Affinity Photo's `.afphoto` opens by its content but isn't listed: Finder shouldn't offer a // vector app for a raster editor's documents. - reader("affinity", "Affinity", &["af", "afdesign", "afpub"], "application/vnd.affinity", false), + reader("affinity", "Affinity", &["af", "afdesign", "afpub"], "application/x-affinity", false), // Photoshop's large document format: read like a PSD (its merged image), never written. reader("psb", "PSB", &["psb"], "image/x-psb", true), // PostScript programs, read as EPS files are; Print to PostScript writes them, exports don't. @@ -706,17 +706,19 @@ pub const OPEN_EXTS: &[&str] = &[ "afpub", ]; -/// Extensions in [`OPEN_EXTS`] the desktop packaging doesn't associate with VectorCraft: Photoshop -/// documents belong to raster editors, so Finder and file managers don't offer a vector app for -/// them, and the packaging declares no `.epsf`, `.ps` or Targa type. The macOS bundle doesn't -/// declare JPEG XL images either. File › Open and Place still read them all. +/// 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 or JPEG XL type (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. pub const UNASSOCIATED_EXTS: &[&str] = &["psd", "psb", "epsf", "ps", "tga", "vda", "icb", "vst", "jxl"]; /// The extension that picks each writable format when exporting (the format's first; PNG-8 shares /// `.png` with PNG, so `.png` comes once), in [`FORMATS`] order. pub fn export_extensions() -> Vec<&'static str> { let mut v: Vec<&'static str> = Vec::new(); - for e in FORMATS.iter().filter(|f| f.write).filter_map(|f| f.extensions.first()) { + let added = plugin_formats(); + for e in FORMATS.iter().chain(added.iter().copied()).filter(|f| f.write).filter_map(|f| f.extensions.first()) { if !v.contains(e) { v.push(e); } @@ -804,10 +806,47 @@ pub fn place_filters() -> impl Iterator Option<&'static Format> { let k = id_or_ext.trim_start_matches('.').to_ascii_lowercase(); - FORMATS.iter().find(|f| f.id == k).or_else(|| FORMATS.iter().find(|f| f.extensions.contains(&k.as_str()))) + FORMATS.iter().find(|f| f.id == k).or_else(|| FORMATS.iter().find(|f| f.extensions.contains(&k.as_str()))).or_else(|| { + let added = plugin_formats(); + added.iter().find(|f| f.id.eq_ignore_ascii_case(&k)).or_else(|| added.iter().find(|f| f.extensions.contains(&k.as_str()))).copied() + }) +} + +/// The formats the installed exporter plug-ins add ([`vectorcraft_plugins::export`]), by plug-in +/// id: write only, with the plug-in's name as the label and its extensions. Each is made once for +/// each installation of its plug-in, its strings interned, so formats live as long as the catalogues +/// that hold them. +pub fn plugin_formats() -> Vec<&'static Format> { + use vectorcraft_plugins::{export, registry}; + static MADE: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner()); + export::installed() + .iter() + .map(|p| { + if let Some((_, f)) = made.iter().find(|(serial, _)| *serial == p.serial()) { + return *f; + } + let m = p.manifest(); + let extensions: Vec<&'static str> = m.extensions.iter().map(|e| registry::intern(e)).collect(); + let f: &'static Format = Box::leak(Box::new(Format { + id: registry::intern(&export::format_id(&m.id)), + label: registry::intern(&m.name), + extensions: Box::leak(extensions.into_boxed_slice()), + mime: "application/octet-stream", + read: false, + write: true, + raster: false, + options: &[], + })); + made.push((p.serial(), f)); + f + }) + .collect() } /// The lower-case extension of a file name or path (empty when it has none). @@ -862,9 +901,18 @@ fn writable(cmd: &str, format_param: Option<&str>, path: Option<&str>) -> Result } fn formats(_: &mut Session, _: &Value) -> Result { - let ids = |pick: fn(&Format) -> bool| FORMATS.iter().filter(|f| pick(f)).map(|f| f.id).collect::>(); + let added = plugin_formats(); + let all = || FORMATS.iter().chain(added.iter().copied()); + let ids = |pick: fn(&Format) -> bool| all().filter(|f| pick(f)).map(|f| f.id).collect::>(); + let listed = |f: &Format| { + let mut v = f.to_json(); + if let Some(id) = vectorcraft_plugins::export::plugin_id(f.id) { + v["plugin"] = json!(id); + } + v + }; Ok(json!({ - "formats": FORMATS.iter().map(Format::to_json).collect::>(), + "formats": all().map(listed).collect::>(), "readable": ids(|f| f.read), "writable": ids(|f| f.write), "openExtensions": OPEN_EXTS, diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 200cc5c443..e747be71fa 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -143,13 +143,13 @@ pub(super) fn import(bytes: &[u8], o: &LoadOptions, editor_document: bool) -> Re } /// Page `page` (0-based) of a PDF as a document of one artboard (its `o.crop` box) and one -/// layer of what it shows (text as outlines: it looks as printed), and the import notes. +/// layer of what it shows, with the same text choice as Open, and the import notes. pub fn page_document(bytes: &[u8], page: usize, o: &LoadOptions) -> Result<(Document, Vec)> { let opts = ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), - text_as: TextAs::Outlines, + text_as: o.text_as, layers: false, ..Default::default() }; @@ -183,15 +183,22 @@ pub(super) fn pdf_info(_: &mut Session, p: &Value) -> Result { }) .collect(); let mut out = json!({"pages": pages.len(), "needsPassword": false, "pageInfo": pages}); - if let Some(n) = p.get("thumbnail").and_then(Value::as_u64) { - let page = usize::try_from(n).ok().and_then(|n| n.checked_sub(1)).filter(|i| *i < info.pages.len()); - let page = page.ok_or_else(|| bad(INFO, format!("thumbnail: no page {n} (the PDF has {})", info.pages.len())))?; + if let Some(page) = thumbnail_page(p, info.pages.len(), "PDF")? { let (doc, _) = page_document(&bytes, page, &o)?; out["thumbnail"] = json!(thumbnail(&doc, p)?); } Ok(out) } +/// The page (0-based) `document.pdfInfo`'s `thumbnail` names, from 1 to `count`; `None` when it is +/// absent or null. Any other value (0, a negative or fractional number, a string) is an error that +/// names the pages the `what` has. +fn thumbnail_page(p: &Value, count: usize, what: &str) -> Result> { + let Some(v) = p.get("thumbnail").filter(|v| !v.is_null()) else { return Ok(None) }; + let page = v.as_u64().and_then(|n| usize::try_from(n).ok()).and_then(|n| n.checked_sub(1)).filter(|i| *i < count); + page.map(Some).ok_or_else(|| bad(INFO, format!("thumbnail: no page {v} (the {what} has {count})"))) +} + /// `document.pdfInfo` of a PostScript file (an EPS, a `.ps` file, a `.ai` in PostScript form): one /// page, the page [`vectorcraft_eps::page`] reads, with no PDF boxes. Its thumbnail is the file as /// the EPS reader reads it without any editing data it carries: what the page prints, or the @@ -200,10 +207,7 @@ fn postscript_info(bytes: &[u8], p: &Value) -> Result { let page = vectorcraft_eps::page(bytes).map_err(err)?; let info = json!({"width": page.width(), "height": page.height(), "rotation": 0, "boxes": {}}); let mut out = json!({"pages": 1, "needsPassword": false, "pageInfo": [info]}); - if let Some(n) = p.get("thumbnail").and_then(Value::as_u64) { - if n != 1 { - return Err(bad(INFO, format!("thumbnail: no page {n} (the file has 1)"))); - } + if thumbnail_page(p, 1, "file")?.is_some() { let doc = vectorcraft_eps::import_with(bytes, false).map_err(err)?.document; out["thumbnail"] = json!(thumbnail(&doc, p)?); } diff --git a/crates/engine/src/cmd/fileio/ppi.rs b/crates/engine/src/cmd/fileio/ppi.rs index 54363e3adf..1c04db9c88 100644 --- a/crates/engine/src/cmd/fileio/ppi.rs +++ b/crates/engine/src/cmd/fileio/ppi.rs @@ -220,6 +220,21 @@ mod tests { assert!(close(resolution(&jpg).unwrap(), (254.0, 240.0 * 2.54))); } + /// A CMYK JPEG carries no JFIF (it describes one- and three-component images), so its + /// resolution is written as EXIF instead and this reader still finds it (#3084). + #[test] + fn a_cmyk_jpeg_keeps_its_resolution_without_jfif() { + use vectorcraft_render::encode::jpeg::{self, ColorModel, JpegOptions}; + let o = JpegOptions { color_model: ColorModel::Cmyk, ..Default::default() }; + let jpg = jpeg::encode(&[0; 4 * 4], 2, 2, 90, Some(240.0), &o).unwrap(); + assert!(!jpg.windows(5).any(|w| w == b"JFIF\0"), "no JFIF on a CMYK file"); + assert_eq!(resolution(&jpg), Some((240.0, 240.0))); + // An RGB file still says it in JFIF, as it always did. + let rgb = jpeg::encode(&[0; 3 * 4], 2, 2, 90, Some(240.0), &JpegOptions::default()).unwrap(); + assert!(rgb.windows(5).any(|w| w == b"JFIF\0")); + assert_eq!(resolution(&rgb), Some((240.0, 240.0))); + } + /// A little-endian TIFF/EXIF block declaring `x`/`y` resolution in `unit`. fn exif_block(x: u32, y: u32, unit: u16) -> Vec { let mut b = b"II*\0".to_vec(); diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 2e884a7398..166eda8b92 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -549,7 +549,10 @@ impl SaveJob { let one = self.encode_one(&artboard_doc(&self.doc, b))?; enc.files.extend(one.files.into_iter().map(|(_, bytes)| (Some(b), bytes))); } - enc.warnings.splice(0..0, fidelity_warning(self.plan.format)); + // Lost artboards first: the status bar shows only the first warning. + let f = self.plan.format; + let lost = if is_svg(f) { super::svg::lost_artboards_warning(&self.doc, &self.params, f.label) } else { None }; + enc.warnings.splice(0..0, lost.into_iter().chain(fidelity_warning(f))); Ok(enc) } diff --git a/crates/engine/src/cmd/fileio/svg.rs b/crates/engine/src/cmd/fileio/svg.rs index 62c2d1a3a2..8f028934a1 100644 --- a/crates/engine/src/cmd/fileio/svg.rs +++ b/crates/engine/src/cmd/fileio/svg.rs @@ -120,7 +120,9 @@ pub fn options_map(p: &Value) -> Result, String> { match o.get("svg") { None | Some(Value::Null) => {} Some(Value::Object(svg)) => m.extend(svg.clone()), - Some(_) => return Err("`svg` must be an object of SVG options (see document.formats)".into()), + Some(_) => { + return Err("`svg` must be an object of SVG options (see document.formats)".into()); + } } Ok(m) } @@ -147,6 +149,17 @@ fn plan(doc: &Document, p: &Value) -> Result<(ExportOptions, Vec>, Ok((opts, named.unwrap_or_else(|| vec![0]).into_iter().map(Some).collect(), chosen)) } +/// What a save of `doc` as SVG (format `label`) with options `p` loses of several artboards: the +/// file is one artboard and reopens as one, unless it carries the native document (Preserve +/// Editing Capabilities). +pub(super) fn lost_artboards_warning(doc: &Document, p: &Value, label: &str) -> Option { + let n = doc.artboards.len(); + let preserved = plan(doc, p).is_ok_and(|(opts, ..)| opts.preserve_editing); + (n > 1 && !preserved).then(|| { + format!("{label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all.") + }) +} + /// Encode `doc` as SVG (or gzipped, SVGZ): one file per chosen artboard, with the images they /// link to and the writer's warnings. pub(super) fn encode(doc: &Document, p: &Value, compressed: bool) -> Result { diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index d66f766d46..61c74fe583 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -103,6 +103,87 @@ fn a_one_bit_rgb_image_opens_from_the_editing_data_in_its_colors() { assert_eq!(found, [[[255, 0, 0], [0, 255, 0], [0, 0, 255]]], "{r}"); } +/// A page of a square and a line of type, as a `.ai`'s PDF part draws them. +const SQUARE_AND_TYPE: &str = "0 g 10 10 40 40 re f BT /F1 12 Tf 100 50 Td (Hi) Tj ET"; + +/// `file` loaded with `clipboard.importPdf` (`editingData` as given) and pasted → the command's +/// reply and the objects the paste selected, in stacking order. +fn paste(s: &mut Session, file: &[u8], editing_data: bool) -> (Value, Vec) { + let p = json!({"dataBase64": vectorcraft_format::base64_encode(file), "editingData": editing_data}); + let r = s.execute("clipboard.importPdf", &p).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let st = s.doc().unwrap(); + (r, st.selection.in_paint_order(&st.doc).into_iter().filter_map(|id| st.doc.node(id).cloned()).collect()) +} + +/// Is any of `nodes` (or an object inside one) type? +fn has_type(nodes: &[Node]) -> bool { + let mut found = false; + nodes.iter().for_each(|n| n.walk(&mut |c| found |= matches!(c.kind, NodeKind::Text(_)))); + found +} + +/// A `.ai` copied in a file manager pastes the objects of its editing data, as `document.open` +/// reads it: both layers' objects in their stacking order, into the active layer, with their names +/// and hidden members, and its type as type. Without `editingData`, as for a PDF, its page pastes: +/// the shown layer's art without names. +#[test] +fn a_copied_ai_file_pastes_from_its_editing_data() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let file = ai::ai(&compressed(&ai::sample_data()), ai::page_pdf()); + let (r, pasted) = paste(&mut s, &file, true); + assert_eq!(r["count"], 7, "{r}"); + let pasted_names: Vec = pasted.iter().map(|n| n.name.clone().unwrap_or_default()).collect(); + assert_eq!(pasted_names, ["Pair", "Ring", "Window", "Shaded", "", "Sub", ""]); + let pair = pasted[0].children().unwrap(); + assert!(pair[0].visible && !pair[1].visible, "the hidden member stays hidden"); + assert!(matches!(pasted[5].kind, NodeKind::Layer { .. }) && pasted[5].locked, "the sublayer comes as it is"); + assert_eq!(pasted.iter().map(|n| n.visible).collect::>(), [true, true, true, false, false, false, false], "the hidden layer's objects"); + let layers = &s.doc().unwrap().doc.layers; + assert_eq!(layers.len(), 1, "no layer is added"); + assert!(pasted.iter().all(|n| layers[0].children().unwrap().iter().any(|c| c.id == n.id)), "into the active layer"); + // The same editing data in an EPS: the same objects, the hidden layer's objects hidden. + let eps = ai::eps(&ai::sample_data(), ai::page_ps()); + s.execute("clipboard.importEps", &json!({"dataBase64": vectorcraft_format::base64_encode(&eps)})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let st = s.doc().unwrap(); + let shown = |nodes: Vec<&Node>| nodes.iter().map(|n| (n.name.clone().unwrap_or_default(), n.visible)).collect::>(); + assert_eq!(shown(st.selection.in_paint_order(&st.doc).into_iter().filter_map(|id| st.doc.node(id)).collect()), shown(pasted.iter().collect())); + let (r, page) = paste(&mut s, &file, false); + assert!(page.iter().all(|n| n.name.is_none()), "{r}"); + // A page of text only, or only a placeholder (saved without PDF compatibility): the editing + // data's objects all the same. + for (page, boxed) in [(TEXT_ART, "/ArtBox [0 0 200 100]"), (PLACEHOLDER, "")] { + let (r, pasted) = paste(&mut s, &ai::ai_with(&compressed(&ai::sample_data()), page, boxed), true); + assert_eq!(pasted.first().and_then(|n| n.name.as_deref()), Some("Pair"), "{page}: {r}"); + assert_eq!(r["count"], 7, "{page}: {r}"); + } + // Type: a text object from the editing data, outlines from the page. + let data = ai::editing_data( + 200.0, + 100.0, + &ai::layer("Art", &format!("0 g\n{}f\n/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n", ai::rect(10.0, 10.0, 50.0, 50.0))), + ); + let typed = ai::ai(&compressed(data.as_bytes()), SQUARE_AND_TYPE); + // (The page's type comes in as type too now that PDF import keeps it, so only this side is told apart.) + let (r, pasted) = paste(&mut s, &typed, true); + assert!(has_type(&pasted), "{r}: {pasted:?}"); + // A `.ai` VectorCraft wrote: the document it carries, its hidden square too. + let mut other = Session::new(); + other.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + for x in [10, 100] { + other.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 40, "height": 40})).unwrap(); + } + other.execute("object.hide", &json!({})).unwrap(); + let saved = other.execute("document.export", &json!({"format": "ai"})).unwrap(); + let saved = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let (r, pasted) = paste(&mut s, &saved, true); + assert_eq!(pasted.iter().map(|n| n.visible).collect::>(), [true, false], "{r}"); + let (r, page) = paste(&mut s, &saved, false); + assert!(page.iter().all(|n| n.visible), "{r}"); +} + /// A PDF saved with the editing data opens from it, as a `.ai` does (#868). #[test] fn a_pdf_saved_with_the_editing_data_opens_from_it() { @@ -173,6 +254,29 @@ fn editing_data_that_cant_be_read_keeps_the_pdf_parts_notes() { assert_eq!(r["warnings"], json!([vectorcraft_pdf::PAST_PAGE_NOTE, unread]), "{r}"); } +/// A copied `.ai` whose editing data can't be read, or isn't there, pastes its page as a PDF +/// does: the same objects as without `editingData`. +#[test] +fn a_copied_ai_file_whose_editing_data_cant_be_read_pastes_its_page() { + let symbols = ai::editing_data(200.0, 100.0, &ai::layer("Art", "/SymbolInstance :\n(Dot) /SymbolRef ,\n;\n")); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + for (what, private) in + [("damaged", b"%AI12_CompressedData not zlib".to_vec()), ("unread layers", compressed(symbols.as_bytes())), ("none", vec![])] + { + let file = ai::ai(&private, SQUARE_AND_TYPE); + let (r, pasted) = paste(&mut s, &file, true); + let (want, page) = paste(&mut s, &file, false); + assert_eq!((&r["count"], &r["warnings"]), (&want["count"], &want["warnings"]), "{what}"); + let kinds = |nodes: &[Node]| nodes.iter().map(|n| std::mem::discriminant(&n.kind)).collect::>(); + assert_eq!(kinds(&pasted), kinds(&page), "{what}"); + assert!(!pasted.is_empty(), "{what}: {r}"); + } + // Editing data that reads and draws as the page does: its objects, not the page's. + let (r, _) = paste(&mut s, &ai::ai(&compressed(&ai::sample_data()), ai::page_pdf()), true); + assert_eq!(r["count"], 7, "{r}"); +} + #[test] fn what_the_reader_doesnt_read_opens_as_before_with_a_warning() { let symbols = ai::editing_data(200.0, 100.0, &ai::layer("Art", "/SymbolInstance :\n(Dot) /SymbolRef ,\n;\n")); diff --git a/crates/engine/src/cmd/fileio/tests_pdffidelity.rs b/crates/engine/src/cmd/fileio/tests_pdffidelity.rs index 4844bd5188..862f3f0bed 100644 --- a/crates/engine/src/cmd/fileio/tests_pdffidelity.rs +++ b/crates/engine/src/cmd/fileio/tests_pdffidelity.rs @@ -38,6 +38,64 @@ fn text_opens_as_type_or_outlines() { assert!(e.contains("textAs must be one of text, outlines"), "{e}"); } +fn live_text_pdf() -> Vec { + let page = |text: &str| PdfPage { + resources: "/Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> >>".into(), + ..PdfPage::new(200.0, 100.0, &format!("BT /F1 12 Tf 10 50 Td ({text}) Tj ET")) + }; + pdf(&[page("First page"), page("Second page")], None) +} + +fn live_texts(s: &Session) -> Vec { + let mut texts = vec![]; + s.doc().unwrap().doc.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + texts.push(t.plain_text()); + } + }); + texts +} + +#[test] +fn pdf_place_keeps_live_text_from_bytes_and_unlinked_paths() { + let bytes = live_text_pdf(); + let dir = vectorcraft_testkit::temp_dir("pdf-place-live-text"); + let path = dir.join("text.pdf"); + std::fs::write(&path, &bytes).unwrap(); + for source in [json!({"name": "text.pdf", "dataBase64": vectorcraft_format::base64_encode(&bytes)}), json!({"path": path, "link": false})] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let mut p = source; + p["page"] = json!(2); + let r = s.execute("file.place", &p).unwrap(); + assert_eq!(live_texts(&s), ["Second page"], "{r}"); + assert!(!r["warnings"].to_string().contains("outlines"), "{r}"); + } + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn pdf_clipboard_paste_keeps_live_text_on_the_selected_page() { + let bytes = live_text_pdf(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let r = s.execute("clipboard.importPdf", &json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "page": 2})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(live_texts(&s), ["Second page"], "{r}"); + assert!(!r["warnings"].to_string().contains("outlines"), "{r}"); +} + +#[test] +fn pdf_place_honors_explicit_text_outlines() { + let bytes = live_text_pdf(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let r = + s.execute("file.place", &json!({"name": "text.pdf", "dataBase64": vectorcraft_format::base64_encode(&bytes), "textAs": "outlines"})).unwrap(); + assert!(live_texts(&s).is_empty()); + assert!(r["warnings"].to_string().contains("outlines"), "{r}"); +} + #[test] fn layers_option_keeps_or_flattens_optional_content() { let (a, b) = (first_extra(1), first_extra(1) + 1); diff --git a/crates/engine/src/cmd/fileio/tests_pdfimport.rs b/crates/engine/src/cmd/fileio/tests_pdfimport.rs index ac4e67673b..f270c87b82 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfimport.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfimport.rs @@ -228,6 +228,27 @@ fn pdf_info_reads_postscript_as_one_page() { assert!(e.contains("no page 2"), "{e}"); } +/// `document.pdfInfo`'s `thumbnail` is a page number from 1, for a PDF and for PostScript alike: +/// any other value is an error that names the pages, and an absent or null one gives no thumbnail. +#[test] +fn pdf_info_refuses_a_thumbnail_that_is_not_a_page_number() { + let ps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 50\n%%EndComments\n0 0 1 setrgbcolor 0 0 50 20 rectfill\n"; + let mut s = Session::new(); + for (bytes, pages) in [(&three_pages()[..], "(the PDF has 3)"), (ps, "(the file has 1)")] { + for n in [json!(-1), json!(0), json!(1.5), json!("1"), json!(true)] { + let e = s.execute("document.pdfInfo", &json!({"dataBase64": b64(bytes), "thumbnail": n})).unwrap_err().to_string(); + assert!(e.contains(&format!("thumbnail: no page {n} {pages}")), "{n}: {e}"); + } + for none in [json!({"dataBase64": b64(bytes)}), json!({"dataBase64": b64(bytes), "thumbnail": null})] { + assert!(s.execute("document.pdfInfo", &none).unwrap().get("thumbnail").is_none(), "{pages}"); + } + let v = s.execute("document.pdfInfo", &json!({"dataBase64": b64(bytes), "thumbnail": 1, "thumbnailSize": 64})).unwrap(); + let png = vectorcraft_format::base64_decode(v["thumbnail"].as_str().unwrap()).unwrap(); + let img = image::load_from_memory(&png).unwrap(); + assert_eq!(img.width().max(img.height()), 64, "{pages}"); + } +} + /// A page showing only text, with an editor's private data when `private`. fn text_page(private: bool, also: &str) -> PdfPage { PdfPage { diff --git a/crates/engine/src/cmd/fileio/tests_svg.rs b/crates/engine/src/cmd/fileio/tests_svg.rs index d52ab20ebf..05cafeb6a7 100644 --- a/crates/engine/src/cmd/fileio/tests_svg.rs +++ b/crates/engine/src/cmd/fileio/tests_svg.rs @@ -145,6 +145,23 @@ fn preserve_editing_reopens_the_native_document() { assert_eq!(s.doc().unwrap().doc.artboards.len(), 1); } +#[test] +fn saving_several_artboards_as_plain_svg_warns_they_are_lost() { + let artboards = |r: &Value| r["warnings"].as_array().unwrap().iter().filter(|w| w.as_str().unwrap().contains("artboards")).count(); + let mut s = session(3); + let r = s.execute("document.save", &json!({"format": "svg"})).unwrap(); + assert_eq!(artboards(&r), 1, "{r}"); + // First: the status bar shows only the first warning. + assert!(r["warnings"][0].as_str().unwrap().contains("1 of the document's 3 artboards"), "{r}"); + assert_eq!(artboards(&s.execute("file.saveAs", &json!({"format": "svgz"})).unwrap()), 1); + // Preserve Editing keeps them all (they reopen); a single artboard loses none. + for p in [json!({"format": "svg", "preserveEditing": true}), json!({"format": "svg", "svg": {"preserveEditing": true}})] { + let r = s.execute("document.save", &p).unwrap(); + assert_eq!(artboards(&r), 0, "{p}: {r}"); + } + assert_eq!(artboards(&session(1).execute("document.save", &json!({"format": "svg"})).unwrap()), 0); +} + #[test] fn save_writes_svg_and_remembers_its_options() { let mut s = session(1); diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index df5471eff8..2a71cc86ae 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -143,7 +143,7 @@ pub fn specs() -> Vec { "Artboard Options…", ["Window", "Artboards"], None, - "{index, name?, x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}", + "{index | artboards: [{index, name?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}", has_doc, artboard_set ), @@ -834,59 +834,94 @@ fn artboard_delete(s: &mut Session, p: &Value) -> Result { ok() } +/// One artboard's part of `artboard.setProps`: its index, new rectangle and name, how far it moved, +/// whether it was resized, the map its art and guides take when they go with it (`fit` when it +/// scales them), and that art. +struct ArtboardEdit<'a> { + index: usize, + now: Rect, + name: Option<&'a str>, + delta: vectorcraft_geom::Vec2, + resized: bool, + fit: Option, + transform: Option, + art: Vec, +} + fn artboard_set(s: &mut Session, p: &Value) -> Result { - let i = super::panelcmds::artboard_index(&s.doc()?.doc, p, "artboard.setProps")?; - let was = s.doc()?.doc.artboards.get(i).map(|a| a.rect).ok_or_else(|| EngineError::Other("no such artboard".into()))?; - let now = rect_from(p, was); - let resized = (now.width() - was.width()).abs() > 1e-6 || (now.height() - was.height()).abs() > 1e-6; - // Scale Artwork with Artboard: resized, it takes the art fully inside it (as Move Artwork with - // Artboard gathers it) and its guides from the old rectangle onto the new one. - let scale_art = bool_or(p, "scaleArt", false); - let fit = if scale_art && resized { rect_map(was, now) } else { None }; - // Position fields honor Move Artwork independently of Scale Artwork. A resize still - // leaves the art alone unless scaling was requested. Fit-to-art callers keep the default. - let delta = now.origin() - was.origin(); - let moving = !resized && bool_or(p, "moveArt", false) && delta != vectorcraft_geom::Vec2::ZERO; - let transform = fit.or_else(|| moving.then(|| Affine::translate(delta))); - let art = if transform.is_some() { - // Locked and hidden art too? Noted in the journal, so a replay transforms the same objects - // whatever the preference is then. - let all = bool_or(p, "lockedAndHidden", s.prefs.move_locked_with_artboard); - s.note_journal("lockedAndHidden", json!(all)); - s.doc()?.doc.art_on_artboard(was, all) - } else { - vec![] - }; - let mut sc = match fit { - Some(xf) if Scaling::factor(xf).is_some() => super::object::scaling(s, p), - _ => Scaling::default(), - }; - sc.patterns = super::object::transform_patterns(s, p, &art)?; - s.edit("Artboard Options", |d, _| { - let a = d.artboards.get_mut(i).ok_or_else(|| EngineError::Other("no such artboard".into()))?; - a.rect = now; - if let Some(n) = str_param(p, "name").map(str::trim) { - // A blank name gives the artboard its default name, Artboard N for the Nth artboard. - a.name = if n.is_empty() { format!("Artboard {}", i + 1) } else { n.to_string() }; + // One artboard (`index` and its fields), or several (`artboards`, each with its own fields). + let entries: Vec<&Value> = match p.get("artboards") { + Some(list) => { + list.as_array().filter(|l| !l.is_empty()).ok_or_else(|| bad("artboard.setProps", "artboards must be a non-empty list"))?.iter().collect() } - let id = a.id; - if let Some(xf) = transform { - d.map_artboard_guides(id, xf); - for id in &art { - if let Some(n) = d.node_mut(*id) { - n.transform(xf, sc); + None => vec![p], + }; + // Scale Artwork with Artboard: resized, an artboard takes the art fully inside it (as Move + // Artwork with Artboard gathers it) and its guides from the old rectangle onto the new one. + let scale_art = bool_or(p, "scaleArt", false); + // Locked and hidden art too? + let all = bool_or(p, "lockedAndHidden", s.prefs.move_locked_with_artboard); + let d = &s.doc()?.doc; + // Each artboard's art is the art inside it before any of them changes; an object inside + // several of them goes with the first one listed that moves or scales its art. + let mut taken = HashSet::new(); + let mut edits: Vec = Vec::with_capacity(entries.len()); + for q in entries { + let index = super::panelcmds::artboard_index(d, q, "artboard.setProps")?; + if edits.iter().any(|e| e.index == index) { + return Err(bad("artboard.setProps", "an artboard is listed twice")); + } + let was = d.artboards.get(index).map(|a| a.rect).ok_or_else(|| EngineError::Other("no such artboard".into()))?; + let now = rect_from(q, was); + let resized = (now.width() - was.width()).abs() > 1e-6 || (now.height() - was.height()).abs() > 1e-6; + let fit = if scale_art && resized { rect_map(was, now) } else { None }; + // Position fields honor Move Artwork independently of Scale Artwork. A resize still + // leaves the art alone unless scaling was requested. Fit-to-art callers keep the default. + let delta = now.origin() - was.origin(); + let moving = !resized && bool_or(p, "moveArt", false) && delta != vectorcraft_geom::Vec2::ZERO; + let transform = fit.or_else(|| moving.then(|| Affine::translate(delta))); + let art = if transform.is_some() { d.art_on_artboard(was, all).into_iter().filter(|id| taken.insert(*id)).collect() } else { vec![] }; + edits.push(ArtboardEdit { index, now, name: str_param(q, "name").map(str::trim), delta, resized, fit, transform, art }); + } + // Noted in the journal when art goes along, so a replay transforms the same objects whatever + // the preference is then. + if edits.iter().any(|e| e.transform.is_some()) { + s.note_journal("lockedAndHidden", json!(all)); + } + let scaling = + if edits.iter().any(|e| e.fit.is_some_and(|xf| Scaling::factor(xf).is_some())) { super::object::scaling(s, p) } else { Scaling::default() }; + let art: Vec = edits.iter().flat_map(|e| e.art.iter().copied()).collect(); + let patterns = super::object::transform_patterns(s, p, &art)?; + s.edit("Artboard Options", |d, _| { + for e in &edits { + let a = d.artboards.get_mut(e.index).ok_or_else(|| EngineError::Other("no such artboard".into()))?; + a.rect = e.now; + if let Some(n) = e.name { + // A blank name gives the artboard its default name, Artboard N for the Nth artboard. + a.name = if n.is_empty() { format!("Artboard {}", e.index + 1) } else { n.to_string() }; + } + let id = a.id; + if let Some(xf) = e.transform { + let mut sc = if e.fit.is_some_and(|xf| Scaling::factor(xf).is_some()) { scaling } else { Scaling::default() }; + sc.patterns = patterns; + d.map_artboard_guides(id, xf); + for id in &e.art { + if let Some(n) = d.node_mut(*id) { + n.transform(xf, sc); + } } + } else if !e.resized { + // Moved (not resized), it takes its guides along. + d.move_artboard_guides(id, e.delta); } - } else if !resized { - // Moved (not resized), it takes its guides along. - d.move_artboard_guides(id, delta); } Ok(()) })?; if !scale_art { return ok(); } - Ok(json!({ "scaled": if fit.is_some() { art.iter().map(|i| i.0).collect::>() } else { vec![] } })) + let scaled: Vec<_> = edits.iter().filter(|e| e.fit.is_some()).flat_map(|e| e.art.iter().map(|i| i.0)).collect(); + Ok(json!({ "scaled": scaled })) } /// The map taking artboard rectangle `from` onto `to`, each side scaled by its own ratio. None diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 227c0d46e1..74a70fd28e 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -5,7 +5,8 @@ //! one copies the selection as Copy does, and placing it pastes a copy as Paste does (its images, //! symbols, patterns and swatches come along; a swatch name the document gives another colour is //! merged into the document's). Items can be put in user-named groups, and a library can be -//! exported to a `.vclibrary` file and imported from one (#926). +//! exported to a `.vclibrary` file and imported from one (#926). Items and groups are kept in the +//! order the Libraries panel shows them, which dragging them there changes. use std::collections::{HashMap, HashSet}; @@ -281,6 +282,25 @@ impl Library { } } + /// Move item `r` next to `to`, an item of its kind: just before it, or just after it when + /// `after`, in their kind's list (the order the panel shows them in). + fn place_next_to(&mut self, r: &ItemRef, to: &ItemRef, after: bool) { + fn shift(list: &mut Vec, key: impl Fn(&T) -> &str, from: &str, to: &str, after: bool) { + let Some(i) = list.iter().position(|x| key(x) == from) else { return }; + let item = list.remove(i); + let j = list.iter().position(|x| key(x) == to).map_or(list.len(), |j| j + usize::from(after)); + list.insert(j.min(list.len()), item); + } + let (from, to_key) = (r.item.as_str(), to.item.as_str()); + match r.kind { + ItemKind::Color => shift(&mut self.colors, |c| c.name.as_str(), from, to_key, after), + ItemKind::CharStyle => shift(&mut self.char_styles, |c| c.name.as_str(), from, to_key, after), + ItemKind::ParaStyle => shift(&mut self.para_styles, |c| c.name.as_str(), from, to_key, after), + ItemKind::Graphic => shift(&mut self.graphics, |g| g.id.as_str(), from, to_key, after), + ItemKind::Unknown => {} + } + } + /// Make a library read from a file (hand-edited, imported) safe and consistent: at most /// [`MAX_ITEMS`] items of each kind and [`MAX_GROUPS`] groups, names clipped to [`MAX_NAME`] /// characters and unique within their kind (a repeated one gets a number), sizes finite, a @@ -552,10 +572,19 @@ pub fn specs() -> Vec { "Move Library Item to Group", [], None, - "{library?, kind, item: name (graphic: id or name), group?: name (null or none: out of its group)} put an item in a group (out of the one it was in) → {library, kind, item, group: name or null}", + "{library?, kind, item: name (graphic: id or name), group?: name (null or none: out of its group), before?: item | after?: item (an item of the same kind, named as `item` is)} put an item in a group (out of the one it was in); with `before` or `after`, also move it just before or after that item in the order its kind is shown in, as dragging it in the Libraries panel does → {library, kind, item, group: name or null}", always, move_item ), + cmd!( + "library.moveGroup", + "Move Library Group", + [], + None, + "{library?, group: name, to: index} move a group to position `to` of the library's groups (0 = first; past the end: last), as dragging its header in the Libraries panel does → {library, group, to: where it went}", + always, + move_group + ), cmd!( query "library.export", "Export Library", @@ -1023,13 +1052,30 @@ fn move_item(s: &mut Session, p: &Value) -> Result { const C: &str = "library.moveItem"; let (id, kind, item) = item_param(s, p, C)?; let group = str_param(p, "group"); + let next_to = match (str_param(p, "before"), str_param(p, "after")) { + (Some(_), Some(_)) => return Err(bad(C, "give `before` or `after`, not both")), + (Some(b), None) => Some((b, false)), + (None, Some(a)) => Some((a, true)), + (None, None) => None, + }; let (key, to) = s.libraries.change(&id, |lib| { - let r = lib.item_ref(kind.item_kind(), item).ok_or_else(|| bad(C, format!("the library has no item `{item}`")))?; + let missing = |item: &str| bad(C, format!("the library has no item `{item}`")); + let r = lib.item_ref(kind.item_kind(), item).ok_or_else(|| missing(item))?; let at = group.map(|g| group_at(lib, g, C)).transpose()?; + let next_to = next_to + .map(|(other, after)| Ok::<_, EngineError>((lib.item_ref(kind.item_kind(), other).ok_or_else(|| missing(other))?, after))) + .transpose()?; + if let Some((other, after)) = &next_to + && *other != r + { + lib.place_next_to(&r, other, *after); + } lib.ungroup(&r); let key = r.item.clone(); let to = at.and_then(|i| lib.groups.get_mut(i)).map(|g| { - g.items.push(r); + // Next to the other item when that is in the group too, else last. + let near = next_to.as_ref().and_then(|(other, after)| g.items.iter().position(|x| x == other).map(|j| j + usize::from(*after))); + g.items.insert(near.unwrap_or(g.items.len()).min(g.items.len()), r); g.name.clone() }); Ok((key, to)) @@ -1037,6 +1083,22 @@ fn move_item(s: &mut Session, p: &Value) -> Result { Ok(json!({ "library": id, "kind": str_param(p, "kind"), "item": key, "group": to })) } +fn move_group(s: &mut Session, p: &Value) -> Result { + const C: &str = "library.moveGroup"; + let id = library_id(s, p, C)?; + let group = group_param(p, C)?; + let to = p.get("to").and_then(Value::as_u64).ok_or_else(|| bad(C, "missing `to` (an index)"))?; + let (name, at) = s.libraries.change(&id, |lib| { + let i = group_at(lib, group, C)?; + let g = lib.groups.remove(i); + let at = usize::try_from(to).unwrap_or(usize::MAX).min(lib.groups.len()); + let name = g.name.clone(); + lib.groups.insert(at, g); + Ok((name, at)) + })?; + Ok(json!({ "library": id, "group": name, "to": at })) +} + fn export(s: &mut Session, p: &Value) -> Result { const C: &str = "library.export"; let id = library_id(s, p, C)?; diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 6acc37220c..5ec103e898 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -47,6 +47,7 @@ pub(crate) mod menucmds; pub(crate) mod newart; pub mod newdoc; mod object; +pub(crate) mod objects_on_path; mod opacitymask; mod overprint; mod package; @@ -257,6 +258,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(brushsym::specs()); v.extend(patterncmds::specs()); v.extend(intertwine::specs()); + v.extend(objects_on_path::specs()); v.extend(prefscmds::specs()); v.extend(distortcmds::specs()); v.extend(paint::proxy_specs()); diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index d806d9c802..186630a880 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -227,7 +227,7 @@ pub fn specs() -> Vec { has_selection, |s, _| clip_edit(s, true) ), - cmd!("object.isolate", "Enter Isolation Mode", [], None, "{id}", has_doc, isolate), + cmd!("object.isolate", "Enter Isolation Mode", [], None, "{id?} (default: the selection's first object)", has_doc, isolate), cmd!("object.exitIsolation", "Exit Isolation Mode", [], None, "{}", has_doc, exit_isolation), cmd!( "object.setProps", @@ -243,7 +243,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), 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), 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, or to the artboard (#1180)", + "{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), 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), 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, or to the artboard (#1180)", has_selection, align ), @@ -1251,12 +1251,17 @@ fn items_bounds(d: &Document, ids: &[NodeId], preview: bool) -> Vec<(NodeId, Rec ids.iter().filter_map(|id| Some((*id, d.bounds_of(&[*id], preview)?))).collect() } -/// Move each object of `moves` by its offset, as undo step `label`; pattern tiles move too when -/// [`transform_patterns`] says so for `ids`. When every move is a rounding error (1e-9 pt or less -/// on both axes), the document and its undo history stay as they are. -fn apply_moves(s: &mut Session, label: &str, p: &Value, ids: &[NodeId], moves: &[(NodeId, Vec2)]) -> Result { +/// Move each object of `moves` by its offset and each ruler guide of `guides` (index, position) +/// to its position, as undo step `label`; pattern tiles move too when [`transform_patterns`] says +/// so for `ids`. When every move is a rounding error (1e-9 pt or less on both axes), the document +/// and its undo history stay as they are. +fn apply_moves(s: &mut Session, label: &str, p: &Value, ids: &[NodeId], moves: &[(NodeId, Vec2)], guides: &[(usize, f64)]) -> Result { let sc = Scaling { patterns: transform_patterns(s, p, ids)?, ..Scaling::default() }; - if moves.iter().all(|(_, dv)| dv.x.abs() <= 1e-9 && dv.y.abs() <= 1e-9) { + let guides: Vec<(usize, f64)> = { + let d = &s.doc()?.doc; + guides.iter().copied().filter(|&(i, pos)| d.guides.get(i).is_some_and(|g| (g.pos - pos).abs() > 1e-9)).collect() + }; + if moves.iter().all(|(_, dv)| dv.x.abs() <= 1e-9 && dv.y.abs() <= 1e-9) && guides.is_empty() { return ok(); } s.edit(label, |d, _| { @@ -1265,15 +1270,42 @@ fn apply_moves(s: &mut Session, label: &str, p: &Value, ids: &[NodeId], moves: & n.transform(Affine::translate(*dv), sc); } } + for &(i, pos) in &guides { + if let Some(g) = d.guides.get_mut(i) { + g.pos = pos; + } + } Ok(()) })?; ok() } -/// What `object.align` aligns to: `to`, else the key object when there is one, else the -/// selection. +/// What `object.align` aligns to: `to`, else the key object (or key guide) when there is one, +/// else the selection. fn align_to<'a>(s: &Session, p: &'a Value) -> Option<&'a str> { - str_param(p, "to").or_else(|| s.doc().ok()?.selection.key.map(|_| "key")) + str_param(p, "to").or_else(|| s.doc().ok()?.selection.has_key().then_some("key")) +} + +/// The key guide `object.align` lines the objects up on (aligning to the key with one set, +/// [`vectorcraft_doc::Selection::key_guide`]): its position, and whether it is vertical. +fn key_guide(s: &Session, p: &Value) -> Option<(f64, bool)> { + let st = s.doc().ok()?; + let g = st.doc.guides.get(st.selection.key_guide?)?; + (align_to(s, p) == Some("key")).then_some((g.pos, g.vertical)) +} + +/// Where Align puts the objects, `r`, and the axes it moves them along (x, y): a key guide gives +/// the line across its axis only (a vertical guide fixes x, a horizontal one y), so the other +/// axis stays as it is. +fn align_reference(s: &Session, p: &Value, ids: &[NodeId], preview: bool, own: Option) -> Result<(Rect, bool, bool)> { + if let Some((pos, vertical)) = key_guide(s, p) { + return Ok((Rect::new(pos, pos, pos, pos), vertical, !vertical)); + } + let r = match own { + Some(b) if align_to(s, p) != Some("artboard") => b, + _ => reference_rect(s, p, ids, preview)?, + }; + Ok((r, true, true)) } fn reference_rect(s: &Session, p: &Value, ids: &[NodeId], preview: bool) -> Result { @@ -1328,7 +1360,8 @@ fn align(s: &mut Session, p: &Value) -> Result { if !s.doc()?.selection.anchors.is_empty() { return align_anchors(s, p, &ids, (h, v)); } - let r = reference_rect(s, p, &ids, preview)?; + let (r, along_x, along_y) = align_reference(s, p, &ids, preview, None)?; + let (h, v) = (h.filter(|_| along_x), v.filter(|_| along_y)); let key = key_root(s, &ids); let moves: Vec<(NodeId, Vec2)> = { let d = &s.doc()?.doc; @@ -1352,7 +1385,35 @@ fn align(s: &mut Session, p: &Value) -> Result { }) .collect() }; - apply_moves(s, "Align", p, &ids, &moves) + let guides = guide_moves(s, p, r, h, v)?; + apply_moves(s, "Align", p, &ids, &moves, &guides) +} + +/// The selected ruler guides that Align to the key object (or key guide) moves, and where: a +/// vertical guide goes to the left edge, centre or right edge of `r` that `h` names, a horizontal +/// one to the top, centre or bottom that `v` names. The key guide stays put, and so do guides +/// when aligning to the selection or the artboard. +fn guide_moves(s: &Session, p: &Value, r: Rect, h: Option<&str>, v: Option<&str>) -> Result> { + if align_to(s, p) != Some("key") { + return Ok(vec![]); + } + let st = s.doc()?; + let at = |vertical: bool| match (vertical, h, v) { + (true, Some("left"), _) => Some(r.x0), + (true, Some("center"), _) => Some(r.center().x), + (true, Some("right"), _) => Some(r.x1), + (false, _, Some("top")) => Some(r.y0), + (false, _, Some("center")) => Some(r.center().y), + (false, _, Some("bottom")) => Some(r.y1), + _ => None, + }; + Ok(st + .selection + .guides + .iter() + .filter(|&&i| Some(i) != st.selection.key_guide) + .filter_map(|&i| Some((i, at(st.doc.guides.get(i)?.vertical)?))) + .collect()) } /// [`align`] of the selected anchor points (whole paths among them give all theirs): each point @@ -1367,8 +1428,10 @@ fn align_anchors(s: &mut Session, p: &Value, ids: &[NodeId], (h, v): (Option<&st let Some(bounds) = pts.iter().skip(1).fold(pts.first().map(|q| Rect::from_points(*q, *q)), |b, q| b.map(|b| b.union_pt(*q))) else { return ok(); }; - // shortcut: no key anchor yet, so Align To Key Object aligns to the points' bounds as Selection does. - let r = if align_to(s, p) == Some("artboard") { reference_rect(s, p, ids, false)? } else { bounds }; + // shortcut: no key anchor yet, so Align To Key Object aligns to the points' bounds as Selection does + // (or to a key guide). + let (r, along_x, along_y) = align_reference(s, p, ids, false, Some(bounds))?; + let (h, v) = (h.filter(|_| along_x), v.filter(|_| along_y)); let target = |q: Point| { let x = match h { Some("left") => r.x0, @@ -1515,7 +1578,7 @@ fn distribute(s: &mut Session, p: &Value) -> Result { (*id, if horiz { Vec2::new(delta, 0.0) } else { Vec2::new(0.0, delta) }) }) .collect(); - apply_moves(s, "Distribute", p, &ids, &moves) + apply_moves(s, "Distribute", p, &ids, &moves, &[]) } fn distribute_spacing(s: &mut Session, p: &Value) -> Result { @@ -1560,7 +1623,7 @@ fn distribute_spacing(s: &mut Session, p: &Value) -> Result { let fixed = spacing.and_then(|_| deltas.iter().find(|(id, _)| Some(*id) == key)).map_or(0.0, |k| k.1); let moves: Vec<(NodeId, Vec2)> = deltas.into_iter().map(|(id, d)| (id, if horiz { Vec2::new(d - fixed, 0.0) } else { Vec2::new(0.0, d - fixed) })).collect(); - apply_moves(s, "Distribute Spacing", p, &ids, &moves) + apply_moves(s, "Distribute Spacing", p, &ids, &moves, &[]) } fn set_bounds(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/objects_on_path.rs b/crates/engine/src/cmd/objects_on_path.rs new file mode 100644 index 0000000000..c8d07cb694 --- /dev/null +++ b/crates/engine/src/cmd/objects_on_path.rs @@ -0,0 +1,334 @@ +//! Object › Objects on Path (#2545): objects attached to a path and spread along it. +//! +//! `object.objectsOnPath.attach` puts the selected objects and a path in an Objects on Path group: +//! a group with a [`ObjectsOnPath`] record ([`vectorcraft_doc::objects_on_path`]), the path at its +//! bottom. Called without a path (Object › Objects on Path › Attach) it chooses the Objects on Path +//! tool, whose click on a path attaches the selected objects to that path. The objects go along the +//! path column by column from left to right, top to bottom in each column, spread evenly from its +//! first anchor and turned to follow it. `object.objectsOnPath.options` sets the group's Pivot and +//! Rotate, and `object.objectsOnPath.expand` makes it a plain group. +//! +//! After every edit, [`refresh`] puts the objects of each Objects on Path group that changed back +//! on its path: editing the path moves them, an object moved on its own goes back to its place, +//! objects added to or taken out of the group join the end of the path or leave the record, and +//! art that replaces an object at its index (Break Link to Symbol) keeps its place. +//! +//! Behavior: (the tool and +//! Object › Objects on Path › Attach; the order on the path, the attachment point, the distribution, +//! the objects squared to the path; Pivot and Rotate; path edits realign the objects; Expand). + +use std::collections::HashMap; +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_doc::objects_on_path::{CENTER, ObjectsOnPath, attachable_path, is_objects_on_path, place}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_geom::Rect; + +use super::edit::{roots_of, selected_roots}; +use super::*; + +/// The id of the Objects on Path tool. +pub const TOOL: &str = "objectsOnPath"; + +pub fn specs() -> Vec { + vec![ + cmd!( + "object.objectsOnPath.attach", + "Attach", + ["Object", "Objects on Path"], + None, + "{path?: id of the path to attach to (without it: choose the Objects on Path tool, whose click on a path attaches the selection to it), ids?: the objects to attach (default: the selection; the path is left out of it), pivot?: 0-8 (the reference point of each object that attaches to the path, row by row from the top left; default 4, the center), rotate?: degrees counter-clockwise from upright on the path (default 0)} put the objects and the path in an Objects on Path group: the path at the bottom, the objects spread evenly along it from its first anchor (the last one at the end of an open path) in their order on the canvas, column by column from left to right and top to bottom in each column, each turned to follow the path; editing the path moves them → {id}", + has_selection, + attach + ), + cmd!( + "object.objectsOnPath.options", + "Objects on Path Options", + [], + None, + "{ids?: Objects on Path groups or objects in them (default: the selection), pivot?: 0-8 (the reference point of each object that attaches to the path, row by row from the top left; 4: the center), rotate?: degrees counter-clockwise from upright on the path} set how the objects of the groups attach → {ids}", + has_objects_on_path, + options + ), + cmd!( + "object.objectsOnPath.expand", + "Expand", + ["Object", "Objects on Path"], + None, + "{ids?: Objects on Path groups or objects in them (default: the selection)} make the groups plain groups of the path and the objects where they are → {ids}", + has_objects_on_path, + expand + ), + ] +} + +// ---------- predicates ---------- + +/// The Objects on Path groups of `ids`: the ones among them, and the innermost one around each +/// object in one. +fn groups_of(d: &Document, ids: &[NodeId]) -> Vec { + let mut out = vec![]; + for id in ids { + let group = d.ancestry(*id).unwrap_or_default().into_iter().rev().find(|a| d.node(*a).is_some_and(is_objects_on_path)); + if let Some(g) = group + && !out.contains(&g) + { + out.push(g); + } + } + out +} + +/// The Objects on Path groups of the selection ([`groups_of`]). +fn selected_groups(s: &Session) -> Vec { + s.active().map(|st| groups_of(&st.doc, &st.selection.objects)).unwrap_or_default() +} + +/// The groups a command acts on: those of `ids` when given, otherwise those of the selection. +fn target_groups(s: &Session, p: &Value, cmd: &str) -> Result> { + if p.get("ids").is_none_or(Value::is_null) { + return Ok(selected_groups(s)); + } + let ids = checked_ids_param(s, p, "ids", cmd)?; + let groups = groups_of(&s.doc()?.doc, &ids); + if groups.is_empty() { + return Err(bad(cmd, "`ids` must name Objects on Path groups or objects in them")); + } + Ok(groups) +} + +fn has_objects_on_path(s: &Session) -> std::result::Result<(), String> { + has_selection(s)?; + if selected_groups(s).is_empty() { Err("select an Objects on Path group".into()) } else { Ok(()) } +} + +/// The Objects on Path group around `id` (not `id` itself), if any. +fn group_around(d: &Document, id: NodeId) -> Option { + d.ancestry(id).unwrap_or_default().into_iter().filter(|a| *a != id).find(|a| d.node(*a).is_some_and(is_objects_on_path)) +} + +// ---------- Attach ---------- + +/// `pivot` and `rotate` from `p`, each checked. +fn pivot_rotate(p: &Value, cmd: &str, pivot: u8, rotate: f64) -> Result<(u8, f64)> { + check_numbers(p, &["pivot", "rotate"], cmd)?; + let pivot = match p.get("pivot").filter(|v| !v.is_null()) { + None => pivot, + Some(v) => v.as_u64().filter(|n| *n <= 8).map(|n| n as u8).ok_or_else(|| bad(cmd, "`pivot` must be a whole number from 0 to 8"))?, + }; + let rotate = match p.get("rotate").and_then(Value::as_f64) { + None => rotate, + Some(r) if r.is_finite() => r, + Some(_) => return Err(bad(cmd, "`rotate` must be a finite number")), + }; + Ok((pivot, rotate)) +} + +/// `ids` in their order along the path: column by column from left to right, top to bottom in each +/// column. A column is a run of objects, taken by their left edges, that each start left of the +/// right edge of the column so far. Objects without bounds go last. Symbol instances are measured +/// by their art. +fn path_order(d: &Document, ids: &[NodeId]) -> Vec { + let symbols = d.symbol_boxes(); + let mut placed: Vec<(NodeId, Rect)> = vec![]; + let mut rest = vec![]; + for id in ids { + match d.node(*id).and_then(|n| n.geometric_bounds_with(&symbols)) { + Some(b) => placed.push((*id, b)), + None => rest.push(*id), + } + } + placed.sort_by(|a, b| a.1.x0.total_cmp(&b.1.x0)); + let mut columns: Vec<(f64, Vec<(NodeId, Rect)>)> = vec![]; + for (id, b) in placed { + match columns.last_mut() { + Some((right, column)) if b.x0 < *right => { + *right = right.max(b.x1); + column.push((id, b)); + } + _ => columns.push((b.x1, vec![(id, b)])), + } + } + let mut out = vec![]; + for (_, mut column) in columns { + column.sort_by(|a, b| a.1.y0.total_cmp(&b.1.y0)); + out.extend(column.into_iter().map(|(id, _)| id)); + } + out.extend(rest); + out +} + +/// Why the path `path` can't take objects, if it can't. +fn path_refused(d: &Document, path: NodeId) -> Option<&'static str> { + let n = d.node(path)?; + if attachable_path(n).is_none() { + return Some("pick a path to attach the objects to (not a guide, a compound path or type)"); + } + if group_around(d, path).is_some() { + return Some("the path is already in an Objects on Path group"); + } + None +} + +/// Why `n` can't be attached to a path, if it can't (the help page names graphs). +fn object_refused(d: &Document, n: &Node) -> Option<&'static str> { + if n.is_layer() { + return Some("layers can't be attached to a path: select the objects in them"); + } + if group_around(d, n.id).is_some() { + return Some("an object already on a path can't be attached again"); + } + let mut graph = false; + n.walk(&mut |c| graph |= c.extras().graph.is_some()); + graph.then_some("graphs can't be attached to a path") +} + +fn attach(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.objectsOnPath.attach"; + let Some(path) = p.get("path").filter(|v| !v.is_null()) else { + let view = s.last_view; + s.select_tool(TOOL, view)?; + return Ok(json!({ "tool": TOOL })); + }; + let path = checked_id(s, path, C)?; + let (pivot, rotate) = pivot_rotate(p, C, CENTER, 0.0)?; + let roots = match p.get("ids") { + Some(_) => roots_of(&s.doc()?.doc, checked_ids_param(s, p, "ids", C)?), + None => selected_roots(s)?, + }; + let ids: Vec = roots.into_iter().filter(|id| *id != path).collect(); + let order = { + let d = &s.doc()?.doc; + if let Some(why) = path_refused(d, path) { + return Err(bad(C, why)); + } + if ids.is_empty() { + return Err(bad(C, "select the objects to attach to the path")); + } + for id in &ids { + let n = d.node(*id).ok_or(EngineError::NoNode(*id))?; + if d.ancestry(path).unwrap_or_default().contains(id) { + return Err(bad(C, "the path can't be inside one of the objects to attach")); + } + if let Some(why) = object_refused(d, n) { + return Err(bad(C, why)); + } + } + path_order(d, &ids) + }; + let id = s.edit("Attach Objects on Path", |d, sel| { + let members: Vec = order.iter().filter_map(|id| d.node(*id).cloned()).collect(); + let rec = ObjectsOnPath::new(path, &members.iter().collect::>(), pivot, rotate); + let mut wrapped = ids.clone(); + wrapped.push(path); + let wrapped = d.paint_order(wrapped); + let id = d.alloc_id(); + d.wrap(&wrapped, |mut children| { + // The path at the bottom: the objects are drawn over it. + if let Some(i) = children.iter().position(|c| c.id == path) { + let p = children.remove(i); + children.insert(0, p); + } + let mut g = Node::new(id, NodeKind::Group { children, clip: false }); + g.extras_mut().objects_on_path = Some(Box::new(rec)); + g + })?; + place_in(d, id); + sel.set([id]); + Ok(id) + })?; + Ok(json!({ "id": id.0 })) +} + +// ---------- Options ---------- + +fn options(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.objectsOnPath.options"; + let groups = target_groups(s, p, C)?; + pivot_rotate(p, C, CENTER, 0.0)?; + s.edit("Objects on Path Options", |d, _| { + for g in &groups { + let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?; + let Some(rec) = n.extras().objects_on_path.as_deref().cloned() else { continue }; + let (pivot, rotate) = pivot_rotate(p, C, rec.pivot, rec.rotate)?; + n.extras_mut().objects_on_path = Some(Box::new(ObjectsOnPath { pivot, rotate, ..rec })); + } + Ok(()) + })?; + Ok(json!({ "ids": groups.iter().map(|g| g.0).collect::>() })) +} + +// ---------- Expand ---------- + +fn expand(s: &mut Session, p: &Value) -> Result { + let groups = target_groups(s, p, "object.objectsOnPath.expand")?; + s.edit("Expand Objects on Path", |d, sel| { + for g in &groups { + d.node_mut(*g).ok_or(EngineError::NoNode(*g))?.extras_mut().objects_on_path = None; + } + sel.set(groups.iter().copied()); + Ok(()) + })?; + Ok(json!({ "ids": groups.iter().map(|g| g.0).collect::>() })) +} + +// ---------- refresh ---------- + +/// After an edit: put the objects of every Objects on Path group that changed back on its path +/// ([`place`]), inner groups first. Only the parts of the tree that the edit changed are searched. +pub(crate) fn refresh(before: &Document, doc: &mut Document) { + let mut groups = vec![]; + changed_groups(&before.layers, &doc.layers, &mut groups); + for id in groups.iter().rev() { + follow_replacements(before, doc, *id); + place_in(doc, *id); + } +} + +/// Members of the group `id` that the edit replaced with new art at the same index keep their +/// place on the path ([`ObjectsOnPath::follow_replacements`]). +fn follow_replacements(before: &Document, doc: &mut Document, id: NodeId) { + let (Some(old), Some(new)) = (before.node(id), doc.node(id)) else { return }; + let (Some(old), Some(new)) = (old.children(), new.children()) else { return }; + let Some(mut rec) = doc.node(id).and_then(|n| n.extras().objects_on_path.as_deref().cloned()) else { return }; + let unchanged = rec.clone(); + rec.follow_replacements(old, new); + if rec != unchanged + && let Some(n) = doc.node_mut(id) + { + n.extras_mut().objects_on_path = Some(Box::new(rec)); + } +} + +/// [`place`] the Objects on Path group `id` of `doc`, measuring symbol instances by their art. +fn place_in(doc: &mut Document, id: NodeId) { + let Some(n) = doc.node(id) else { return }; + let mut g = n.clone(); + if place(&mut g, &doc.symbol_boxes()) + && let Some(slot) = doc.node_mut(id) + { + *slot = g; + } +} + +/// The Objects on Path groups among `after` and inside them that are not the same nodes as before +/// (`before`: the same list before the edit), outer ones first. +fn changed_groups(before: &[Arc], after: &[Arc], out: &mut Vec) { + let mut by_id: Option>> = None; + for (i, a) in after.iter().enumerate() { + let b = match before.get(i) { + Some(b) if b.id == a.id => Some(b), + _ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(), + }; + if b.is_some_and(|b| Arc::ptr_eq(b, a)) { + continue; + } + if is_objects_on_path(a) { + out.push(a.id); + } + if let Some(children) = a.children() { + changed_groups(b.and_then(|b| b.children()).map_or(&[], Vec::as_slice), children, out); + } + } +} diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 97b83838c6..7a671478a9 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -42,6 +42,15 @@ pub fn specs() -> Vec { has_doc, set_handle ), + cmd!( + "path.moveAnchor", + "Move Anchor Point", + [], + None, + "{id, subpath?, anchor, x, y} move one anchor to (x, y), its handles with it", + has_doc, + move_anchor + ), cmd!( "path.setAnchors", "Set Anchors", @@ -65,7 +74,7 @@ pub fn specs() -> Vec { "Join", ["Object", "Path"], Some("Cmd+J"), - "{ids?: [path, path] (default: the selected paths), ends?: [\"first\"|\"last\", \"first\"|\"last\"] (which end of each path to join, as the Pen joins them; default: the nearest pair)} join two open paths into one (the first keeps its id, selected), or close a single open path; without ids, direct-selected anchors lying on one another along a path merge into one anchor instead", + "{ids?: [path, path] (default: the selected paths), ends?: [\"first\"|\"last\", \"first\"|\"last\"] (which end of each path to join, as the Pen joins them; default: the nearest pair), to?: \"corner\"|\"smooth\" (the joined anchor: corner retracts both handles, smooth pulls handles in line with the neighbours)} join two open paths into one (the first keeps its id, selected), or close a single open path; without ids, direct-selected anchors lying on one another along a path merge into one anchor instead", has_selection, join ), @@ -230,6 +239,22 @@ fn set_handle(s: &mut Session, p: &Value) -> Result { ok() } +/// `path.moveAnchor`: one anchor to (x, y), its handles keeping their offsets (the Anchor Point +/// tool's Shift-drag). +fn move_anchor(s: &mut Session, p: &Value) -> Result { + let id = id_param(p, "id").ok_or_else(|| bad("path.moveAnchor", "missing id"))?; + let si = usize_opt(p, "subpath", "path.moveAnchor")?.unwrap_or(0); + let ai = p.get("anchor").and_then(Value::as_u64).ok_or_else(|| bad("path.moveAnchor", "missing anchor"))? as usize; + let pos = Point::new(f64_req(p, "x", "path.moveAnchor")?, f64_req(p, "y", "path.moveAnchor")?); + s.edit("Move", |d, _| { + let path = path_mut(d, id)?; + let a = path.anchor_mut(si, ai).ok_or_else(|| EngineError::Other("no such anchor".into()))?; + *a = a.transform(vectorcraft_geom::Affine::translate(pos - a.p)); + Ok(()) + })?; + ok() +} + fn set_anchors(s: &mut Session, p: &Value) -> Result { let id = id_param(p, "id").ok_or_else(|| bad("path.setAnchors", "missing id"))?; let subs = p.get("subpaths").and_then(Value::as_array).ok_or_else(|| bad("path.setAnchors", "missing subpaths"))?; @@ -311,10 +336,19 @@ fn end_points(sp: &SubPath) -> Option<(Point, Point)> { Some((sp.anchors.first()?.p, sp.anchors.last()?.p)) } +/// Corner or smooth on an anchor a join leaves behind. +fn join_point(sp: &mut SubPath, ai: usize, smooth: bool) { + if smooth { + sp.smooth_anchor(ai); + } else if let Some(a) = sp.anchors.get_mut(ai) { + a.retract(); + } +} + /// Merge each run of `picked` neighbours of `sp` that lie on one another into one anchor, which /// keeps the first one's incoming handle and the last one's outgoing handle. Returns how many /// anchors went. -fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool) -> usize { +fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind: Option) -> usize { let same = |a: &Anchor, b: &Anchor| a.p.distance(b.p) < 1e-6; let before = sp.anchors.len(); // The closing pair of a closed path first: taking the last anchor moves no other index. @@ -327,6 +361,9 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool) -> usize { { first.h_in = last.h_in; sp.anchors.pop(); + if let Some(smooth) = join_kind { + join_point(sp, 0, smooth); + } } // Back to front, so the indices `picked` knows stay true for the anchors still to visit. for i in (1..sp.anchors.len()).rev() { @@ -337,6 +374,9 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool) -> usize { { a.h_out = b.h_out; sp.anchors.remove(i); + if let Some(smooth) = join_kind { + join_point(sp, i - 1, smooth); + } } } before - sp.anchors.len() @@ -344,6 +384,12 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool) -> usize { fn join(s: &mut Session, p: &Value) -> Result { const C: &str = "path.join"; + let join_kind = match p.get("to").and_then(Value::as_str) { + None => None, + Some("smooth") => Some(true), + Some("corner") => Some(false), + Some(_) => return Err(bad(C, "`to` must be \"corner\" or \"smooth\"")), + }; let ids = match ids_param(p, "ids") { Some(ids) => { let st = s.doc()?; @@ -361,7 +407,8 @@ fn join(s: &mut Session, p: &Value) -> Result { let mut merged = vec![]; for (id, picked) in &st.selection.anchors { let Some(mut path) = st.doc.node(*id).and_then(|n| n.path_data()).cloned() else { continue }; - let n: usize = path.subpaths.iter_mut().enumerate().map(|(si, sp)| merge_coincident(sp, |ai| picked.contains(&(si, ai)))).sum(); + let n: usize = + path.subpaths.iter_mut().enumerate().map(|(si, sp)| merge_coincident(sp, |ai| picked.contains(&(si, ai)), join_kind)).sum(); if n > 0 { merged.push((*id, path)); } @@ -401,6 +448,11 @@ fn join(s: &mut Session, p: &Value) -> Result { && let Some(first) = sp.anchors.first_mut() { first.h_in = last.h_in; + // Closed first, so the merged anchor smooths between both its neighbours. + sp.closed = true; + if let Some(smooth) = join_kind { + join_point(sp, 0, smooth); + } } sp.closed = true; Ok(()) @@ -433,6 +485,7 @@ fn join(s: &mut Session, p: &Value) -> Result { if ry { y.reverse(); } + let junction = x.anchors.len() - 1; if let (Some(xe), Some(ys)) = (x.anchors.last().map(|a| a.p), y.anchors.first().map(|a| a.p)) && xe.distance(ys) < 1e-6 { @@ -442,6 +495,9 @@ fn join(s: &mut Session, p: &Value) -> Result { } } x.anchors.extend(y.anchors); + if let Some(smooth) = join_kind { + join_point(&mut x, junction, smooth); + } pa.subpaths[sa] = x; d.remove(b)?; sel.set([a]); @@ -602,7 +658,6 @@ fn without_anchors(sp: SubPath, removed: &BTreeSet) -> Vec { if gone.is_empty() { return vec![sp]; } - let keep = |anchors: Vec| (anchors.len() >= 2).then(|| SubPath::new(anchors, false)); let mut runs: Vec> = vec![]; let mut run = vec![]; for (i, anchor) in sp.anchors.into_iter().enumerate() { @@ -630,7 +685,7 @@ fn without_anchors(sp: SubPath, removed: &BTreeSet) -> Vec { } else if !run.is_empty() { runs.push(run); } - runs.into_iter().filter_map(keep).collect() + runs.into_iter().filter_map(open_run).collect() } /// Remove connections, splitting open/closed contours into their surviving open runs. diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index fe27f9424b..5eac00532e 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -130,7 +130,7 @@ pub fn specs() -> Vec { "Simplify…", ["Object", "Path"], None, - "{tolerance?: pt (1), cornerAngle?: deg (30), straightLines?: bool} → {ids, before, after} anchor counts", + "{tolerance?: pt (1), level?: 0..100 (the Simplify slider, in place of tolerance: 0 fewest anchor points, 50 is 1 pt, every 10 levels halves or doubles it), auto?: bool (Auto-Simplify: the lowest level whose tolerance is at most 1/400 of the selection's longer side, or 100 when that side is under 12.5 pt), cornerAngle?: deg (30), straightLines?: bool} → {ids, before, after} anchor counts, and the level used with level or auto", has_selection, simplify ), @@ -800,13 +800,29 @@ fn edit_paths(s: &mut Session, label: &str, f: impl Fn(&PathData) -> PathData) - } fn simplify(s: &mut Session, p: &Value) -> Result { + // With auto, the slider's level is Auto-Simplify's for the selection's size; otherwise it is the level given. + let level = if bool_or(p, "auto", false) { + let roots = selected_roots(s)?; + let size = s.doc()?.doc.bounds_of(&roots, false).map_or(0.0, |b| b.width().max(b.height())); + Some(po::auto_simplify_level(size)) + } else { + num_param(p, "level").map(|l| if l.is_finite() { l.round().clamp(0.0, 100.0) } else { po::SIMPLIFY_LEVEL }) + }; + let tolerance = match level { + Some(l) => po::simplify_level_tolerance(l), + None => len_param(p, "tolerance").unwrap_or(1.0), + }; let opts = po::SimplifyOptions { - tolerance: len_param(p, "tolerance").unwrap_or(1.0).clamp(1e-4, 1e4), + tolerance: tolerance.clamp(1e-4, 1e4), corner_angle_deg: num_param(p, "cornerAngle").unwrap_or(30.0).clamp(0.0, 180.0), straight_lines: bool_or(p, "straightLines", false), }; let (ids, before, after) = edit_paths(s, "Simplify", |path| po::simplify_with(path, &opts))?; - Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "before": before, "after": after })) + let mut out = json!({ "ids": ids.iter().map(|i| i.0).collect::>(), "before": before, "after": after }); + if let Some(l) = level { + out["level"] = json!(l); + } + Ok(out) } fn add_anchor_points(s: &mut Session, _: &Value) -> Result { diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index b38d629097..f7b62f9503 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -5,12 +5,13 @@ //! preference, and listed with `plugin.list` / `plugin.info`. Object filters run //! with `plugin.run` on the selected paths and compound paths (one undo step, transactional: a //! plug-in that fails leaves the document untouched); live-effect plug-ins are applied like any -//! effect (`effect.apply {effect: "plugin."}`) and drawn by `vectorcraft-effects`. +//! effect (`effect.apply {effect: "plugin."}`) and drawn by `vectorcraft-effects`; exporters +//! add a file format that `document.export` writes (`fileio::plugin_formats`). use std::sync::{Arc, Mutex}; use serde_json::{Map, Value, json}; -use vectorcraft_plugins::{Kind, Plugin, effect, objects, registry}; +use vectorcraft_plugins::{Kind, Plugin, effect, export, objects, registry}; use super::*; @@ -27,8 +28,13 @@ pub fn describe(p: &Plugin) -> Value { "params": m.params_doc(), "paramsSchema": serde_json::to_value(m).ok().and_then(|v| v.get("params").cloned()), "size": p.size(), "source": p.source(), }); - if m.kind == Kind::Effect { - v["effect"] = json!(effect::effect_id(&m.id)); + match m.kind { + Kind::Effect => v["effect"] = json!(effect::effect_id(&m.id)), + Kind::Exporter => { + v["format"] = json!(export::format_id(&m.id)); + v["extensions"] = json!(m.extensions); + } + Kind::Filter => {} } v } @@ -56,8 +62,14 @@ fn run(s: &mut Session, p: &Value) -> Result { const C: &str = "plugin.run"; let plugin = plugin_by_id(C, p)?; let m = plugin.manifest(); - if m.kind != Kind::Filter { - return Err(bad(C, format!("`{}` is a live effect: apply it with effect.apply {{\"effect\": \"{}\"}}", m.id, effect::effect_id(&m.id)))); + match m.kind { + Kind::Filter => {} + Kind::Effect => { + return Err(bad(C, format!("`{}` is a live effect: apply it with effect.apply {{\"effect\": \"{}\"}}", m.id, effect::effect_id(&m.id)))); + } + Kind::Exporter => { + return Err(bad(C, format!("`{}` is an exporter: export with document.export {{\"format\": \"{}\"}}", m.id, export::format_id(&m.id)))); + } } // Bad parameters fail before anything runs. let mut params = Value::Object(m.resolve_params(&plugin_params(p)).map_err(|e| bad(C, e.to_string()))?); @@ -206,7 +218,7 @@ pub fn specs() -> Vec { "List Plug-ins", [], None, - "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), size, source}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's format id, plugin., for document.export, and its file extensions), size, source}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null}", always, list ), diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index a6fb02140f..2197877e36 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -66,7 +66,7 @@ pub fn specs() -> Vec { "Cancel Key Object", [], None, - "{id?: a selected top-level object (not a layer, a compound-path member or an object inside another selected object); one of two or more (the Selection tool: a click on one object of a selection of several; on the key again: no id)} the key object Align aligns to and Distribute Spacing spaces from; without `id` it cancels the key, as does a selection that holds only the key and objects inside it (one object, or a group key and its own members); any other id is an error that leaves the key as it was → {key} (the resulting key object, or null)", + "{id?: a selected top-level object (not a layer, a compound-path member or an object inside another selected object); one of two or more or the only one with ruler guides selected (the Selection tool: a click on one object of a selection of several, or of one with guides; on the key again: no id), guide?: index (a selected ruler guide, guide.list, with one or more objects selected: the Selection tool's click on a selected guide; Align lines the objects up on it and the guide stays put)} the key object Align aligns to and Distribute Spacing spaces from; without `id` or `guide` it cancels the key, as does a selection that holds only the key and objects inside it (one object, or a group key and its own members) and no ruler guide, or a key guide with no object selected or taken out of the selection; any other id or guide is an error that leaves the key as it was → {key, guide?} (the resulting key object, or null; guide: the key guide, left out without one)", has_doc, key ), @@ -368,6 +368,29 @@ fn selection_result(s: &Session) -> Result { fn key(s: &mut Session, p: &Value) -> Result { let id = p.get("id").map(|value| checked_id(s, value, "select.key")).transpose()?; + let guide = match p.get("guide").filter(|v| !v.is_null()) { + Some(v) => { + Some(v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad("select.key", "`guide` must be a guide index (guide.list)"))?) + } + None => None, + }; + if let Some(g) = guide { + let sel = &s.doc()?.selection; + if id.is_some() { + return Err(bad("select.key", "give `id` or `guide`, not both")); + } + if !sel.guides.contains(&g) { + return Err(bad("select.key", format!("guide {g} is not selected"))); + } + if sel.is_empty() { + return Err(bad("select.key", "select objects to align to the guide")); + } + s.select(|_, sel| { + sel.key = None; + sel.key_guide = Some(g); + })?; + return key_result(s); + } if let Some(id) = id { let st = s.doc()?; // A selected top-level object is the only top-level object among the selected ones of @@ -377,8 +400,21 @@ fn key(s: &mut Session, p: &Value) -> Result { return Err(bad("select.key", format!("object {id} is not a selected top-level object"))); } } - s.select(|_, sel| sel.key = id)?; - Ok(json!({ "key": s.doc()?.selection.key })) + s.select(|_, sel| { + sel.key = id; + sel.key_guide = None; + })?; + key_result(s) +} + +/// `{key}`, with `guide` when a guide is the key. +fn key_result(s: &Session) -> Result { + let sel = &s.doc()?.selection; + let mut out = json!({ "key": sel.key }); + if let Some(g) = sel.key_guide { + out["guide"] = json!(g); + } + Ok(out) } /// `[[subpath, anchor]…]` anchor references of `cmd`: a malformed entry fails rather than being diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index 3438579a29..f5d4b74a1e 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -272,7 +272,14 @@ impl Libraries { .map(|e| (e.path.clone(), e.lib.clone())) .ok_or_else(|| bad(cmd, format!("`{id}` isn't a loaded library")))?; let (file, bytes) = match source.filter(|p| L::EXTS.contains(&extension(p).as_str())) { - Some(p) => (file_name(&p), read_file(&p)?), + Some(p) => { + let ext = extension(&p); + let base = file_name(&p); + // Color books (.acb) name the tab from the book title inside the file; a sandbox + // copy of an import often lands as tmp….tmp.acb (#2996). + let file = if ext == "acb" || temporary_library_file_name(&base) { library_file_name(lib.name(), &ext) } else { base }; + (file, read_file(&p)?) + } None => (library_file_name(lib.name(), ext), encode(&lib)?), }; self.rescan(); @@ -302,6 +309,12 @@ impl Libraries { } } +/// A library file name that looks like a host temporary (e.g. macOS `tmp1F2C.tmp.acb`). +fn temporary_library_file_name(name: &str) -> bool { + let lower = name.to_ascii_lowercase(); + lower.contains(".tmp.") +} + /// The file name of library `name` with extension `ext`: characters file systems reject become /// `-`, and dots and spaces at either end are dropped. A name with nothing left is `Library`. pub fn library_file_name(name: &str, ext: &str) -> String { diff --git a/crates/engine/src/cmd/variablecmds.rs b/crates/engine/src/cmd/variablecmds.rs index 78e0802836..2a1fba843c 100644 --- a/crates/engine/src/cmd/variablecmds.rs +++ b/crates/engine/src/cmd/variablecmds.rs @@ -459,7 +459,7 @@ fn dataset_list(s: &mut Session, _p: &Value) -> Result { fn apply_dataset(s: &mut Session, name: &str) -> Result { const C: &str = "dataset.select"; - let (applied, skipped, mut typed) = s.edit("Apply Data Set", |d, sel| { + let (applied, skipped, mut typed, bound) = s.edit("Apply Data Set", |d, sel| { let ds = d.variables.dataset(name).cloned().ok_or_else(|| bad(C, format!("no dataset named `{name}`")))?; // One object may be driven by several variables; walk them in definition order, so two // text variables on the same object land the later one's value and both are counted. @@ -467,6 +467,8 @@ fn apply_dataset(s: &mut Session, name: &str) -> Result { for v in &d.variables.variables { pairs.extend(d.variables.objects_of(&v.name).into_iter().map(|id| (id, v.name.clone()))); } + // Whether an object is bound to a variable that this row has a value for (the reply's `warning`). + let bound = pairs.iter().any(|(_, var)| ds.values.contains_key(var)); let mut applied = 0usize; let mut skipped = 0usize; // Collects the type objects whose text the row rewrote, for the reply's `overflow`. @@ -514,12 +516,18 @@ fn apply_dataset(s: &mut Session, name: &str) -> Result { d.variables.active_dataset = Some(name.to_string()); // Every selected object left hidden or locked, such as one the row hid, is deselected. sel.deselect_uneditable(d); - Ok((applied, skipped, typed)) + Ok((applied, skipped, typed, bound)) })?; // Two text variables on one object rewrite it twice; it is named once. typed.sort_unstable(); typed.dedup(); - Ok(super::typecmd::with_overflow(s, &typed, json!({"name": name, "applied": applied, "skipped": skipped}))) + let mut out = super::typecmd::with_overflow(s, &typed, json!({"name": name, "applied": applied, "skipped": skipped})); + // A row with no value for any bound variable applies nothing. The reply then carries a + // `warning`, which the app shows in its status bar. + if !bound { + out["warning"] = json!(format!("nothing in data set {name} was applied: no object is bound to a variable it has a value for")); + } + Ok(out) } fn dataset_select(s: &mut Session, p: &Value) -> Result { @@ -1037,7 +1045,7 @@ pub fn specs() -> Vec { "Select Data Set", ["Window", "Variables"], None, - "{name} apply a dataset in one undo step, deselecting every selected object left hidden or locked (the key object too) → {applied, skipped, overflow?: [id…] (area type and type on a path whose text it rewrote and that no longer fits; left out when all fits)}", + "{name} apply a dataset in one undo step, deselecting every selected object left hidden or locked (the key object too) → {applied, skipped, overflow?: [id…] (area type and type on a path whose text it rewrote and that no longer fits; left out when all fits), warning? (when no object is bound to a variable that the dataset has a value for, so nothing was applied)}", has_doc, dataset_select ), diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 1850e59228..20db02bceb 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -258,6 +258,8 @@ fn document_base(s: &Session) -> Value { "target": st.selection.target.map(|t| t.0), // The key object Align aligns to and Distribute Spacing spaces from (`select.key`). "key": st.selection.key.map(|k| k.0), + // The ruler guide that is the key instead (`select.key {guide}`): an index into `guide.list`. + "keyGuide": st.selection.key_guide, "history": st.history.undo.iter().map(|h| h.label.clone()).collect::>(), "redo": st.history.redo.iter().rev().map(|h| h.label.clone()).collect::>(), "objects": d.node_count(), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 50ed6976ea..4c848ecbc6 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -36,6 +36,7 @@ pub use journal::Journal; pub use tooling::{UiRequest, ViewInfo}; pub use vectorcraft_doc as doc; pub use vectorcraft_doc::cancel; +pub use vectorcraft_pathops::{SIMPLIFY_LEVEL, simplify_level_tolerance}; pub use vectorcraft_tools as tools; #[derive(Debug, thiserror::Error)] @@ -773,6 +774,11 @@ pub(crate) fn deselect_guides(d: &Document, sel: &mut Selection) -> bool { sel.remove(id); } sel.guides.clear(); + sel.key_guide = None; + // A key object kept only for the guides to line up on goes with them. + if sel.key.is_some_and(|k| sel.objects.iter().all(|o| *o == k)) { + sel.key = None; + } any } @@ -1348,6 +1354,8 @@ impl Session { // Placed documents are read by the native format's loader. vectorcraft_doc::placed_document::set_loader(cmd::place::document::read_document); vectorcraft_doc::placed_document::set_file_reader(cmd::place::document::read_file_again); + // Clicks find an image's own fills and strokes where their effects draw them. + vectorcraft_doc::hit::set_image_paint(vectorcraft_render::effects::image_paint); Self { docs: vec![], active: None, @@ -1702,14 +1710,17 @@ impl Session { let before = st.doc.clone(); let before_sel = st.selection.clone(); let doc = Arc::make_mut(&mut st.doc); - // Dimensions follow the art they measure. + // Objects attached to a path follow it, and dimensions follow the art they measure. let result = match f(doc, &mut st.selection).and_then(|v| { + cmd::objects_on_path::refresh(&before, doc); cmd::dimension::refresh(&before, doc)?; Ok(v) }) { Ok(v) => match cmd::shaper::refresh(&before, Arc::make_mut(&mut st.doc)) { Err(e) => Err(e), Ok(()) => { + // Attached Shaper groups whose art was rebuilt go back on their path. + cmd::objects_on_path::refresh(&before, Arc::make_mut(&mut st.doc)); // Inline graphics in text follow their symbols. cmd::inline::refresh(&before, Arc::make_mut(&mut st.doc)); // Text Wrap: area type follows its wrap objects; then threads re-flow. @@ -2143,6 +2154,8 @@ mod tests_intertwine; #[cfg(test)] mod tests_journal; #[cfg(test)] +mod tests_keyguide; +#[cfg(test)] mod tests_knockout; #[cfg(test)] mod tests_labspots; @@ -2185,6 +2198,8 @@ mod tests_newart; #[cfg(test)] mod tests_newdoc; #[cfg(test)] +mod tests_objects_on_path; +#[cfg(test)] mod tests_objexpand; #[cfg(test)] mod tests_opacitymask; diff --git a/crates/engine/src/tests_clipflavours.rs b/crates/engine/src/tests_clipflavours.rs index 759f0f83a7..173bb43537 100644 --- a/crates/engine/src/tests_clipflavours.rs +++ b/crates/engine/src/tests_clipflavours.rs @@ -7,7 +7,7 @@ use vectorcraft_geom::Point; use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; use super::*; -use crate::cmd::clipboard::{BITMAP, EPS, FILE_HEAD, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour}; +use crate::cmd::clipboard::{AI, BITMAP, EPS, FILE_HEAD, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour}; fn session() -> Session { let mut s = Session::new(); @@ -241,7 +241,8 @@ fn copied_ai_files_paste_as_the_pdf_or_postscript_inside() { let ps = b"%!PS-Adobe-3.0\n%%BoundingBox: 0 0 40 40\n%%EndComments\n1 0 0 setrgbcolor\nnewpath 0 0 moveto 40 0 lineto 40 40 lineto closepath fill\nshowpage\n"; let of = |name: &str, bytes: &[u8]| file_flavour(name, &bytes[..bytes.len().min(FILE_HEAD)], &PASTE_ORDER); for name in ["art.ai", "art.ait", "ART.AI"] { - assert_eq!(of(name, &pdf), Some(PDF), "{name}"); + // Asked for as PDF; Paste reads it from its editing data (tests_aiimport). + assert_eq!(of(name, &pdf), Some(AI), "{name}"); assert_eq!(of(name, ps), Some(EPS), "{name}"); } // Neither PDF nor PostScript: nothing to paste, whatever the name says. @@ -315,6 +316,53 @@ fn copy_offers_flavours_by_the_preferences() { assert_eq!((f[0].data.as_slice(), f[1].mime), (b"Words".as_slice(), SVG)); } +/// A PNG of `side` × `side` noise pixels: noise keeps it about `side² × 3` bytes, as a photo. +fn noise_png(side: u32) -> Vec { + let mut x: u32 = 0x9e37_79b9; + let px = (0..side * side * 3) + .map(|_| { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + (x >> 24) as u8 + }) + .collect(); + let mut out = vec![]; + image::RgbImage::from_raw(side, side, px).unwrap().write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +/// #2213: a placed photo in the plain-text flavour made every paste read megabytes of SVG back +/// through the system clipboard. Past 1 MiB of embedded images the SVG goes out under its own type +/// and the PNG only; a small picture, vector art of any size and type keep their text. +#[test] +fn a_copy_with_a_large_image_offers_no_svg_text() { + let mut s = session(); + let mimes = |s: &Session| s.clipboard_flavours().iter().map(|f| f.mime).collect::>(); + for (side, text) in [(700, false), (64, true)] { + let png = noise_png(side); + assert_eq!(png.len() > 1 << 20, !text, "{} bytes", png.len()); + run(&mut s, "clipboard.importImage", json!({"dataBase64": vectorcraft_format::base64_encode(&png)})); + run(&mut s, "edit.paste", json!({})); + run(&mut s, "edit.copy", json!({})); + let want: &[&str] = if text { &[TEXT, SVG, PNG] } else { &[SVG, PNG] }; + assert_eq!(mimes(&s), want, "{side} px"); + assert_eq!(run(&mut s, "clipboard.flavours", json!({}))["flavours"], json!(want), "{side} px"); + // The SVG still embeds the picture, for apps that read it. + let svg = s.clipboard_flavours().into_iter().find(|f| f.mime == SVG).unwrap(); + assert!(String::from_utf8_lossy(&svg.data).contains("data:image/png;base64,")); + run(&mut s, "edit.clear", json!({})); + } + // Vector art of more than 1 MiB of SVG keeps its text: only embedded images count. + let rects: String = + (0..30_000).map(|i| format!(r##""##, i % 400, i / 100, i * 977)).collect(); + run(&mut s, "clipboard.importSvg", json!({"svg": format!(r#"{rects}"#)})); + run(&mut s, "edit.paste", json!({})); + run(&mut s, "edit.copy", json!({})); + let f = s.clipboard_flavours(); + assert!(f[0].mime == TEXT && f[0].data.len() > 1 << 20, "{} bytes of text", f[0].data.len()); +} + /// The Type tool pastes the text it copied with its formatting, unless pasted text is kept plain. fn paste_copied_range(plain: bool) -> f64 { let mut s = session(); diff --git a/crates/engine/src/tests_containers.rs b/crates/engine/src/tests_containers.rs index 62abd07d49..003c8a0f35 100644 --- a/crates/engine/src/tests_containers.rs +++ b/crates/engine/src/tests_containers.rs @@ -1,5 +1,5 @@ -//! Group, layer and type appearance through commands: their own fills, strokes and effects, the -//! Contents (Characters) slot, `target: "contents"`, Target Contents and effects on layers. +//! Group, layer, type and image appearance through commands: their own fills, strokes and effects, +//! the Contents (Characters) slot, `target: "contents"`, Target Contents and effects on layers. use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; @@ -161,6 +161,134 @@ fn type_with_an_inline_graphic_stays_type_when_its_own_stroke_has_an_effect() { assert!(matches!(baked.node(t).unwrap().kind, NodeKind::Text(_))); } +/// A selected 30×30 red image placed with its frame from (50, 50) to (80, 80). +fn image(s: &mut Session) -> NodeId { + let mut png = vec![]; + image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let r = run(s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [65, 65]})); + NodeId(r["ids"][0].as_u64().unwrap()) +} + +#[test] +fn new_image_fills_and_strokes_go_below_the_image() { + let mut s = session(); + let im = image(&mut s); + run(&mut s, "appearance.addStroke", json!({})); + run(&mut s, "appearance.addFill", json!({})); + // Each lands right below the Contents row: [stroke, fill | image]. + let ap = node(&s, im).appearance; + assert!(!ap.items[0].is_fill() && ap.items[1].is_fill() && ap.contents_at() == 2, "{ap:?}"); + assert_eq!(run(&mut s, "appearance.moveItem", json!({"from": "contents", "to": 1}))["contents"], 1); + assert_eq!(node(&s, im).appearance.contents_at(), 1); + // The active row above the image stays active when a new item goes in below it. + run(&mut s, "appearance.setActiveItem", json!({"index": 1})); + run(&mut s, "appearance.addStroke", json!({})); + assert_eq!(s.appearance_item(), Some(2)); + assert!(node(&s, im).appearance.items[2].is_fill()); +} + +#[test] +fn an_images_stroke_with_outline_object_draws_exports_and_expands_along_its_frame() { + let mut s = session(); + let im = image(&mut s); + run(&mut s, "appearance.addStroke", json!({})); + run(&mut s, "appearance.setItem", json!({"index": 0, "weight": 4, "color": "#000000"})); + // Without an effect the stroke draws nothing, and Use Preview Bounds measures the frame. + assert_eq!(pixel(&s, 49, 65), [255; 4]); + s.prefs.use_preview_bounds = true; + assert_eq!(s.transform_bounds(&[im]), Some(vectorcraft_geom::Rect::new(50.0, 50.0, 80.0, 80.0))); + assert!(s.execute("effect.expandAppearance", &json!({})).is_err()); + run(&mut s, "effect.apply", json!({"effect": "path.outlineObject", "item": 0})); + // Under the image, the stroke's outer 2 pt shows. + assert_eq!((pixel(&s, 48, 65), pixel(&s, 49, 65), pixel(&s, 51, 65)), ([0, 0, 0, 255], [0, 0, 0, 255], RED)); + assert_eq!(pixel(&s, 47, 65), [255; 4]); + // SVG and PDF hold the image and the frame stroked 4 pt. + let doc = s.doc().unwrap().doc.clone(); + let svg = vectorcraft_svg::export(&doc, &Default::default()); + assert!(svg.contains(" Vec { + let v = ViewInfo::default(); + s.select_tool("selection", v).unwrap(); + for k in [vectorcraft_tools::PointerKind::Down, vectorcraft_tools::PointerKind::Up] { + s.pointer(&vectorcraft_tools::PointerEvent::new(k, x, y), v).unwrap(); + } + s.active().unwrap().selection.objects.clone() +} + +#[test] +fn a_click_on_an_images_stroke_or_fill_outside_its_frame_selects_the_image() { + let mut s = session(); + let im = image(&mut s); + // A 4 pt stroke 12 pt outside the frame: it paints from x 36 to 40, the frame starts at 50. + run(&mut s, "appearance.addStroke", json!({})); + run(&mut s, "appearance.setItem", json!({"index": 0, "weight": 4, "color": "#000000"})); + run(&mut s, "effect.apply", json!({"effect": "path.outlineObject", "item": 0})); + run(&mut s, "effect.apply", json!({"effect": "path.offsetPath", "params": {"offset": 12}, "item": 0})); + assert_eq!(pixel(&s, 38, 65), [0, 0, 0, 255]); + run(&mut s, "select.none", json!({})); + assert_eq!(click(&mut s, 38.0, 65.0), [im]); + // Between the stroke and the frame, and outside the stroke, nothing paints. + run(&mut s, "select.none", json!({})); + assert!(click(&mut s, 45.0, 65.0).is_empty()); + assert!(click(&mut s, 30.0, 65.0).is_empty()); + // A fill that Convert to Shape makes 9 pt larger than the frame on each side. + run(&mut s, "select.set", json!({"ids": [im.0]})); + run(&mut s, "appearance.addFill", json!({})); + run(&mut s, "paint.setFill", json!({"color": "#00ff00", "item": 1})); + run(&mut s, "effect.apply", json!({"effect": "convertToShape.rectangle", "item": 1})); + assert_eq!(pixel(&s, 44, 65), GREEN); + run(&mut s, "select.none", json!({})); + assert_eq!(click(&mut s, 44.0, 65.0), [im]); + // In a group, the stroke selects the group. + let r = id_of(&run(&mut s, "shape.rectangle", json!({"x": 120, "y": 120, "width": 20, "height": 20}))); + run(&mut s, "select.set", json!({"ids": [im.0, r.0]})); + let g = id_of(&run(&mut s, "object.group", json!({}))); + run(&mut s, "select.none", json!({})); + assert_eq!(click(&mut s, 38.0, 65.0), [g]); +} + +#[test] +fn a_click_on_the_copy_of_an_images_stroke_that_a_transform_effect_makes_selects_the_image() { + let mut s = session(); + let im = image(&mut s); + run(&mut s, "appearance.addStroke", json!({})); + run(&mut s, "appearance.setItem", json!({"index": 0, "weight": 4, "color": "#000000"})); + run(&mut s, "effect.apply", json!({"effect": "path.outlineObject", "item": 0})); + // One copy 60 pt to the right: its stroke paints from x 138 to 142 on the right. + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": {"moveH": 60, "copies": 1}, "item": null})); + assert_eq!(pixel(&s, 141, 65), [0, 0, 0, 255]); + run(&mut s, "select.none", json!({})); + assert_eq!(click(&mut s, 141.0, 65.0), [im]); + run(&mut s, "select.none", json!({})); + assert!(click(&mut s, 147.0, 65.0).is_empty()); +} + #[test] fn group_appearance_round_trips_and_expands() { let mut s = session(); diff --git a/crates/engine/src/tests_css.rs b/crates/engine/src/tests_css.rs index 24976e1e69..8a39eb059f 100644 --- a/crates/engine/src/tests_css.rs +++ b/crates/engine/src/tests_css.rs @@ -48,7 +48,7 @@ fn type_gives_font_properties_and_gradients_css_gradients() { let mut s = session(); let t = run(&mut s, "text.create", json!({"x": 20, "y": 50, "text": "Title", "size": 24}))["id"].as_u64().unwrap(); let text = css(&run(&mut s, "css.selection", json!({"ids": [t]}))).to_string(); - for decl in ["font-family: 'Source Sans 3';", "font-size: 24px;", "color: #"] { + for decl in ["font-family: 'Source Sans 3', sans-serif;", "font-size: 24px;", "color: #"] { assert!(text.contains(decl), "{decl} in {text}"); } run(&mut s, "shape.rectangle", json!({"x": 0, "y": 100, "width": 100, "height": 50})); diff --git a/crates/engine/src/tests_draw2.rs b/crates/engine/src/tests_draw2.rs index 88c9c27bfa..4fd0df21b5 100644 --- a/crates/engine/src/tests_draw2.rs +++ b/crates/engine/src/tests_draw2.rs @@ -983,6 +983,24 @@ fn set_handle_refuses_a_subpath_that_is_not_a_whole_number() { edits_the_subpath_given(&mut s, "path.setHandle", &p, id); } +#[test] +fn move_anchor_takes_its_handles_along_and_refuses_a_subpath_that_is_not_a_whole_number() { + let mut s = session(); + let id = two_subpaths(&mut s); + let p = json!({"id": id.0, "anchor": 0, "x": 140, "y": 250}); + refuses_an_index_that_is_not_whole(&mut s, "path.moveAnchor", &p, "subpath"); + edits_the_subpath_given(&mut s, "path.moveAnchor", &p, id); + // The anchor lands on (x, y) and its handles keep their offsets from it. + s.execute("path.setHandle", &json!({"id": id.0, "anchor": 0, "which": "out", "x": 30, "y": 40})).unwrap(); + let a = path(&s, id).subpaths[0].anchors[0]; + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": a.p.x + 15.0, "y": a.p.y - 5.0})).unwrap(); + let b = path(&s, id).subpaths[0].anchors[0]; + assert_eq!(b.p, a.p + vectorcraft_geom::Vec2::new(15.0, -5.0)); + assert_eq!(b.h_out - b.p, a.h_out - a.p); + assert_eq!(b.h_in - b.p, a.h_in - a.p); + assert!(s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 99, "x": 0, "y": 0})).is_err()); +} + #[test] fn insert_anchor_refuses_a_subpath_that_is_not_a_whole_number() { let mut s = session(); @@ -1828,11 +1846,36 @@ fn join_takes_the_paths_and_the_ends_to_join() { json!({"ids": [a.0, 999]}), json!({"ids": [a.0, r.0], "ends": ["first"]}), json!({"ids": [a.0, b.0], "ends": ["first", "middle"]}), + json!({"to": "round"}), ] { assert!(s.execute("path.join", &bad).is_err(), "{bad}"); } } +/// `path.join {to}` makes the joined anchor a corner or smooth point. +#[test] +fn join_to_corner_or_smooth_sets_the_merged_anchor() { + let mut s = session(); + let r = rect(&mut s, 100.0, 100.0, 100.0, 80.0); + s.execute("select.anchors", &json!({"id": r.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); + s.execute("path.average", &json!({"axis": "both"})).unwrap(); + s.execute("path.join", &json!({"to": "corner"})).unwrap(); + let a = &path(&s, r).subpaths[0].anchors[0]; + assert_eq!(a.kind, vectorcraft_geom::AnchorKind::Corner); + assert_eq!((a.h_in, a.h_out), (a.p, a.p)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("path.average", &json!({"axis": "both"})).unwrap(); + s.execute("path.join", &json!({"to": "smooth"})).unwrap(); + let a = &path(&s, r).subpaths[0].anchors[0]; + assert_eq!(a.kind, vectorcraft_geom::AnchorKind::Smooth); + let a = line(&mut s, 0.0, 0.0, 100.0, 0.0); + let b = line(&mut s, 100.0, 0.0, 200.0, 0.0); + s.execute("path.join", &json!({"ids": [a.0, b.0], "to": "smooth"})).unwrap(); + let j = &path(&s, a).subpaths[0].anchors[1]; + assert_eq!(j.kind, vectorcraft_geom::AnchorKind::Smooth); +} + #[test] fn pen_with_alt_converts_the_anchors_of_a_path_in_a_selected_group() { // #1273: a selected group (or compound path) shows its paths' anchors, so Alt with the Pen @@ -1968,6 +2011,26 @@ fn open_anchor_delete_preserves_curves_appearance_and_history() { assert_eq!(s.doc().unwrap().doc, after); } +#[test] +fn closed_anchor_delete_then_join_closes_with_a_line() { + let mut s = session(); + let data = "M100 100C120 60 180 60 200 100C220 140 280 140 300 100C320 60 380 60 400 100C420 140 480 140 500 100C500 200 100 200 100 100Z"; + let id = NodeId(s.execute("path.create", &json!({"d": data})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 2]]})).unwrap(); + s.execute("path.deleteAnchors", &json!({})).unwrap(); + let result = path(&s, id); + assert_eq!(result.subpaths.len(), 1); + let sp = &result.subpaths[0]; + assert!(!sp.closed); + assert!(!sp.anchors.first().unwrap().has_in() && !sp.anchors.last().unwrap().has_out(), "dangling handles are cleared"); + s.execute("path.join", &json!({"ids": [id.0]})).unwrap(); + let joined = path(&s, id); + let sp = &joined.subpaths[0]; + assert!(sp.closed); + let closing = sp.segment(sp.segment_count() - 1); + assert!(closing.p1 == closing.p0 && closing.p2 == closing.p3, "closing segment is a line: {closing:?}"); +} + #[test] fn open_anchor_delete_does_not_change_explicit_remove_anchors() { for command in ["path.removeAnchors", "path.removeAnchor"] { diff --git a/crates/engine/src/tests_keyguide.rs b/crates/engine/src/tests_keyguide.rs new file mode 100644 index 0000000000..5c908709ef --- /dev/null +++ b/crates/engine/src/tests_keyguide.rs @@ -0,0 +1,185 @@ +//! #2143: a ruler guide selected with objects can be the key object Align lines them up on. + +use serde_json::{Value, json}; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; + +use super::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn rect(s: &mut Session, x: f64, y: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap()) +} + +fn bounds(s: &Session, id: NodeId) -> vectorcraft_geom::Rect { + s.doc().unwrap().doc.bounds_of(&[id], false).unwrap() +} + +/// A Selection tool click at (`x`, `y`), with Shift when `shift`. +fn click(s: &mut Session, x: f64, y: f64, shift: bool) { + let (v, mods) = (ViewInfo::default(), Mods { shift, ..Default::default() }); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, x, y).with_mods(mods), v).unwrap(); + } +} + +#[test] +fn a_clicked_guide_is_the_key_and_align_lines_the_objects_up_on_it() { + let mut s = session(); + let (a, b) = (rect(&mut s, 100.0, 100.0), rect(&mut s, 300.0, 250.0)); + s.execute("guide.add", &json!({"vertical": true, "pos": 500})).unwrap(); + s.select_tool("selection", ViewInfo::default()).unwrap(); + // Click an object, Shift-click the guide, then click the guide again. + click(&mut s, 110.0, 110.0, false); + click(&mut s, 500.0, 400.0, true); + assert_eq!((s.doc().unwrap().selection.objects.clone(), s.doc().unwrap().selection.guides.clone()), (vec![a], vec![0])); + click(&mut s, 500.0, 400.0, false); + assert_eq!(s.doc().unwrap().selection.key_guide, Some(0), "the guide is the key"); + assert_eq!(s.execute("document.inspect", &json!({})).unwrap()["keyGuide"], 0); + // Shift-click a third object: the guide stays the key. + click(&mut s, 310.0, 260.0, true); + assert_eq!(s.doc().unwrap().selection.objects, vec![a, b]); + assert_eq!(s.doc().unwrap().selection.key_guide, Some(0)); + let (ya, yb) = (bounds(&s, a).y0, bounds(&s, b).y0); + s.execute("object.align", &json!({"horizontal": "center", "vertical": "center"})).unwrap(); + // Both centred on the guide's x; a vertical guide fixes no y, so they keep theirs. + for (id, y) in [(a, ya), (b, yb)] { + let r = bounds(&s, id); + assert!((r.center().x - 500.0).abs() < 1e-6 && (r.y0 - y).abs() < 1e-6, "{id:?}: {r:?}"); + } + assert_eq!(s.doc().unwrap().doc.guides[0].pos, 500.0, "the guide stays put"); + s.execute("object.align", &json!({"horizontal": "left"})).unwrap(); + assert!((bounds(&s, a).x0 - 500.0).abs() < 1e-6 && (bounds(&s, b).x0 - 500.0).abs() < 1e-6); + // A click on the key guide again: no key. + click(&mut s, 500.0, 400.0, false); + assert_eq!(s.doc().unwrap().selection.key_guide, None); +} + +#[test] +fn one_object_aligns_to_a_horizontal_key_guide() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0); + s.execute("guide.add", &json!({"vertical": false, "pos": 300})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + assert_eq!(s.execute("select.key", &json!({"guide": 0})).unwrap(), json!({"key": null, "guide": 0})); + let x = bounds(&s, a).x0; + s.execute("object.align", &json!({"vertical": "bottom", "horizontal": "right"})).unwrap(); + let r = bounds(&s, a); + assert!((r.y1 - 300.0).abs() < 1e-6 && (r.x0 - x).abs() < 1e-6, "{r:?}"); + // `to` still wins. + s.execute("object.align", &json!({"horizontal": "left", "to": "artboard"})).unwrap(); + assert!(bounds(&s, a).x0.abs() < 1e-6); +} + +#[test] +fn select_key_takes_only_a_selected_guide_with_objects() { + let mut s = session(); + let (a, b) = (rect(&mut s, 100.0, 100.0), rect(&mut s, 300.0, 100.0)); + for pos in [500, 600] { + s.execute("guide.add", &json!({"vertical": true, "pos": pos})).unwrap(); + } + let err = |s: &mut Session, p: Value| assert!(s.execute("select.key", &p).is_err(), "{p}"); + s.execute("guide.select", &json!({"indexes": [1]})).unwrap(); + err(&mut s, json!({"guide": 1})); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + err(&mut s, json!({"guide": 1})); + s.execute("guide.select", &json!({"indexes": [0, 1], "toggle": true})).unwrap(); + for bad in [json!({"guide": 7}), json!({"guide": -1}), json!({"guide": "x"}), json!({"guide": 1, "id": a.0})] { + err(&mut s, bad); + } + s.execute("select.key", &json!({"guide": 1})).unwrap(); + // An object key replaces the guide key, and the other way round. + s.execute("select.key", &json!({"id": b.0})).unwrap(); + assert_eq!((s.doc().unwrap().selection.key, s.doc().unwrap().selection.key_guide), (Some(b), None)); + s.execute("select.key", &json!({"guide": 1})).unwrap(); + assert_eq!((s.doc().unwrap().selection.key, s.doc().unwrap().selection.key_guide), (None, Some(1))); + // Deleting a guide before it keeps the key on the same guide. + s.execute("guide.remove", &json!({"index": 0})).unwrap(); + assert_eq!(s.doc().unwrap().selection.key_guide, Some(0)); + assert_eq!(s.doc().unwrap().doc.guides[0].pos, 600.0); + // Taking the guide out of the selection, or every object, lets the key go. + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + assert_eq!(s.doc().unwrap().selection.key_guide, None); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + s.execute("select.key", &json!({"guide": 0})).unwrap(); + s.execute("select.toggle", &json!({"id": a.0})).unwrap(); + assert_eq!(s.doc().unwrap().selection.key_guide, Some(0), "one object is enough"); + s.execute("select.toggle", &json!({"id": b.0})).unwrap(); + assert_eq!(s.doc().unwrap().selection.key_guide, None, "no object to align"); +} + +#[test] +fn selected_anchor_points_align_to_a_key_guide() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0); + s.execute("guide.add", &json!({"vertical": true, "pos": 400})).unwrap(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "set"})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + s.execute("select.key", &json!({"guide": 0})).unwrap(); + s.execute("object.align", &json!({"horizontal": "center"})).unwrap(); + let NodeKind::Path { path, .. } = &s.doc().unwrap().doc.node(a).unwrap().kind else { panic!("path") }; + let p = path.subpaths[0].anchors[0].p; + assert_eq!(p.x, 400.0); + assert_eq!(path.subpaths[0].anchors[1].p.x, 140.0, "the other points stay"); +} + +#[test] +fn selected_guides_align_to_a_clicked_key_object() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0); + s.execute("guide.add", &json!({"vertical": true, "pos": 500})).unwrap(); + s.execute("guide.add", &json!({"vertical": false, "pos": 400})).unwrap(); + s.select_tool("selection", ViewInfo::default()).unwrap(); + // Click the object, Shift-click both guides, then click the object again: one object is + // enough to be the key while guides are selected. + click(&mut s, 110.0, 110.0, false); + click(&mut s, 500.0, 300.0, true); + click(&mut s, 300.0, 400.0, true); + assert_eq!(s.doc().unwrap().selection.guides, vec![0, 1]); + click(&mut s, 110.0, 110.0, false); + assert_eq!(s.doc().unwrap().selection.key, Some(a), "the object is the key"); + let before = bounds(&s, a); + s.execute("object.align", &json!({"horizontal": "center", "vertical": "center"})).unwrap(); + let guides = |s: &Session| s.doc().unwrap().doc.guides.iter().map(|g| g.pos).collect::>(); + assert_eq!(guides(&s), [120.0, 110.0], "the vertical guide on the centre's x, the horizontal one on its y"); + assert_eq!(bounds(&s, a), before, "the key stays put"); + s.execute("object.align", &json!({"horizontal": "right"})).unwrap(); + assert_eq!(guides(&s), [140.0, 110.0], "horizontal alignment moves only the vertical guide"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(guides(&s), [120.0, 110.0], "one undo step"); + // Aligning to the artboard leaves the guides alone. + s.execute("object.align", &json!({"horizontal": "left", "to": "artboard"})).unwrap(); + assert_eq!(guides(&s), [120.0, 110.0]); + // Deselecting the guides lets the lone key go. + s.execute("guide.select", &json!({"indexes": [0, 1], "toggle": true})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, vec![a]); + assert_eq!(s.doc().unwrap().selection.key, None); +} + +#[test] +fn guides_align_to_a_key_object_among_others_and_parallel_ones_to_a_key_guide() { + let mut s = session(); + let (a, b) = (rect(&mut s, 100.0, 100.0), rect(&mut s, 300.0, 250.0)); + for pos in [500, 600] { + s.execute("guide.add", &json!({"vertical": true, "pos": pos})).unwrap(); + } + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0, 1], "toggle": true})).unwrap(); + s.execute("select.key", &json!({"id": b.0})).unwrap(); + s.execute("object.align", &json!({"horizontal": "left"})).unwrap(); + assert_eq!(bounds(&s, a).x0, 300.0); + assert!(s.doc().unwrap().doc.guides.iter().all(|g| g.pos == 300.0)); + // Aligning to the selection leaves guides alone. + s.execute("object.align", &json!({"horizontal": "right", "to": "selection"})).unwrap(); + assert!(s.doc().unwrap().doc.guides.iter().all(|g| g.pos == 300.0)); + // A key guide stays put, and the other vertical guide lines up on it. + s.execute("guide.move", &json!({"index": 1, "pos": 700})).unwrap(); + s.execute("select.key", &json!({"guide": 1})).unwrap(); + s.execute("object.align", &json!({"horizontal": "center"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.guides.iter().map(|g| g.pos).collect::>(), [700.0, 700.0]); +} diff --git a/crates/engine/src/tests_library.rs b/crates/engine/src/tests_library.rs index bdc9c1e1bb..15c8d9be87 100644 --- a/crates/engine/src/tests_library.rs +++ b/crates/engine/src/tests_library.rs @@ -276,6 +276,61 @@ fn items_are_grouped_moved_and_ungrouped() { assert_eq!(run(&mut s, "library.list", json!({}))["libraries"][0]["groups"], 1); } +/// The names of the current library's `list` ("colors", "graphics"…), in their order. +fn order(s: &mut Session, list: &str, key: &str) -> Vec { + let got = run(s, "library.get", json!({})); + got[list].as_array().unwrap().iter().map(|v| v[key].as_str().unwrap().to_string()).collect() +} + +/// Dragging in the Libraries panel: an item moves just before or after another of its kind, into +/// that one's group or out of every group, and groups move to another place in the list. +#[test] +fn items_and_groups_are_reordered() { + let mut s = session(); + run(&mut s, "library.create", json!({"name": "Brand"})); + for (name, color) in [("Red", "#ff0000"), ("Green", "#00ff00"), ("Blue", "#0000ff"), ("Gray", "#808080")] { + run(&mut s, "library.add", json!({"kind": "fillColor", "color": color, "name": name})); + } + // Before an item, and after one; on itself it stays. + run(&mut s, "library.moveItem", json!({"kind": "fillColor", "item": "Blue", "before": "Red"})); + assert_eq!(order(&mut s, "colors", "name"), ["Blue", "Red", "Green", "Gray"]); + run(&mut s, "library.moveItem", json!({"kind": "fillColor", "item": "Blue", "after": "Gray"})); + assert_eq!(order(&mut s, "colors", "name"), ["Red", "Green", "Gray", "Blue"]); + run(&mut s, "library.moveItem", json!({"kind": "fillColor", "item": "Red", "before": "Red"})); + assert_eq!(order(&mut s, "colors", "name"), ["Red", "Green", "Gray", "Blue"]); + // Into a group next to an item there: the group lists it next to that one too. + run( + &mut s, + "library.createGroup", + json!({"name": "Cool", "items": [{"kind": "fillColor", "item": "Green"}, {"kind": "fillColor", "item": "Blue"}]}), + ); + let r = run(&mut s, "library.moveItem", json!({"kind": "fillColor", "item": "Gray", "group": "Cool", "before": "Blue"})); + assert_eq!(r["group"], "Cool"); + assert_eq!(order(&mut s, "colors", "name"), ["Red", "Green", "Gray", "Blue"]); + assert_eq!(groups(&mut s), [("Cool".into(), refs(&[("color", "Green"), ("color", "Gray"), ("color", "Blue")]))]); + // Next to an ungrouped item, without a group: out of its group. + run(&mut s, "library.moveItem", json!({"kind": "fillColor", "item": "Blue", "before": "Red"})); + assert_eq!(order(&mut s, "colors", "name"), ["Blue", "Red", "Green", "Gray"]); + assert_eq!(groups(&mut s), [("Cool".into(), refs(&[("color", "Green"), ("color", "Gray")]))]); + // Wrong asks change nothing. + assert!(s.execute("library.moveItem", &json!({"kind": "fillColor", "item": "Red", "before": "Nope"})).is_err()); + assert!(s.execute("library.moveItem", &json!({"kind": "fillColor", "item": "Red", "before": "Blue", "after": "Gray"})).is_err()); + assert!(s.execute("library.moveItem", &json!({"kind": "charStyle", "item": "Red", "before": "Blue"})).is_err(), "not a style"); + assert_eq!(order(&mut s, "colors", "name"), ["Blue", "Red", "Green", "Gray"]); + // Groups: to an index, past the end to the last place. + run(&mut s, "library.createGroup", json!({"name": "Warm"})); + run(&mut s, "library.createGroup", json!({"name": "Neutral"})); + let names = |s: &mut Session| groups(s).into_iter().map(|(n, _)| n).collect::>(); + assert_eq!(run(&mut s, "library.moveGroup", json!({"group": "neutral", "to": 0}))["to"], 0); + assert_eq!(names(&mut s), ["Neutral", "Cool", "Warm"]); + assert_eq!(run(&mut s, "library.moveGroup", json!({"group": "Neutral", "to": 99}))["to"], 2); + assert_eq!(names(&mut s), ["Cool", "Warm", "Neutral"]); + assert!(s.execute("library.moveGroup", &json!({"group": "Nope", "to": 0})).is_err()); + assert!(s.execute("library.moveGroup", &json!({"group": "Cool", "to": -1})).is_err()); + assert!(s.execute("library.moveGroup", &json!({"group": "Cool"})).is_err()); + assert_eq!(groups(&mut s)[0].1, refs(&[("color", "Green"), ("color", "Gray")]), "a group keeps its items when it moves"); +} + /// A library goes out to a file with its art and groups and comes back as a new library, numbered /// when its name is taken; the graphic it brings places in a document (#926). #[test] diff --git a/crates/engine/src/tests_menucmds.rs b/crates/engine/src/tests_menucmds.rs index 8b93e55322..1b888a2a7e 100644 --- a/crates/engine/src/tests_menucmds.rs +++ b/crates/engine/src/tests_menucmds.rs @@ -1280,6 +1280,17 @@ fn next_object_above_and_below_pass_over_what_cant_be_selected() { assert_eq!(selected(&s), vec![a]); } +/// A keyboard shortcut runs `object.isolate` with no params; the first selected object is isolated (#2991). +#[test] +fn object_isolate_without_id_uses_the_selection() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 50.0, 50.0); + let _b = rect(&mut s, 100.0, 0.0, 50.0, 50.0); + sel(&mut s, &[a]); + s.execute("object.isolate", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().isolation, Some(a)); +} + /// In isolation mode Select › Same and Select › Object select only objects in the isolated group. #[test] fn select_menu_commands_stay_inside_the_isolated_group() { diff --git a/crates/engine/src/tests_objects_on_path.rs b/crates/engine/src/tests_objects_on_path.rs new file mode 100644 index 0000000000..5f2faa67d9 --- /dev/null +++ b/crates/engine/src/tests_objects_on_path.rs @@ -0,0 +1,390 @@ +//! Object › Objects on Path (#2545): objects attached to a path, spread along it and turned to +//! follow it, kept there while the path is edited. Driven through `Session::execute`. + +use serde_json::{Value, json}; +use vectorcraft_geom::{Point, Rect}; + +use super::tests_clip::{id_of, select}; +use super::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s +} + +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 line(s: &mut Session, a: (f64, f64), b: (f64, f64)) -> NodeId { + id_of(&s.execute("shape.line", &json!({"x1": a.0, "y1": a.1, "x2": b.0, "y2": b.1})).unwrap()) +} + +fn bounds(s: &Session, id: NodeId) -> Rect { + s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap() +} + +fn center(s: &Session, id: NodeId) -> Point { + let c = bounds(s, id).center(); + Point::new((c.x * 1000.0).round() / 1000.0, (c.y * 1000.0).round() / 1000.0) +} + +fn attach(s: &mut Session, path: NodeId, objects: &[NodeId], extra: Value) -> NodeId { + select(s, objects); + let mut p = json!({ "path": path.0 }); + if let (Some(p), Some(e)) = (p.as_object_mut(), extra.as_object()) { + p.extend(e.clone()); + } + id_of(&s.execute("object.objectsOnPath.attach", &p).unwrap()) +} + +fn set_line(s: &mut Session, id: NodeId, a: (f64, f64), b: (f64, f64)) { + let anchors = json!([{"x": a.0, "y": a.1}, {"x": b.0, "y": b.1}]); + s.execute("path.setAnchors", &json!({"id": id.0, "subpaths": [{"anchors": anchors, "closed": false}]})).unwrap(); +} + +/// Three 20 pt squares, out of order on the canvas, and a 300 pt line from (50, 300) to the right. +fn squares_and_line(s: &mut Session) -> ([NodeId; 3], NodeId) { + let right = rect(s, 250.0, 20.0, 20.0, 20.0); + let left = rect(s, 10.0, 100.0, 20.0, 20.0); + let middle = rect(s, 120.0, 0.0, 20.0, 20.0); + let path = line(s, (50.0, 300.0), (350.0, 300.0)); + ([left, middle, right], path) +} + +#[test] +fn attach_spreads_the_objects_evenly_along_an_open_path_from_left_to_right() { + let mut s = session(); + let ([left, middle, right], path) = squares_and_line(&mut s); + let g = attach(&mut s, path, &[right, left, middle], json!({})); + let d = &s.doc().unwrap().doc; + let n = d.node(g).unwrap(); + assert_eq!(n.kind_label(), "Objects on Path"); + assert_eq!(n.children().unwrap().first().map(|c| c.id), Some(path), "the path is at the bottom of the group"); + let rec = n.extras().objects_on_path.as_deref().unwrap(); + assert_eq!(rec.members.iter().map(|m| m.id).collect::>(), [left, middle, right], "left to right on the canvas"); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [g]); + // First on the start, last on the end, evenly between: the centers on the line. + assert_eq!(center(&s, left), Point::new(50.0, 300.0)); + assert_eq!(center(&s, middle), Point::new(200.0, 300.0)); + assert_eq!(center(&s, right), Point::new(350.0, 300.0)); + let b = bounds(&s, middle); + assert!((b.width() - 20.0).abs() < 1e-9 && (b.height() - 20.0).abs() < 1e-9, "upright on a level path: {b:?}"); +} + +#[test] +fn objects_in_a_column_go_top_to_bottom() { + let mut s = session(); + // Its left edge is the leftmost, but it is below the other one in their column. + let lower = rect(&mut s, 8.0, 80.0, 20.0, 20.0); + let upper = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + let beside = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + let path = line(&mut s, (0.0, 300.0), (300.0, 300.0)); + let g = attach(&mut s, path, &[beside, lower, upper], json!({})); + let ids: Vec = s.doc().unwrap().doc.node(g).unwrap().extras().objects_on_path.as_deref().unwrap().members.iter().map(|m| m.id).collect(); + assert_eq!(ids, [upper, lower, beside]); +} + +#[test] +fn the_objects_turn_with_the_path_and_rotate_tilts_them() { + let mut s = session(); + // A 40 × 10 bar on a path that runs straight down: it turns a quarter. + let bar = rect(&mut s, 0.0, 0.0, 40.0, 10.0); + let other = rect(&mut s, 100.0, 0.0, 40.0, 10.0); + let path = line(&mut s, (200.0, 50.0), (200.0, 350.0)); + let g = attach(&mut s, path, &[bar, other], json!({})); + let b = bounds(&s, bar); + assert!((b.width() - 10.0).abs() < 1e-6 && (b.height() - 40.0).abs() < 1e-6, "across the path: {b:?}"); + assert_eq!(center(&s, bar), Point::new(200.0, 50.0)); + // Rotate 90: turned back level, still centered on the path. + s.execute("object.objectsOnPath.options", &json!({"rotate": 90})).unwrap(); + let b = bounds(&s, bar); + assert!((b.width() - 40.0).abs() < 1e-6 && (b.height() - 10.0).abs() < 1e-6, "tilted by Rotate: {b:?}"); + assert_eq!(center(&s, other), Point::new(200.0, 350.0)); + let rec = s.doc().unwrap().doc.node(g).unwrap().extras().objects_on_path.as_deref().cloned().unwrap(); + assert_eq!((rec.pivot, rec.rotate), (4, 90.0)); + // The same angle given to Attach. + let mut t = session(); + let bar = rect(&mut t, 0.0, 0.0, 40.0, 10.0); + let path = line(&mut t, (200.0, 50.0), (200.0, 350.0)); + attach(&mut t, path, &[bar], json!({"rotate": 90})); + let b = bounds(&t, bar); + assert!((b.width() - 40.0).abs() < 1e-6 && (b.height() - 10.0).abs() < 1e-6, "{b:?}"); +} + +#[test] +fn a_turned_object_attaches_square_to_the_path_or_across_it() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 40.0, 10.0); + let b = rect(&mut s, 100.0, 0.0, 40.0, 10.0); + s.execute("object.rotate", &json!({"ids": [a.0], "angle": 30})).unwrap(); + s.execute("object.rotate", &json!({"ids": [b.0], "angle": 60})).unwrap(); + let path = line(&mut s, (50.0, 300.0), (350.0, 300.0)); + attach(&mut s, path, &[a, b], json!({})); + let (ba, bb) = (bounds(&s, a), bounds(&s, b)); + assert!((ba.width() - 40.0).abs() < 1e-6 && (ba.height() - 10.0).abs() < 1e-6, "30° rounds to level: {ba:?}"); + assert!((bb.width() - 10.0).abs() < 1e-6 && (bb.height() - 40.0).abs() < 1e-6, "60° rounds to upright: {bb:?}"); +} + +#[test] +fn a_reflected_group_keeps_the_mirrored_tilt() { + let mut s = session(); + let bar = rect(&mut s, 0.0, 0.0, 40.0, 10.0); + let other = rect(&mut s, 100.0, 0.0, 40.0, 10.0); + let path = line(&mut s, (50.0, 300.0), (350.0, 300.0)); + let g = attach(&mut s, path, &[bar, other], json!({"rotate": 30})); + // The x of the bar's topmost corner, from its center: tilted counter-clockwise, it is on the right. + let top_x = |s: &Session| { + let n = s.doc().unwrap().doc.node(bar).unwrap(); + let anchors = &n.path_data().unwrap().subpaths[0].anchors; + let top = anchors.iter().min_by(|a, b| a.p.y.total_cmp(&b.p.y)).unwrap().p; + top.x - bounds(s, bar).center().x + }; + assert!(top_x(&s) > 1.0); + select(&mut s, &[g]); + s.execute("object.reflect", &json!({"axis": "horizontal"})).unwrap(); + assert!(top_x(&s) < -1.0, "mirrored: tilted clockwise"); + let rec = s.doc().unwrap().doc.node(g).unwrap().extras().objects_on_path.as_deref().cloned().unwrap(); + assert_eq!(rec.rotate, -30.0); +} + +#[test] +fn scaling_the_group_out_of_proportion_keeps_the_scaled_tilt_and_scaling_back_restores_it() { + let mut s = session(); + let bar = rect(&mut s, 0.0, 0.0, 40.0, 10.0); + let other = rect(&mut s, 100.0, 0.0, 40.0, 10.0); + let path = line(&mut s, (50.0, 300.0), (350.0, 300.0)); + let g = attach(&mut s, path, &[bar, other], json!({"rotate": 45})); + let anchors = |s: &Session| -> Vec<(f64, f64)> { + let n = s.doc().unwrap().doc.node(bar).unwrap().clone(); + n.path_data().unwrap().subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect() + }; + let before = anchors(&s); + select(&mut s, &[g]); + s.execute("object.scale", &json!({"sx": 200, "sy": 100, "origin": [200, 300]})).unwrap(); + // The bar's long edge was at 45°: twice as wide, it slopes at atan(1/2). + let a = anchors(&s); + let (dx, dy) = (a[1].0 - a[0].0, a[1].1 - a[0].1); + assert!((dy.abs().atan2(dx.abs()).to_degrees() - 0.5f64.atan().to_degrees()).abs() < 1e-6, "{a:?}"); + s.execute("object.scale", &json!({"sx": 50, "sy": 100, "origin": [200, 300]})).unwrap(); + for (p, q) in anchors(&s).iter().zip(&before) { + assert!((p.0 - q.0).abs() < 1e-6 && (p.1 - q.1).abs() < 1e-6, "{:?} against {before:?}", anchors(&s)); + } +} + +#[test] +fn pivot_picks_the_point_that_sits_on_the_path() { + let mut s = session(); + let ([left, middle, right], path) = squares_and_line(&mut s); + attach(&mut s, path, &[left, middle, right], json!({"pivot": 7})); + // The middle of each square's bottom edge is on the line: the squares stand on it. + let b = bounds(&s, middle); + assert!((b.y1 - 300.0).abs() < 1e-6 && (b.center().x - 200.0).abs() < 1e-6, "{b:?}"); + s.execute("object.objectsOnPath.options", &json!({"pivot": 1})).unwrap(); + let b = bounds(&s, middle); + assert!((b.y0 - 300.0).abs() < 1e-6, "hanging from the line by their top edge: {b:?}"); +} + +#[test] +fn a_closed_path_spreads_the_objects_all_the_way_round_from_its_first_anchor() { + let mut s = session(); + let ids: Vec = (0..4).map(|i| rect(&mut s, 10.0 + 40.0 * f64::from(i), 0.0, 10.0, 10.0)).collect(); + let ring = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let first = s.doc().unwrap().doc.node(ring).unwrap().path_data().unwrap().subpaths[0].anchors[0].p; + attach(&mut s, ring, &ids, json!({})); + assert_eq!(center(&s, ids[0]), first, "the first object on the first anchor"); + let mut at: Vec<(i64, i64)> = ids.iter().map(|id| center(&s, *id)).map(|p| (p.x.round() as i64, p.y.round() as i64)).collect(); + at.sort(); + assert_eq!(at, [(100, 100), (100, 300), (300, 100), (300, 300)], "a quarter of the way round apart"); +} + +#[test] +fn editing_the_path_moves_the_objects_and_undo_takes_it_back() { + let mut s = session(); + let ([left, middle, right], path) = squares_and_line(&mut s); + attach(&mut s, path, &[left, middle, right], json!({})); + set_line(&mut s, path, (50.0, 250.0), (250.0, 250.0)); + assert_eq!(center(&s, left), Point::new(50.0, 250.0)); + assert_eq!(center(&s, middle), Point::new(150.0, 250.0)); + assert_eq!(center(&s, right), Point::new(250.0, 250.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(center(&s, middle), Point::new(200.0, 300.0), "one undo step puts the path and the objects back"); + // Attach itself is one step. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(center(&s, middle), Point::new(130.0, 10.0)); + let d = &s.doc().unwrap().doc; + assert!(d.layers.iter().all(|l| l.children().unwrap().iter().all(|c| !vectorcraft_doc::objects_on_path::is_objects_on_path(c)))); +} + +#[test] +fn an_object_moved_on_its_own_goes_back_on_the_path() { + let mut s = session(); + let ([left, middle, right], path) = squares_and_line(&mut s); + let g = attach(&mut s, path, &[left, middle, right], json!({})); + s.execute("object.move", &json!({"ids": [middle.0], "dx": 30, "dy": -40})).unwrap(); + assert_eq!(center(&s, middle), Point::new(200.0, 300.0)); + // The whole group moves as one. + select(&mut s, &[g]); + s.execute("object.move", &json!({"dx": 10, "dy": 20})).unwrap(); + assert_eq!(center(&s, middle), Point::new(210.0, 320.0)); + assert_eq!(center(&s, right), Point::new(360.0, 320.0)); +} + +#[test] +fn objects_moved_into_the_group_join_the_end_and_ones_moved_out_leave() { + let mut s = session(); + let ([left, middle, right], path) = squares_and_line(&mut s); + let g = attach(&mut s, path, &[left, middle], json!({})); + s.execute("layer.move", &json!({"ids": [right.0], "target": g.0, "place": "inside"})).unwrap(); + assert_eq!(center(&s, left), Point::new(50.0, 300.0)); + assert_eq!(center(&s, middle), Point::new(200.0, 300.0)); + assert_eq!(center(&s, right), Point::new(350.0, 300.0), "the new object goes at the end"); + s.execute("layer.move", &json!({"ids": [middle.0], "target": g.0, "place": "above"})).unwrap(); + let rec = s.doc().unwrap().doc.node(g).unwrap().extras().objects_on_path.as_deref().cloned().unwrap(); + assert_eq!(rec.members.iter().map(|m| m.id).collect::>(), [left, right]); + assert_eq!(center(&s, right), Point::new(350.0, 300.0), "two objects stay on the ends"); +} + +#[test] +fn art_that_replaces_an_object_keeps_its_place_on_the_path() { + let mut s = session(); + let mark = rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let first = id_of(&s.execute("symbol.new", &json!({"name": "Mark", "ids": [mark.0]})).unwrap()); + let second = id_of(&s.execute("symbol.place", &json!({"name": "Mark", "x": 100, "y": 10})).unwrap()); + let third = id_of(&s.execute("symbol.place", &json!({"name": "Mark", "x": 200, "y": 10})).unwrap()); + let path = line(&mut s, (50.0, 300.0), (350.0, 300.0)); + let g = attach(&mut s, path, &[first, second, third], json!({})); + let v = s.execute("symbol.breakLink", &json!({"ids": [first.0]})).unwrap(); + let art = v["ids"].as_array().and_then(|a| a.first()).and_then(Value::as_u64).map(NodeId).unwrap(); + let rec = s.doc().unwrap().doc.node(g).unwrap().extras().objects_on_path.as_deref().cloned().unwrap(); + assert_eq!(rec.members.iter().map(|m| m.id).collect::>(), [art, second, third], "the art takes the instance's place"); + assert_eq!(center(&s, art), Point::new(50.0, 300.0)); + assert_eq!(center(&s, third), Point::new(350.0, 300.0)); +} + +#[test] +fn a_shaper_group_stays_on_the_path_when_a_source_changes() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + rect(&mut s, 50.0, 0.0, 100.0, 100.0); + let pts = [[25.0, 20.0], [75.0, 35.0], [30.0, 50.0], [125.0, 65.0]]; + let shaper = NodeId(s.execute("shaper.scribble", &json!({"points": pts})).unwrap()["id"].as_u64().unwrap()); + let other = rect(&mut s, 300.0, 0.0, 20.0, 20.0); + let path = line(&mut s, (50.0, 300.0), (350.0, 300.0)); + attach(&mut s, path, &[shaper, other], json!({})); + assert_eq!(center(&s, shaper), Point::new(50.0, 300.0)); + select(&mut s, &[a]); + s.execute("object.setBounds", &json!({"width": 200.0, "height": 100.0, "reference": 0})).unwrap(); + // The rebuilt art is wider, and its center is still on the start of the path. + assert!(bounds(&s, shaper).width() > 180.0, "{:?}", bounds(&s, shaper)); + assert_eq!(center(&s, shaper), Point::new(50.0, 300.0)); +} + +#[test] +fn the_group_saves_and_reopens_live_and_exports_as_plain_art() { + let mut s = session(); + let ([left, middle, right], path) = squares_and_line(&mut s); + let g = attach(&mut s, path, &[left, middle, right], json!({"rotate": 30, "pivot": 7})); + let data = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].clone(); + let mut o = Session::new(); + o.execute("document.open", &json!({"name": "objects.vectorcraft", "dataBase64": data})).unwrap(); + let before = s.doc().unwrap().doc.node(g).unwrap().extras().objects_on_path.clone(); + assert_eq!(o.doc().unwrap().doc.node(g).unwrap().extras().objects_on_path, before); + set_line(&mut o, path, (50.0, 200.0), (350.0, 200.0)); + assert!((bounds(&o, middle).center().x - bounds(&s, middle).center().x).abs() < 1e-6); + assert!(bounds(&o, middle).center().y < 210.0, "editing the reopened path moves the objects"); + for format in ["svg", "pdf"] { + let data = s.execute("document.export", &json!({"format": format})).unwrap()["dataBase64"].clone(); + let mut o = Session::new(); + o.execute("document.open", &json!({"name": format!("objects.{format}"), "dataBase64": data})).unwrap(); + let r = vectorcraft_render::Renderer::new().render(&o.doc().unwrap().doc, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()); + let c = bounds(&s, middle).center(); + assert!(r.pixel(c.x as u32, c.y as u32 - 4)[3] > 128, "{format}: the square is drawn where it is attached"); + assert!(r.pixel(130, 10)[3] < 10, "{format}: not where it was drawn"); + } +} + +#[test] +fn a_pasted_copy_stays_live_on_its_own_path() { + let mut s = session(); + let ([left, middle, right], path) = squares_and_line(&mut s); + let g = attach(&mut s, path, &[left, middle, right], json!({})); + select(&mut s, &[g]); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let copy = s.doc().unwrap().selection.objects.to_vec(); + let [copy] = copy[..] else { panic!("{copy:?}") }; + assert_ne!(copy, g); + let n = s.doc().unwrap().doc.node(copy).unwrap().clone(); + let rec = n.extras().objects_on_path.as_deref().cloned().unwrap(); + let kids: Vec = n.children().unwrap().iter().map(|c| c.id).collect(); + assert_eq!(kids.first(), Some(&rec.path), "the copy names its own path"); + assert!(rec.members.iter().all(|m| kids.contains(&m.id) && ![left, middle, right].contains(&m.id))); + let (a, b) = (s.doc().unwrap().doc.node(rec.path).unwrap().geometric_bounds().unwrap(), bounds(&s, path)); + set_line(&mut s, rec.path, (a.x0, a.y0 - 50.0), (a.x1, a.y0 - 50.0)); + assert!((bounds(&s, rec.members[1].id).center().y - (a.y0 - 50.0)).abs() < 1e-6, "the copy's objects follow the copy's path"); + assert_eq!(bounds(&s, path), b); + assert_eq!(center(&s, middle), Point::new(200.0, 300.0), "the original stays"); +} + +#[test] +fn expand_leaves_a_plain_group() { + let mut s = session(); + let ([left, middle, right], path) = squares_and_line(&mut s); + let g = attach(&mut s, path, &[left, middle, right], json!({})); + let v = s.execute("object.objectsOnPath.expand", &json!({})).unwrap(); + assert_eq!(v["ids"], json!([g.0])); + let n = s.doc().unwrap().doc.node(g).unwrap().clone(); + assert_eq!(n.kind_label(), "Group"); + assert_eq!(n.children().unwrap().len(), 4); + set_line(&mut s, path, (50.0, 250.0), (250.0, 250.0)); + assert_eq!(center(&s, middle), Point::new(200.0, 300.0), "the objects stay where they were"); + assert!(s.execute("object.objectsOnPath.expand", &json!({})).is_err(), "nothing left to expand"); +} + +#[test] +fn attach_without_a_path_chooses_the_tool() { + let mut s = session(); + let ([left, ..], _) = squares_and_line(&mut s); + select(&mut s, &[left]); + assert_eq!(s.execute("object.objectsOnPath.attach", &json!({})).unwrap()["tool"], "objectsOnPath"); + assert_eq!(s.tool_id(), "objectsOnPath"); +} + +#[test] +fn what_cannot_be_attached_is_refused_with_a_reason() { + let mut s = session(); + let ([left, _, right], path) = squares_and_line(&mut s); + let err = |s: &mut Session, p: Value| s.execute("object.objectsOnPath.attach", &p).unwrap_err().to_string(); + select(&mut s, &[path]); + assert!(err(&mut s, json!({"path": path.0})).contains("select the objects"), "the path alone"); + let dot = line(&mut s, (10.0, 10.0), (10.0, 10.0)); + assert!(err(&mut s, json!({"path": dot.0, "ids": [left.0]})).contains("pick a path"), "a path without length"); + let guide = line(&mut s, (0.0, 380.0), (300.0, 380.0)); + select(&mut s, &[guide]); + s.execute("view.guides.make", &json!({})).unwrap(); + assert!(err(&mut s, json!({"path": guide.0, "ids": [right.0]})).contains("pick a path"), "a guide"); + let g = attach(&mut s, path, &[right], json!({})); + let other = line(&mut s, (0.0, 350.0), (300.0, 350.0)); + assert!(err(&mut s, json!({"path": other.0, "ids": [right.0]})).contains("already on a path")); + assert!(err(&mut s, json!({"path": path.0, "ids": [left.0]})).contains("already in an Objects on Path group")); + assert!(err(&mut s, json!({"path": other.0, "ids": [g.0], "pivot": 9})).contains("pivot")); + assert!(s.execute("object.objectsOnPath.options", &json!({"ids": [other.0]})).is_err()); +} + +#[test] +fn options_and_expand_take_ids_without_a_selection() { + let mut s = session(); + let ([left, middle, right], path) = squares_and_line(&mut s); + let g = attach(&mut s, path, &[left, middle, right], json!({})); + s.execute("select.set", &json!({"ids": []})).unwrap(); + // An object in the group names the group. + let v = s.execute("object.objectsOnPath.options", &json!({"ids": [middle.0], "pivot": 7})).unwrap(); + assert_eq!(v["ids"], json!([g.0])); + assert!((bounds(&s, middle).y1 - 300.0).abs() < 1e-6, "standing on the line"); + let v = s.execute("object.objectsOnPath.expand", &json!({"ids": [g.0]})).unwrap(); + assert_eq!(v["ids"], json!([g.0])); + assert_eq!(s.doc().unwrap().doc.node(g).unwrap().kind_label(), "Group"); + assert!(s.execute("object.objectsOnPath.expand", &json!({"ids": [g.0]})).is_err(), "no longer an Objects on Path group"); +} diff --git a/crates/engine/src/tests_pathops.rs b/crates/engine/src/tests_pathops.rs index 9220223d8e..384fa65936 100644 --- a/crates/engine/src/tests_pathops.rs +++ b/crates/engine/src/tests_pathops.rs @@ -448,6 +448,58 @@ fn simplify_dense_polyline() { assert!(close(bounds(&s, id), Rect::new(0.0, 60.0, 300.0, 140.0), 2.0)); } +/// A sine wave with an anchor every point over `width` pt, `amplitude` pt high and a wavelength of +/// `2π × period` pt, its anchors `jag` pt above and below it in turn, selected: (the session, the +/// path's id). +fn dense_wave(width: u32, amplitude: f64, period: f64, jag: f64) -> (Session, NodeId) { + let mut s = session(); + let y = |i: u32| 100.0 + amplitude * (f64::from(i) / period).sin() + if i.is_multiple_of(2) { jag } else { -jag }; + let anchors: Vec = (0..=width).map(|i| json!({"x": f64::from(i), "y": y(i)})).collect(); + let r = s.execute("path.create", &json!({"anchors": anchors})).unwrap(); + (s, NodeId(r["id"].as_u64().unwrap())) +} + +/// The Simplify slider: moving its level from 0 to 100 never lowers the anchor count, level 0 +/// leaves fewer anchors than level 100, and level 50 gives the 1 pt result. +#[test] +fn simplify_level_moves_the_anchor_count_monotonically() { + let (mut s, id) = dense_wave(300, 40.0, 25.0, 0.0); + let mut counts = vec![]; + for level in (0..=100).step_by(10) { + let out = s.execute("object.path.simplify", &json!({ "level": level })).unwrap(); + assert_eq!(out["level"], json!(f64::from(level))); + counts.push(path_of(&s, id).0.anchor_count()); + s.execute("edit.undo", &json!({})).unwrap(); + } + assert!(counts.windows(2).all(|w| w[0] <= w[1]), "{counts:?}"); + assert!(counts[0] < counts[10], "{counts:?}"); + s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap(); + assert_eq!(path_of(&s, id).0.anchor_count(), counts[5], "level 50 is 1 pt"); +} + +/// Auto-Simplify picks the lowest level whose tolerance is at most 1/400 of the selection's longer +/// side, and 11 sampled points on each segment of the original path stay that close to the result. +#[test] +fn auto_simplify_keeps_the_shape_within_a_400th_of_its_size() { + let (mut s, id) = dense_wave(100, 15.0, 8.0, 0.2); + let original = path_of(&s, id).0.clone(); + let out = s.execute("object.path.simplify", &json!({"auto": true})).unwrap(); + // 100 pt across: 0.25 pt at most, level 70 (0.25 pt). + assert_eq!(out["level"], json!(70.0)); + let result = path_of(&s, id).0.clone(); + assert!(result.anchor_count() < original.anchor_count() / 2, "{}", result.anchor_count()); + // How far each point along the original lies from the nearest point of the result. + use vectorcraft_geom::ParamCurve; + use vectorcraft_geom::kurbo::ParamCurveNearest; + let fitted = &result.subpaths[0]; + let off = |p: vectorcraft_geom::Point| { + (0..fitted.segment_count()).map(|i| fitted.segment(i).nearest(p, 1e-9).distance_sq.sqrt()).fold(f64::INFINITY, f64::min) + }; + let sp = &original.subpaths[0]; + let worst = (0..sp.segment_count()).flat_map(|i| (0..=10).map(move |k| sp.segment(i).eval(f64::from(k) / 10.0))).map(off).fold(0.0, f64::max); + assert!(worst <= 100.0 / 400.0, "{worst}"); +} + /// How many steps there are to undo and to redo, and whether the document has unsaved changes. fn history(s: &Session) -> (usize, usize, bool) { let st = s.doc().unwrap(); diff --git a/crates/engine/src/tests_plugins.rs b/crates/engine/src/tests_plugins.rs index 6e8d896704..32d61cfe65 100644 --- a/crates/engine/src/tests_plugins.rs +++ b/crates/engine/src/tests_plugins.rs @@ -174,6 +174,94 @@ fn live_effect_plugins_reshape_editable_art_and_expand() { assert_eq!(baked.unwrap().bounds(), triangle().bounds()); } +/// A live effect is given its object's fills and strokes, read only, and which of them it sits on; +/// a change of paint runs it again. +#[test] +fn live_effects_are_given_their_object_s_paints() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + run(&mut s, "paint.setStroke", json!({"ids": [id.0], "color": "#000000"})); + run(&mut s, "stroke.set", json!({"ids": [id.0], "weight": 5})); + // The red fill as the host writes paints: a JSON value, its keys sorted. + let red = serde_json::to_value(&node(&s, id).appearance.fill().unwrap().paint).unwrap().to_string(); + let tri = json!({"objects": [{"path": triangle()}]}).to_string(); + // Each draws the triangle while it is given what it looks for, else hands the geometry back. + let effect = |id: &str, given, needle: &str| tpl::when_given(&tpl::manifest(id, "effect", "{}"), given, needle, &tri); + install_wat(&mut s, &effect("test.engine.wide", tpl::Given::Input, r#""width":5.0"#)); + install_wat(&mut s, &effect("test.engine.red", tpl::Given::Input, &format!(r#""fills":[{red}]"#))); + install_wat(&mut s, &effect("test.engine.second", tpl::Given::Params, r#""item":{"stroke":1}"#)); + let effected = |s: &Session, item: Option| { + let n = node(s, id); + let path = n.path_data().unwrap().clone(); + let ctx = vectorcraft_render::effects::GeomContext::of(&n); + let (effects, ctx) = match item { + Some(i) => match &n.appearance.items[i] { + vectorcraft_doc::AppearanceItem::Stroke(st) => (st.effects.clone(), ctx.item(&n.appearance.items[i])), + other => panic!("not a stroke: {other:?}"), + }, + None => (n.appearance.effects.clone(), ctx), + }; + vectorcraft_render::effects::apply_geometry_with(&effects, &path, path.bounds().unwrap(), &ctx) + }; + let own = node(&s, id).path_data().unwrap().clone(); + let remove = |s: &mut Session| run(s, "effect.remove", json!({"ids": [id.0], "index": 0, "item": null})); + for effect in ["plugin.test.engine.wide", "plugin.test.engine.red"] { + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": effect, "item": null})); + assert_eq!(effected(&s, None), triangle(), "{effect}: given the 5 pt stroke and the red fill"); + remove(&mut s); + } + // Run again once the stroke is thinner. + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.wide", "item": null})); + run(&mut s, "stroke.set", json!({"ids": [id.0], "weight": 3, "item": 1})); + assert_eq!(effected(&s, None), own, "a 3 pt stroke"); + remove(&mut s); + // On the second of two strokes, and not on the first. + run(&mut s, "appearance.addStroke", json!({"ids": [id.0]})); + let top = node(&s, id).appearance.items.len() - 1; + for item in [1, top] { + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.second", "item": item})); + } + assert_eq!(effected(&s, Some(1)), own, "the first stroke"); + assert_eq!(effected(&s, Some(top)), triangle(), "the second stroke"); +} + +/// Expand gives a plug-in effect on a fill the context drawing gives it (`_context.item`), so a +/// gradient fill is expanded into the shape the canvas fills. +#[test] +fn expanding_a_fill_gives_its_plug_in_effect_the_fill_it_sits_on() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + run(&mut s, "paint.setFill", json!({"ids": [id.0], "gradient": {"kind": "linear"}})); + let tri = json!({"objects": [{"path": triangle()}]}).to_string(); + let on_fill = tpl::when_given(&tpl::manifest("test.engine.onfill", "effect", "{}"), tpl::Given::Params, r#""item":{"fill":0}"#, &tri); + install_wat(&mut s, &on_fill); + let fill = node(&s, id).appearance.items.iter().position(|i| i.is_fill()).unwrap(); + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "plugin.test.engine.onfill", "item": fill})); + // Drawn, the gradient fills the triangle: a point of it outside the rectangle is painted. + let opts = vectorcraft_render::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let drawn = vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 40, 40, vectorcraft_geom::Affine::IDENTITY, &opts); + assert_ne!(drawn.pixel(15, 1), [255, 255, 255, 255], "drawn as a triangle"); + run(&mut s, "select.set", json!({"ids": [id.0]})); + run(&mut s, "object.expand", json!({"steps": 2})); + // The gradient's strips sit in a clip group whose clipping path is the shape filled. + let group = s.doc().unwrap().selection.objects[0]; + let clip = node(&s, group).children().unwrap()[0].clone(); + assert_eq!(clip.path_data().unwrap().bounds(), triangle().bounds(), "the triangle the canvas fills"); +} + +/// `CRAFT_PLUGIN_PAINTS_WASM=` saves a test live effect to try in the app +/// (`stroke-width-test-effect.wasm`): it draws a triangle over the area 100,80–300,230 while its +/// object's stroke is 5 pt wide, and hands the geometry back otherwise. +#[test] +fn stroke_width_test_effect() { + let Some(dir) = std::env::var_os("CRAFT_PLUGIN_PAINTS_WASM") else { return }; + let triangle = PathData::single(SubPath::polyline(&[Point::new(100.0, 230.0), Point::new(300.0, 230.0), Point::new(200.0, 80.0)], true)); + let manifest = r#"{"id":"org.example.strokewidth","name":"Stroke Width (test plug-in)","version":"1","kind":"effect", + "description":"Draws a triangle while the object's stroke is 5 pt wide.","params":{}}"#; + let src = tpl::when_given(manifest, tpl::Given::Input, r#""width":5.0"#, &json!({"objects": [{"path": triangle}]}).to_string()); + std::fs::write(std::path::Path::new(&dir).join("stroke-width-test-effect.wasm"), wat::parse_str(src).unwrap()).unwrap(); +} + #[test] fn plugin_management_commands() { let mut s = session(); diff --git a/crates/engine/src/tests_rasterfilters.rs b/crates/engine/src/tests_rasterfilters.rs index fe7be62089..fa08af2580 100644 --- a/crates/engine/src/tests_rasterfilters.rs +++ b/crates/engine/src/tests_rasterfilters.rs @@ -1,5 +1,5 @@ //! The Photoshop-style raster effects (Effect › Artistic, Blur › Radial Blur and Smart Blur, Brush Strokes, -//! Distort › Diffuse Glow, Glass and Ocean Ripple, Pixelate › Color Halftone, Crystallize, Mezzotint and Pointillize, Sharpen › Unsharp Mask, Sketch › Halftone Pattern, Texture › +//! Distort › Diffuse Glow, Glass and Ocean Ripple, Pixelate › Color Halftone, Crystallize, Mezzotint and Pointillize, Sharpen › Unsharp Mask, Sketch › Chalk & Charcoal, Chrome, Graphic Pen, Halftone Pattern and Reticulation, Texture › //! Craquelure, Grain, Mosaic Tiles, Patchwork, Stained Glass and Texturizer, Video): applied and //! edited as commands, listed in the catalogue, drawn on the canvas, and written to PDF and SVG //! as images of the effected object. @@ -31,8 +31,16 @@ const BRUSH_STROKES: [(&str, &str); 8] = [ ]; /// Effect › Artistic, at their defaults. -const ARTISTIC: [(&str, &str); 4] = - [("artistic.cutout", "{}"), ("artistic.filmGrain", "{}"), ("artistic.neonGlow", "{}"), ("artistic.posterEdges", "{}")]; +const ARTISTIC: [(&str, &str); 8] = [ + ("artistic.cutout", "{}"), + ("artistic.filmGrain", "{}"), + ("artistic.neonGlow", "{}"), + ("artistic.plasticWrap", "{}"), + ("artistic.posterEdges", "{}"), + ("artistic.smudgeStick", "{}"), + ("artistic.sponge", "{}"), + ("artistic.watercolor", "{}"), +]; /// Effect › Distort (Diffuse Glow with its highlights glowing from a low brightness up, as the /// striped art's reds are dark). @@ -44,7 +52,19 @@ const PIXELATE: [(&str, &str); 4] = [("pixelate.colorHalftone", "{}"), ("pixelate.crystallize", "{}"), ("pixelate.mezzotint", "{}"), ("pixelate.pointillize", "{}")]; /// Effect › Sketch, at their defaults. -const SKETCH: [(&str, &str); 1] = [("sketch.halftonePattern", "{}")]; +const SKETCH: [(&str, &str); 11] = [ + ("sketch.basRelief", "{}"), + ("sketch.chalkCharcoal", "{}"), + ("sketch.charcoal", "{}"), + ("sketch.chrome", "{}"), + ("sketch.graphicPen", "{}"), + ("sketch.halftonePattern", "{}"), + ("sketch.notePaper", "{}"), + ("sketch.photocopy", "{}"), + ("sketch.plaster", "{}"), + ("sketch.reticulation", "{}"), + ("sketch.stamp", "{}"), +]; /// Effect › Texture, at their defaults. const TEXTURE: [(&str, &str); 6] = [ @@ -196,6 +216,11 @@ fn artistic_settings_survive_a_save_and_open() { json!({"edgeThickness": 4.0, "edgeIntensity": 5.0, "posterization": 1.0}), [json!({"edgeIntensity": 0.0}), json!({"posterization": 6.0})], ), + ( + "artistic.plasticWrap", + json!({"highlightStrength": 18.0, "detail": 10.0, "smoothness": 8.0}), + [json!({"highlightStrength": 5.0}), json!({"highlightStrength": 0.0})], + ), ] { let (mut s, g) = striped(); // Black and a grey beside the reds: Cutout puts the grey with black at 2 levels and apart diff --git a/crates/engine/src/tests_swatchlib.rs b/crates/engine/src/tests_swatchlib.rs index 0783e159dc..0f25a04ec3 100644 --- a/crates/engine/src/tests_swatchlib.rs +++ b/crates/engine/src/tests_swatchlib.rs @@ -392,6 +392,50 @@ fn loaded_libraries_copy_into_the_user_folder_without_replacing_files() { let _ = std::fs::remove_dir_all(dir); } +/// A color book opened from a host temporary path (macOS sandbox copies) is stored under its title +/// when copied into the user library folder (#2996). +#[test] +fn copying_a_color_book_from_a_temporary_path_uses_its_title() { + fn acb_str(out: &mut Vec, s: &str) { + let units: Vec = s.encode_utf16().collect(); + out.extend((units.len() as u32).to_be_bytes()); + units.iter().for_each(|u| out.extend(u.to_be_bytes())); + } + let mut bytes = b"8BCB".to_vec(); + bytes.extend(1u16.to_be_bytes()); + bytes.extend(3000u16.to_be_bytes()); + for s in ["$$$/colorbook/Test/title=Test Book^R", "TEST ", " C", "a book"] { + acb_str(&mut bytes, s); + } + bytes.extend(1u16.to_be_bytes()); + bytes.extend(7u16.to_be_bytes()); + bytes.extend(0u16.to_be_bytes()); + bytes.extend(0u16.to_be_bytes()); + acb_str(&mut bytes, "185"); + bytes.extend(b"TST001"); + bytes.extend([228, 0, 43]); + bytes.extend(b"spflspot"); + + let dir = temp_dir("acb-temp"); + let user = dir.join("user"); + let elsewhere = dir.join("elsewhere"); + std::fs::create_dir_all(&user).unwrap(); + std::fs::create_dir_all(&elsewhere).unwrap(); + let source = elsewhere.join("tmp1F2C.tmp.acb"); + std::fs::write(&source, &bytes).unwrap(); + let source = source.to_string_lossy().to_string(); + + let mut s = session(); + s.swatch_libraries.set_user_dir(Some(user.to_string_lossy().to_string())); + let loaded = run(&mut s, "swatch.library.load", json!({ "path": source }))["library"].clone(); + assert_eq!(run(&mut s, "swatch.library.get", json!({ "library": loaded }))["name"], "Test Book®"); + let r = run(&mut s, "swatch.library.copyToUser", json!({ "library": loaded })); + assert_eq!((r["library"].as_str(), r["name"].as_str(), r["copied"].as_bool()), (Some("user/Test Book®.acb"), Some("Test Book®"), Some(true))); + assert_eq!(r["path"], user.join("Test Book®.acb").to_string_lossy().to_string()); + assert_eq!(std::fs::read(user.join("Test Book®.acb")).unwrap(), bytes); + let _ = std::fs::remove_dir_all(dir); +} + #[test] fn a_library_group_stays_one_group_when_a_swatch_has_its_name() { use vectorcraft_testkit::ase::{Block, ase}; diff --git a/crates/engine/src/tests_textedit.rs b/crates/engine/src/tests_textedit.rs index 917a011565..4a761ec0c0 100644 --- a/crates/engine/src/tests_textedit.rs +++ b/crates/engine/src/tests_textedit.rs @@ -361,6 +361,26 @@ fn the_touch_type_tool_drags_a_character() { assert!(near(moved_by(&before, &after, 2), (0.0, 0.0)), "{:?}", moved_by(&before, &after, 2)); } +/// Arrow keys with the Touch Type tool nudge the selected character by the keyboard increment. +#[test] +fn touch_type_arrow_keys_nudge_the_selected_character() { + let mut s = session(); + let id = NodeId(s.execute("text.create", &json!({"x": 100, "y": 100, "text": "Type", "size": 40})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": []})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("touchType", v).unwrap(); + let t = obj(&s, id); + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t); + let y = lay.glyphs.iter().find(|g| g.byte == 1).unwrap(); + let at = t.xf * (y.origin + vectorcraft_geom::Vec2::new(y.advance / 2.0, -10.0)); + click(&mut s, at.x, at.y); + let before = glyph_pens(&s, id); + s.tool_key(vectorcraft_tools::ToolKey::Right, Mods::default(), v).unwrap(); + let after = glyph_pens(&s, id); + assert!(near(moved_by(&before, &after, 1), (1.0, 0.0)), "{:?}", moved_by(&before, &after, 1)); + assert_eq!(undo_labels(&s).iter().filter(|l| *l == "Touch Type").count(), 1); +} + #[test] fn type_tool_typing_is_one_undo_step() { let mut s = session(); diff --git a/crates/engine/src/tests_variables.rs b/crates/engine/src/tests_variables.rs index 0b5698abc6..7d2b1dadbb 100644 --- a/crates/engine/src/tests_variables.rs +++ b/crates/engine/src/tests_variables.rs @@ -131,6 +131,44 @@ fn mismatched_and_missing_bindings_are_skipped_and_counted() { assert_eq!(plain(&s, t), "y"); } +/// A row with no value for any bound variable, such as one from Import Data Sets… before anything +/// is bound, applies nothing, and the reply's `warning` names it. A bound variable with a value in +/// the row gives no warning, even when its object is locked and skipped. +#[test] +fn a_row_with_no_value_for_a_bound_variable_warns_that_nothing_was_applied() { + let mut s = session(); + let t = text(&mut s, "x"); + s.execute("dataset.import", &json!({"csv": "name,Name,Title\nA,Ann,Boss\nB,Bob,Chief\n"})).unwrap(); + let warning = |row: &str| format!("nothing in data set {row} was applied: no object is bound to a variable it has a value for"); + let v = s.execute("dataset.select", &json!({"name": "A"})).unwrap(); + assert_eq!((v["applied"].as_u64(), v["skipped"].as_u64(), &v["warning"]), (Some(0), Some(0), &json!(warning("A"))), "{v}"); + let v = s.execute("dataset.next", &json!({})).unwrap(); + assert_eq!(v["warning"], json!(warning("B")), "{v}"); + let v = s.execute("dataset.prev", &json!({})).unwrap(); + assert_eq!(v["warning"], json!(warning("A")), "{v}"); + assert_eq!(plain(&s, t), "x"); + + // A bound variable that the row has no value for still applies nothing. + s.execute("variable.define", &json!({"name": "Other", "kind": "text"})).unwrap(); + s.execute("variable.bind", &json!({"variable": "Other", "ids": [t.0]})).unwrap(); + let v = s.execute("dataset.select", &json!({"name": "B"})).unwrap(); + assert_eq!((v["applied"].as_u64(), v["skipped"].as_u64(), &v["warning"]), (Some(0), Some(1), &json!(warning("B"))), "{v}"); + + // Bound to a variable with a value, the row applies it and gives no warning. + s.execute("variable.bind", &json!({"variable": "Title", "ids": [t.0]})).unwrap(); + let v = s.execute("dataset.select", &json!({"name": "A"})).unwrap(); + assert_eq!(v["applied"].as_u64(), Some(1), "{v}"); + assert!(v.get("warning").is_none(), "{v}"); + assert_eq!(plain(&s, t), "Boss"); + + // Locked art is skipped, and its binding still counts as bound. + s.execute("select.set", &json!({"ids": [t.0]})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let v = s.execute("dataset.select", &json!({"name": "B"})).unwrap(); + assert_eq!(v["applied"].as_u64(), Some(0), "{v}"); + assert!(v.get("warning").is_none(), "{v}"); +} + #[test] fn deleting_a_variable_cleans_bindings_values_and_leaves_datasets_alone() { let mut s = session(); diff --git a/crates/engine/src/tests_xform.rs b/crates/engine/src/tests_xform.rs index 499c1598e4..e97d261bdf 100644 --- a/crates/engine/src/tests_xform.rs +++ b/crates/engine/src/tests_xform.rs @@ -816,6 +816,50 @@ fn artboard_set_props_scales_art_only_when_asked_and_resized() { assert!(s.execute("artboard.setProps", &json!({"index": 9, "width": 10, "scaleArt": true})).is_err()); } +/// #1482: `artboard.setProps {artboards}` resizes several artboards in one undo step, and with +/// `scaleArt` each object scales once, with the artboard it was inside before the change: art that +/// the first artboard's new size moves into the second stays as the first one put it, and art +/// inside two overlapping artboards goes with the first one listed. An empty list, an artboard +/// listed twice, an entry without an index and an index that names no artboard are refused. +#[test] +fn artboard_set_props_resizes_several_artboards_and_scales_each_object_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2, "created": null})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 0, "x": 0, "y": 0})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 1, "x": 120, "y": 0})).unwrap(); + let art = rect(&mut s, 70.0, 10.0, 10.0, 10.0); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let out = s + .execute( + "artboard.setProps", + &json!({"artboards": [{"index": 0, "width": 200}, {"index": 1, "width": 200, "name": " Back\t"}], "scaleArt": true}), + ) + .unwrap(); + assert_eq!(out["scaled"], json!([art.0])); + let boards = &s.doc().unwrap().doc.artboards; + assert_eq!((boards[0].rect, boards[1].rect), (Rect::new(0.0, 0.0, 200.0, 100.0), Rect::new(120.0, 0.0, 320.0, 100.0))); + assert_eq!(boards[1].name, "Back"); + assert_eq!(bounds(&s, art), Rect::new(140.0, 10.0, 160.0, 20.0), "scaled once, with Artboard 1"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(*s.doc().unwrap().doc, *before); + // Artboard 2 over Artboard 1's right half: the art inside both goes with Artboard 2, listed first. + s.execute("artboard.setProps", &json!({"index": 1, "x": 50})).unwrap(); + s.execute("artboard.setProps", &json!({"artboards": [{"index": 1, "width": 200}, {"index": 0, "width": 200}], "scaleArt": true})).unwrap(); + assert_eq!(bounds(&s, art), Rect::new(90.0, 10.0, 110.0, 20.0)); + let was = s.doc().unwrap().doc.clone(); + for bad in [ + json!({"artboards": []}), + json!({"artboards": [{"index": 0, "width": 50}, {"index": 0, "height": 50}]}), + json!({"artboards": [{"index": 0, "width": 50}, {"height": 50}]}), + json!({"artboards": [{"index": 0, "width": 50}, {"index": 2, "height": 50}]}), + ] { + assert!(s.execute("artboard.setProps", &bad).is_err(), "{bad}"); + assert_eq!(*s.doc().unwrap().doc, *was, "{bad}"); + } +} + /// Move Artwork is independent of scaling and takes only fully contained art and board guides. #[test] fn coordinate_moves_honor_move_art_and_keep_resize_behavior() { diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 1d371d00c3..1a68096888 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -21,6 +21,8 @@ pub struct ViewInfo { pub snap_to_pixel: bool, /// View → Snap to Point: picked points (a transform's reference point) land on anchors. pub snap_to_point: bool, + /// View → Snap to Glyph: drawing snaps to live-text baselines and glyph bounds (needs Smart Guides). + pub snap_to_glyph: bool, /// View → Show Corner Widget. pub corner_widgets: bool, /// The document window (none headless): screen-fixed widgets sit in it. @@ -40,6 +42,7 @@ impl Default for ViewInfo { show_bbox: true, snap_to_pixel: false, snap_to_point: true, + snap_to_glyph: false, corner_widgets: true, screen: None, artboard: 0, @@ -202,11 +205,13 @@ impl Session { // wins instead of pixels quietly rounding every drag to whole points (#1816). snap_to_pixel: view.snap_to_pixel && !view.snap_to_grid, snap_to_point: view.snap_to_point, + snap_to_glyph: view.snap_to_glyph && view.smart_guides && !view.snap_to_grid, corner_widgets: view.corner_widgets, fill_active: self.fill_active, gradient_stop: self.selected_stop(), appearance_item: self.appearance_item(), constrain_angle: self.prefs.constrain_angle, + keyboard_increment: self.prefs.keyboard_increment, freeform_point: self.selected_freeform_point(), raster_sample: self.prefs.eyedropper.sample_size, preview_bounds: self.prefs.use_preview_bounds, diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index ba9539de80..74ccfc0b4f 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -227,6 +227,43 @@ fn live_objects_draw_through_new_color_settings() { } } +/// The art drawn for 3D effects and color adjustments follows the Color Settings: in the next +/// frame, a CMYK cyan rectangle with Revolve, with Extrude & Bevel, with Inflate, with Rotate, with +/// Brightness/Contrast, and a group holding it with Brightness/Contrast, draw through the new +/// working CMYK profile. +#[test] +fn effect_art_draws_through_new_color_settings() { + let _g = settings(); + let old = cms::active_settings(); + let cyan = json!({"c": 100, "m": 0, "y": 0, "k": 0}); + let brighter = json!({"brightness": 30}); + let cases = [ + ("the revolved rectangle", "threeD.revolve", json!({}), false), + ("the extruded rectangle", "threeD.extrude", json!({}), false), + ("the inflated rectangle", "threeD.inflate", json!({}), false), + ("the rotated rectangle", "threeD.rotate", json!({}), false), + ("the adjusted rectangle", "adjust.brightnessContrast", brighter.clone(), false), + ("the adjusted group", "adjust.brightnessContrast", brighter, true), + ]; + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let frame = |r: &mut Renderer, s: &Session| r.render(&s.doc().unwrap().doc, 400, 300, Affine::IDENTITY, &opts).pixels; + for (what, effect, params, grouped) in cases { + let mut s = session(); + let shape = rect(&mut s, 150.0, 60.0, 60.0, 120.0); + exec(&mut s, "paint.setFill", json!({"ids": [shape.0], "color": cyan})); + let target = if grouped { id_of(&exec(&mut s, "object.group", json!({"ids": [shape.0]}))) } else { shape }; + exec(&mut s, "effect.apply", json!({"ids": [target.0], "effect": effect, "params": params})); + let mut r = Renderer::new(); + let before = frame(&mut r, &s); + s.execute("edit.colorSettings", &json!({"cmyk": cms::DEVICE_CMYK})).unwrap(); + let fresh = frame(&mut Renderer::new(), &s); + let warm = frame(&mut r, &s); + cms::set_active(&old).unwrap(); + assert!(fresh != before, "{what}: the new profile changes the frame"); + assert!(warm == fresh, "{what}: drawn as a new renderer draws it"); + } +} + /// #2276: with a working RGB space other than sRGB, the Eyedropper takes an image's sRGB pixel /// into the working space, so the sampled fill shows as the pixel it was picked from. #[test] diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index a19d5caa8a..93e53dbdea 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -219,6 +219,8 @@ fn structured_junk() { ("path.insertAnchor", json!({"id": 2, "subpath": 0, "segment": 99, "t": 5})), ("path.insertAnchor", json!({"id": 2, "subpath": 7, "segment": 0, "t": -1})), ("path.setHandle", json!({"id": 2, "subpath": 0, "anchor": 100, "which": "in", "x": 0, "y": 0})), + ("path.moveAnchor", json!({"id": 2, "subpath": 0, "anchor": 100, "x": 0, "y": 0})), + ("path.moveAnchor", json!({"id": 2, "subpath": 0, "anchor": 0, "x": 1e308, "y": -1e308})), ("path.removeAnchor", json!({"id": 2, "subpath": 0, "anchor": 0})), ("path.split", json!({"id": 2, "subpath": 0, "segment": 1000, "t": 0.5})), ("path.reshapeSegment", json!({"id": 2, "subpath": 0, "segment": 0, "t": 2.0, "dx": 1e308, "dy": 0})), @@ -329,10 +331,20 @@ fn structured_junk() { ("effect.apply", json!({"effect": "pixelate.crystallize", "params": {"cellSize": -1e308}})), ("effect.apply", json!({"effect": "pixelate.mezzotint", "params": {"type": 5}})), ("effect.apply", json!({"effect": "pixelate.pointillize", "params": {"cellSize": "NaN"}})), + ("effect.apply", json!({"effect": "artistic.smudgeStick", "params": {"strokeLength": 1e308, "highlightArea": "NaN", "intensity": [1]}})), + ("effect.apply", json!({"effect": "artistic.sponge", "params": {"brushSize": -1e308, "definition": 1e308, "smoothness": null}})), + ("effect.apply", json!({"effect": "artistic.watercolor", "params": {"brushDetail": "1e999", "shadowIntensity": -1, "texture": 1e308}})), ("effect.apply", json!({"effect": "artistic.cutout", "params": {"levels": 1e308, "edgeSimplicity": "NaN", "edgeFidelity": -1e308}})), ("effect.apply", json!({"effect": "artistic.neonGlow", "params": {"glowSize": -1e308, "glowBrightness": "1e999", "color": [1]}})), ("effect.apply", json!({"effect": "artistic.posterEdges", "params": {"edgeThickness": 1e308, "edgeIntensity": [], "posterization": -7}})), + ("effect.apply", json!({"effect": "sketch.chrome", "params": {"detail": -1e308, "smoothness": "NaN"}})), + ("effect.apply", json!({"effect": "sketch.graphicPen", "params": {"strokeLength": -1e308, "lightDarkBalance": "NaN", "strokeDirection": 3}})), ("effect.apply", json!({"effect": "sketch.halftonePattern", "params": {"size": -1e308, "contrast": "NaN", "patternType": 3}})), + ("effect.apply", json!({"effect": "sketch.basRelief", "params": {"detail": "NaN", "smoothness": 1e308, "lightDirection": 3}})), + ("effect.apply", json!({"effect": "sketch.charcoal", "params": {"thickness": 1e308, "detail": -1e308, "lightDarkBalance": [1]}})), + ("effect.apply", json!({"effect": "sketch.photocopy", "params": {"detail": "1e999", "darkness": null}})), + ("effect.apply", json!({"effect": "sketch.stamp", "params": {"lightDarkBalance": -1e308, "smoothness": "NaN"}})), + ("effect.apply", json!({"effect": "sketch.reticulation", "params": {"density": "NaN", "foregroundLevel": -1e308, "backgroundLevel": 1e308}})), ("effect.apply", json!({"effect": "texture.craquelure", "params": {"crackSpacing": -1e308, "crackDepth": "NaN", "crackBrightness": 1e308}})), ("effect.apply", json!({"effect": "texture.grain", "params": {"intensity": 1e308, "contrast": [1], "grainType": 7}})), ("effect.apply", json!({"effect": "texture.mosaicTiles", "params": {"tileSize": "1e999", "groutWidth": -1, "lightenGrout": null}})), @@ -353,6 +365,9 @@ fn structured_junk() { ("object.path.offsetPath", json!({"offset": 1e308})), ("object.path.offsetPath", json!({"offset": -1e308})), ("object.path.simplify", json!({"tolerance": -1, "cornerAngle": 1e308})), + ("object.path.simplify", json!({"level": 1e308, "tolerance": "x"})), + ("object.path.simplify", json!({"level": -1e308, "auto": "yes"})), + ("object.path.simplify", json!({"auto": true, "level": [1]})), ( "shape.rectangularGrid", json!({"x": 0, "y": 0, "width": 1e308, "height": -1e308, "rows": 999, "columns": u64::MAX, "rowSkew": 1e308, "columnSkew": -1e308, "frame": false, "fill": true}), diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index d09817c679..aac355e5b9 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -988,7 +988,8 @@ fn styles(what: &str, data: &str) -> Result<(), TestCaseError> { } /// Libraries panel library file `data` imported, then each kind's first item used on the rich -/// document and moved into its first group, the group deleted and the library exported (#926). +/// document, moved into its first group and next to its kind's last item, the group moved and +/// deleted and the library exported (#926). fn libraries(what: &str, data: &str) -> Result<(), TestCaseError> { survive_library(what, "library.import", data, |s, r| { let lib = r["id"].clone(); @@ -1001,9 +1002,17 @@ fn libraries(what: &str, data: &str) -> Result<(), TestCaseError> { let _ = no_panic(s.execute("library.use", &json!({"library": lib, "kind": kind, "item": item[key]}))); let to = json!({"library": lib, "kind": kind, "item": item[key], "group": got["groups"][0]["name"]}); let _ = no_panic(s.execute("library.moveItem", &to)); + // Next to the last item of its kind, whatever group that is in. + let last = got[list].as_array().and_then(|a| a.last()).map(|v| v[key].clone()).unwrap_or_default(); + for side in ["before", "after"] { + let _ = no_panic(s.execute("library.moveItem", &json!({"library": lib, "kind": kind, "item": item[key], side: last}))); + } } } if let Some(g) = got["groups"].get(0) { + for to in [0, 1, 1_000_000] { + let _ = no_panic(s.execute("library.moveGroup", &json!({"library": lib, "group": g["name"], "to": to}))); + } let _ = no_panic(s.execute("library.deleteGroup", &json!({"library": lib, "group": g["name"]}))); } let _ = no_panic(s.execute("library.export", &json!({"library": lib}))); diff --git a/crates/engine/tests/plugin_export.rs b/crates/engine/tests/plugin_export.rs new file mode 100644 index 0000000000..868ec71e92 --- /dev/null +++ b/crates/engine/tests/plugin_export.rs @@ -0,0 +1,217 @@ +//! Exporter plug-ins (`"kind": "exporter"`, docs/plugins.md › Exporters) through the engine: the +//! formats they add to `document.formats` and `document.export`, the document and parameters they +//! are given, and what is written when they succeed, decline, misbehave or are cancelled. +//! +//! A test binary of its own: installed plug-ins are process-wide, and the unit tests that check the +//! exact list of formats would see these ones. +// Integration tests: 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::path::PathBuf; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; +use vectorcraft_engine::cmd::fileio; +use vectorcraft_engine::{EngineError, Session}; +use vectorcraft_plugins::wat::{self as tpl, Echo}; + +/// A document with one rectangle. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap(); + s +} + +/// Installs the plug-in written in WAT `src` → its `plugin.list` entry. +fn install(s: &mut Session, src: &str) -> Value { + let wasm = wat::parse_str(src).unwrap_or_else(|e| panic!("bad test WAT: {e}")); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm)})).unwrap() +} + +/// The file a `document.export` without a path gives back. +fn exported(r: &Value) -> Vec { + vectorcraft_format::base64_decode(r["dataBase64"].as_str().expect("dataBase64")).unwrap() +} + +/// A fresh folder for files this test writes. +fn tmp_dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("vc-plugin-export-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +fn path_of(p: &std::path::Path) -> String { + p.to_string_lossy().into_owned() +} + +#[test] +fn an_exporter_adds_a_write_only_format_while_it_is_installed() { + let mut s = session(); + let entry = install(&mut s, &tpl::returning(&tpl::exporter("test.list", r#"["tsl","tsl2"]"#, "{}"), r#"{"dataBase64":""}"#)); + assert_eq!((&entry["kind"], &entry["format"], &entry["extensions"]), (&json!("exporter"), &json!("plugin.test.list"), &json!(["tsl", "tsl2"]))); + let formats = s.execute("document.formats", &json!({})).unwrap(); + let listed = formats["formats"].as_array().unwrap().iter().find(|f| f["id"] == "plugin.test.list").expect("listed"); + assert_eq!((&listed["label"], &listed["extensions"]), (&json!("Test test.list"), &json!(["tsl", "tsl2"]))); + assert_eq!((&listed["read"], &listed["write"], &listed["plugin"]), (&json!(false), &json!(true), &json!("test.list"))); + assert!(formats["writable"].as_array().unwrap().contains(&json!("plugin.test.list"))); + assert!(!formats["readable"].as_array().unwrap().contains(&json!("plugin.test.list"))); + assert!(fileio::export_extensions().contains(&"tsl")); + assert_eq!(fileio::format(".TSL2").map(|f| f.id), Some("plugin.test.list"), "by any of its extensions, in any case"); + assert_eq!(fileio::format("plugin.test.list").map(|f| f.label), Some("Test test.list")); + + s.execute("plugin.remove", &json!({"id": "test.list"})).unwrap(); + let formats = s.execute("document.formats", &json!({})).unwrap(); + assert!(!formats["writable"].as_array().unwrap().contains(&json!("plugin.test.list"))); + assert!(fileio::format("tsl").is_none()); + let e = s.execute("document.export", &json!({"format": "plugin.test.list"})).unwrap_err(); + assert!(e.to_string().contains("unknown format"), "{e}"); +} + +/// The exporter is given the document as a native file's JSON: what `document.save` writes before +/// the data of large images, which stays behind (compact, where a save of a small document is +/// indented). +#[test] +fn the_exporter_is_given_the_native_file_s_json() { + let mut s = session(); + install(&mut s, &tpl::echo_exporter(&tpl::exporter("test.input", r#"["tsi"]"#, "{}"), Echo::Input)); + // Noise, so the PNG is large enough to go after the JSON in a native file. + let mut seed = 1_u32; + let noise = image::RgbaImage::from_fn(64, 64, |_, _| { + seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345); + let [r, g, b, _] = seed.to_be_bytes(); + image::Rgba([r, g, b, 255]) + }); + let mut png = vec![]; + noise.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + assert!(png.len() >= vectorcraft_format::INLINE_MAX, "{} bytes", png.len()); + s.execute("file.place", &json!({"name": "noise.png", "dataBase64": vectorcraft_format::base64_encode(&png)})).unwrap(); + + let r = s.execute("document.export", &json!({"format": "plugin.test.input"})).unwrap(); + assert_eq!(r["format"], "plugin.test.input"); + let given = exported(&r); + let saved = exported(&s.execute("document.save", &json!({})).unwrap()); + assert!(saved.len() > given.len() + png.len(), "the image data follows the JSON in the saved file"); + let doc: Value = serde_json::from_slice(&given).unwrap(); + let saved_json: Value = serde_json::from_slice(vectorcraft_format::json_part(&saved)).unwrap(); + assert_eq!(doc, saved_json, "the saved file's JSON"); + assert!(!given.contains(&b'\n'), "without indentation"); + assert_eq!((&doc["format"], &doc["version"]), (&json!("vectorcraft"), &json!(vectorcraft_format::VERSION))); + let images = doc["images"].as_object().unwrap(); + let image = images.values().next().unwrap(); + assert_eq!(images.len(), 1); + assert!(image.get("blob").is_some() && image.get("data").is_none(), "{image}"); +} + +#[test] +fn the_exporter_is_given_its_parameters_and_the_file_it_writes() { + let dir = tmp_dir("params"); + let mut s = session(); + let params = r#"{"density":{"type":"number","min":0,"max":10,"default":4},"mode":{"type":"choice","options":["fast","fine"],"default":"fast"}}"#; + install(&mut s, &tpl::echo_exporter(&tpl::exporter("test.params", r#"["tsp","tsq"]"#, params), Echo::Params)); + let sent = |r: &Value| -> Value { serde_json::from_slice(&exported(r)).unwrap() }; + + // The defaults, and without a path its first extension and the document's name. + let r = s.execute("document.export", &json!({"format": "plugin.test.params"})).unwrap(); + let got = sent(&r); + assert_eq!((&got["density"], &got["mode"]), (&json!(4.0), &json!("fast"))); + assert_eq!((&got["_context"]["mode"], &got["_context"]["extension"]), (&json!("export"), &json!("tsp"))); + let title = s.doc().unwrap().doc.title.clone(); + assert_eq!(got["_context"]["name"], json!(title)); + + // Given ones, clamped as a filter's are, and the path's extension when the exporter lists it. + let path = dir.join("Poster.tsq"); + let r = s.execute("document.export", &json!({"path": path_of(&path), "params": {"density": 12, "mode": "fine"}})).unwrap(); + assert_eq!(r["format"], "plugin.test.params"); + let written: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(written, json!({"density": 10.0, "mode": "fine", "_context": {"mode": "export", "extension": "tsq", "name": "Poster"}})); + + // Bad parameters fail before the plug-in runs, and nothing is written. + let bad = dir.join("Bad.tsp"); + let e = s.execute("document.export", &json!({"path": path_of(&bad), "params": {"mode": "slow"}})).unwrap_err(); + assert!(matches!(e, EngineError::BadParams { .. }), "{e}"); + assert!(!bad.exists()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Only the selected objects, with `selectedOnly`, as for the built-in formats. +#[test] +fn selected_only_hands_over_the_selection() { + let mut s = session(); + install(&mut s, &tpl::echo_exporter(&tpl::exporter("test.selection", r#"["tse"]"#, "{}"), Echo::Input)); + let ellipse = s.execute("shape.ellipse", &json!({"x": 200, "y": 10, "width": 50, "height": 50})).unwrap()["id"].clone(); + s.execute("select.set", &json!({"ids": [ellipse]})).unwrap(); + let count = |r: &Value| String::from_utf8(exported(r)).unwrap().matches("\"anchors\"").count(); + let all = count(&s.execute("document.export", &json!({"format": "plugin.test.selection"})).unwrap()); + let selected = count(&s.execute("document.export", &json!({"format": "plugin.test.selection", "selectedOnly": true})).unwrap()); + assert!(selected >= 1 && selected < all, "{selected} of {all} paths"); +} + +/// A built-in format keeps its extension: an exporter that lists `svg` too writes it only when +/// asked for by its format id. +#[test] +fn built_in_formats_keep_their_extensions() { + let dir = tmp_dir("builtin"); + let mut s = session(); + install(&mut s, &tpl::echo_exporter(&tpl::exporter("test.svgtoo", r#"["tsv","svg"]"#, "{}"), Echo::Params)); + assert_eq!(fileio::format("svg").map(|f| f.id), Some("svg")); + let svg = dir.join("a.svg"); + s.execute("document.export", &json!({"path": path_of(&svg)})).unwrap(); + assert!(String::from_utf8(std::fs::read(&svg).unwrap()).unwrap().contains("= wait && took < Duration::from_secs(10), "stopped while running, not before: {took:?}"); +} diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 432a3dd233..f12e5953b1 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -53,7 +53,7 @@ use vectorcraft_color::{BlendMode, Paint}; use vectorcraft_doc::cmyk::Inks; use vectorcraft_doc::{ Appearance, AppearanceItem, Artboard, ColorMode, Dash, Document, FillLayer, ImageBlob, ImageObject, Knockout, LayerColor, LineCap, LineJoin, - LinkInfo, Node, NodeId, NodeKind, OpacityMask, PatternDef, StrokeLayer, + LinkInfo, Node, NodeId, NodeKind, OpacityMask, PatternDef, StrokeLayer, Unit, }; use vectorcraft_geom::{FillRule, PathData}; @@ -80,6 +80,19 @@ const MAX_PIXELS: u64 = 1 << 25; const MAX_HEX: usize = (MAX_PIXELS as usize) * 10; /// Largest side of the document and its artboards (points). const MAX_SIDE: f64 = 1e6; + +/// `%AI5_RulerUnits` → [`Unit`] (Illustrator 7 spec table 3; centimeters is 4; pixels is 6 in later files). +fn ruler_unit(v: u8) -> Option { + Some(match v { + 0 => Unit::Inches, + 1 => Unit::Millimeters, + 2 => Unit::Points, + 3 => Unit::Picas, + 4 => Unit::Centimeters, + 6 => Unit::Pixels, + _ => return None, + }) +} /// Art space (y up) → a pattern's space in the document's terms (y down). const FLIP: Affine = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0]); /// Most patterns read (others can't fill art). @@ -507,6 +520,8 @@ struct Reader<'a> { /// (see [`Reader::ensure_space`]); 1 (no scaling) when the file doesn't declare one, `None` /// when the declared factor is not applied ([`read`]). large_canvas: Option, + /// `%AI5_RulerUnits` from the header (Illustrator 7 spec table 3, plus centimeters and pixels). + ruler_units: Option, /// This reader reads a pattern's definition (see [`Reader::define_pattern`]). pattern: Option, /// The tile (y down) of each pattern read, by name. @@ -643,6 +658,7 @@ impl<'a> Reader<'a> { art_size: None, template_center: None, large_canvas: None, + ruler_units: None, pattern: None, pattern_tiles: HashMap::new(), text: None, @@ -773,6 +789,11 @@ impl<'a> Reader<'a> { self.cropmarks = Some(r); } } + } else if self.frames.is_empty() + && let Some(v) = line.strip_prefix("AI5_RulerUnits:") + && let Ok(n) = v.trim().parse::() + { + self.ruler_units = Some(n); } else if let Some(v) = line.strip_prefix("AI5_ArtSize:") { self.art_size = two(v); } else if let Some(v) = line.strip_prefix("AI3_TemplateBox:") { @@ -1324,6 +1345,10 @@ impl<'a> Reader<'a> { // Far-Eastern type) and final-form positions (§15.3). "Tk" | "TK" | "TC" | "TW" | "Tq" | "Tc" | "Tw" | "Tm" | "Td" | "T*" | "TR" | "T+" | "T-" | "TV" | "Tv" | "Ty" | "TY" | "TG" | "Tg" | "Tu" | "Xu" => {} + // Hyphenation and tab-ruler attributes the reader doesn't keep either (§22): `Th` + // hyphen control, `XL` hyphenation language, `Xb`/`XB` a tab definition (and the `Xe` + // tab descriptions between them). + "Th" | "XL" | "Xb" | "XB" | "Xe" => {} "TE" => self.te(&vals), // An image whose samples follow in comment lines (read at `%AI5_EndRaster`). "XI" if self.raster.is_some() => { @@ -2277,6 +2302,9 @@ impl<'a> Reader<'a> { let (swatches, groups) = vectorcraft_color::default_swatches(ColorMode::Cmyk.model()); (doc.swatches, doc.swatch_groups) = (swatches.into(), groups.into()); } + if let Some(u) = self.ruler_units.and_then(ruler_unit) { + doc.units = u; + } for n in &self.spots { if doc.swatch(&n.name).is_none() { doc.swatches.push(Swatch { name: n.name.clone(), paint: Paint::solid(n.color), global: true, spot: n.spot }); diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index e6fd8defbe..07ffb07286 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -21,7 +21,7 @@ //! ``` //! //! A style is *plain* when it is one fill and one stroke at most, in solid colours (a fill's gradient -//! is the object's own), and only effects read here (Outer Glow, Drop Shadow) after them. Such +//! is the object's own), and only effects read here (Outer Glow, Drop Shadow, Feather) after them. Such //! objects are read as themselves with that fill, stroke and those effects; others keep their //! drawn look. A fill's or stroke's style says whether it paints with `stroke fill Xd`. @@ -36,9 +36,10 @@ use super::obj::V; use super::paint; /// The filters a plain style may chain. -const PLAIN: [&str; 7] = - ["Chain Style Filter", "Stack Style Filter", "Stroke Style Filter", "Fill Style Filter", "Conduit Filter", "Blend Style Filter", GLOW]; +const PLAIN: [&str; 8] = + ["Chain Style Filter", "Stack Style Filter", "Stroke Style Filter", "Fill Style Filter", "Conduit Filter", "Blend Style Filter", GLOW, FEATHER]; const GLOW: &str = "Adobe Outer Glow"; // brand-ok: the filter's name in the files +const FEATHER: &str = "Adobe Feather"; // brand-ok: the filter's name in the files const SHADOW: &str = "Adobe Drop Shadow"; // brand-ok: the filter's name in the files /// A plain style's paint, as the object comes in. @@ -307,7 +308,7 @@ fn style(filters: &[Filter]) -> ArtStyle { } } for (i, f) in filters.iter().enumerate() { - let effect = f.name == GLOW || f.name == SHADOW; + let effect = f.name == GLOW || f.name == FEATHER || f.name == SHADOW; if !PLAIN.contains(&f.name.as_str()) && f.name != SHADOW { plain = false; } @@ -330,6 +331,12 @@ fn style(filters: &[Filter]) -> ArtStyle { params: json!({"mode": mode(2), "opacity": param("opac").unwrap_or(0.75) * 100.0, "blur": 2.0 * param("blur").unwrap_or(5.0), "color": color}), visible: true, }), + // LiveEffect XML uses `radius`; art styles abbreviate it `rad` (public scripting posts on applyEffect). + FEATHER => effects.push(Effect { + id: "stylize.feather".into(), + params: json!({"radius": param("rad").or_else(|| param("radius")).filter(|v| v.is_finite()).unwrap_or(5.0)}), + visible: true, + }), SHADOW => { let mut params = json!({ "mode": mode(1), @@ -440,6 +447,30 @@ mod tests { } } + #[test] + fn a_feather_reads_its_radius_from_rad() { + let data = b"/KnownStyle :\n(Soft) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Adobe Feather) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n12 /Real (rad) ,\n; /Dict ;\n /Part ,\n;\n"; + let styles = art_styles(data); + let [feather] = styles["Soft"].effects.as_slice() else { panic!() }; + assert_eq!((feather.id.as_str(), feather.params["radius"].as_f64()), ("stylize.feather", Some(12.0))); + } + + #[test] + fn a_feather_falls_back_to_radius_and_defaults_to_five_points() { + let with_name = b"/KnownStyle :\n(Soft) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Adobe Feather) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n3 /Real (radius) ,\n; /Dict ;\n /Part ,\n;\n"; + let styles = art_styles(with_name); + let [feather] = styles["Soft"].effects.as_slice() else { panic!() }; + assert_eq!(feather.params["radius"].as_f64(), Some(3.0)); + + let bare = b"/KnownStyle :\n(Soft) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Adobe Feather) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n; /Dict ;\n /Part ,\n;\n"; + let styles = art_styles(bare); + let [feather] = styles["Soft"].effects.as_slice() else { panic!() }; + assert_eq!(feather.params["radius"].as_f64(), Some(5.0)); + } + #[test] fn hostile_dash_offsets_and_width_profiles_are_tamed() { let mut f = Filter::default(); diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index cb700fbfc5..0ab7b1b67f 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use kurbo::{Point, Rect}; use vectorcraft_color::gradient::GradientKind; use vectorcraft_color::{BlendMode, Color, Paint}; -use vectorcraft_doc::{AppearanceItem, ColorMode, Document, Knockout, LayerColor, LineCap, LineJoin, Node, NodeKind}; +use vectorcraft_doc::{AppearanceItem, ColorMode, Document, Knockout, LayerColor, LineCap, LineJoin, Node, NodeKind, Unit}; use super::*; @@ -33,6 +33,20 @@ fn read_ok(body: &str) -> Structure { } } +#[test] +fn ruler_units_from_the_header_set_the_documents_units() { + let body = layer(""); + let with_mm = format!( + "%!PS-Adobe-3.0\n%%Creator: test\n%AI5_FileFormat 14.0\n%AI5_RulerUnits: 1\n%AI3_Cropmarks: 0 0 200 100\n%%EndComments\n%%BeginProlog\n%%EndProlog\n%%BeginSetup\n%%EndSetup\n{body}\n%%PageTrailer\ngsave annotatepage grestore showpage\n%%Trailer\n%%EOF\n" + ); + assert_eq!(read_ok(&with_mm).doc.units, Unit::Millimeters); + assert_eq!(read_ok(&stream(&body)).doc.units, Unit::Points, "default when the comment is absent"); + let with_in = with_mm.replace("AI5_RulerUnits: 1", "AI5_RulerUnits: 0"); + assert_eq!(read(with_in.as_bytes()).unwrap().doc.units, Unit::Inches); + let with_px = with_mm.replace("AI5_RulerUnits: 1", "AI5_RulerUnits: 6"); + assert_eq!(read(with_px.as_bytes()).unwrap().doc.units, Unit::Pixels); +} + /// The children of the first layer. fn art(doc: &Document) -> Vec> { doc.layers.first().and_then(|l| l.children()).cloned().unwrap_or_default() @@ -1229,6 +1243,25 @@ fn an_object_with_a_style_this_reads_comes_in_as_itself() { assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); } +#[test] +fn an_object_with_a_feather_style_comes_in_with_a_live_effect() { + let feather_style = "%AI9_BeginArtStyles\n\ + /KnownStyle :\n(Soft) /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(Fill Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/FillStyle : 0 O\n0 0 0 0 0 0 1 Xa\n0 1 Xd\n/Def ;\n (FillStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n\ + /BasicFilter :\n(Adobe Feather) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n8 /Real (rad) ,\n; /Dict ;\n /Part ,\n;\n\ + %AI9_EndArtStyles\n"; + let hidden_rect = rect_path(0.0, 0.0, 10.0, 10.0).replace('\n', "\n%_"); + let art_ = format!("0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{hidden_rect}f\n%_0 BB\n1 (Soft) XW\n", rect_path(0.0, 0.0, 10.0, 10.0)); + let r = read_ok(&format!("{feather_style}{}", layer(&art_))); + let a = art(&r.doc); + assert_eq!(a.len(), 1); + let [feather] = a[0].appearance.effects.as_slice() else { panic!("{:#?}", a[0].appearance) }; + assert_eq!((feather.id.as_str(), feather.params["radius"].as_f64()), ("stylize.feather", Some(8.0))); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); +} + #[test] fn a_bare_comment_line_in_a_prolog_leaves_its_end_alone() { // GUARDS: a bare `%` line's empty marker matched the empty begin marker of a section that has none. @@ -1429,3 +1462,39 @@ fn winding_declared_compound_members_keep_the_final_gradient() { let r = read_ok(&format!("{defs}{}", layer(&body.replace("1 D\n", "").replace("0 D\n", "")))); assert!(matches!(art(&r.doc)[0].kind, NodeKind::Group { .. })); } + +/// #779: path guides from Illustrator's `(op) *` operator (AI7 §6.1) import as guide paths. +#[test] +fn path_guides_from_the_star_operator() { + let line = |x0: f64, y0: f64, x1: f64, y1: f64| format!("{x0} {y0} m\n{x1} {y1} L\n(N) *\n"); + let body = format!("{RED}{}f\n{}{}", rect_path(0.0, 0.0, 50.0, 50.0), line(10.0, 20.0, 90.0, 20.0), "(N) *\n15 10 m\n15 80 L\n(N) *\n",); + let kids = art(&read_ok(&layer(&body)).doc); + assert_eq!(kids.len(), 3); + let guides = kids.iter().filter(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })).count(); + assert_eq!(guides, 2, "the two construction lines are guide paths"); + assert!(matches!(kids[0].kind, NodeKind::Path { guide: false, .. })); + for g in kids.iter().filter(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })) { + assert!(g.appearance.items.is_empty(), "an (N) guide is non-printing geometry with no paint"); + } +} + +/// Legacy version 7 writes `(N) *` before and after the path (§6). +#[test] +fn path_guides_wrapped_before_and_after_the_path() { + let body = "(N) *\n20 30 m\n80 30 L\n(N) *\n"; + let kids = art(&read_ok(&layer(body)).doc); + assert_eq!(kids.len(), 1); + assert!(matches!(kids[0].kind, NodeKind::Path { guide: true, .. })); +} + +/// A stroked guide keeps the stroke for display but stays a guide path. +#[test] +fn stroked_path_guides_from_the_star_operator() { + let body = "1 w\n0 0 0 1 k\n10 10 m\n90 10 L\n(S) *\n"; + let kids = art(&read_ok(&layer(body)).doc); + assert_eq!(kids.len(), 1); + let n = &kids[0]; + assert!(matches!(n.kind, NodeKind::Path { guide: true, .. })); + assert_eq!(n.appearance.items.len(), 1); + assert!(matches!(n.appearance.items[0], AppearanceItem::Stroke(_))); +} diff --git a/crates/eps/src/import/tests_illustrator.rs b/crates/eps/src/import/tests_illustrator.rs index eeff5610bf..19c79deeb8 100644 --- a/crates/eps/src/import/tests_illustrator.rs +++ b/crates/eps/src/import/tests_illustrator.rs @@ -121,6 +121,23 @@ fn a_postscript_ai_whose_layers_cant_be_read_says_why() { assert!(e.contains("`Adobe_packedarray`") && e.contains("its layers couldn't be read either") && e.contains("`frobnicate`"), "{e}"); } +/// A `.ai` in PostScript form (read through its layers) whose text carries hyphenation and +/// tab-ruler attributes: `XL` (hyphenation language), `Xb`/`XB` (a tab definition) and `Th` +/// (hyphen control). These keep no geometry, so the reader drops them rather than failing the +/// file the way it did before — the symptom seen on Illustrator 6/8 EPS files whose +/// `Adobe_level2_AI5` program can't be run. +#[test] +fn text_with_hyphenation_and_tab_attributes_opens_instead_of_failing() { + let text = "0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 9 Tf\n\ + %_ 0 XL\n36 0 Xb\nXB\n0 1 2 2 99 Th\n0 Ta\n(hi) Tx\nTO\n"; + // The operators sit on a visible layer (so they'd be reported as unknown, not quietly skipped + // on a hidden one), beside the square so the layer is never empty. + let src = NAMED_PROLOG.replace("S\nLB\n%AI5_EndLayer--\n%AI5_BeginLayer", &format!("S\n{text}LB\n%AI5_EndLayer--\n%AI5_BeginLayer")); + let r = import(src.as_bytes()).unwrap(); + assert!(!r.preview, "read through the layers, not a fallback preview"); + assert!(!r.warnings.iter().any(|w| w.contains("doesn't know") || w.contains("couldn't be read")), "{:?}", r.warnings); +} + /// An Illustrator 3 file of paths alone, as image editors export their paths (storytold/photocraft#6036): /// no prolog and no layers, the paths unpainted (`n` closes, `N` doesn't), a compound path of two. const PATHS_ONLY: &str = "%!PS-Adobe-2.0 EPSF-1.2\n%%Creator: an image editor\n%%BoundingBox: 0 0 200 100\n\ diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index df3b4c9cc7..c0cd26c315 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -2,7 +2,7 @@ //! carries (see `native`). The files here are small ones written by hand for the tests, with the //! operators seen in files their users own. -use vectorcraft_doc::{Document, LayerColor, Node, NodeKind}; +use vectorcraft_doc::{Document, LayerColor, Node, NodeKind, Unit}; use crate::import::import; @@ -73,6 +73,16 @@ fn names(d: &Document) -> Vec { d.layers.iter().map(|l| l.name.clone().unwrap_or_default()).collect() } +#[test] +fn native_import_keeps_ruler_units_from_editing_data() { + let art = layer("Art", true, &square(10, 10)); + let native = format!( + "%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 100 100\n%%HiResBoundingBox: 0 0 100 100\n%AI3_Cropmarks: 0 0 100 100\n%AI5_RulerUnits: 1\n%AI5_NumLayers: 1\n{art}%%Trailer\n" + ); + let r = import(&eps(&page_square(10, 10), &native)).unwrap(); + assert_eq!(r.document.units, Unit::Millimeters); +} + fn kinds(l: &Node) -> Vec<&'static str> { l.children() .into_iter() diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 751d3487a9..1317a3f457 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -163,6 +163,13 @@ fn preview_mime(bytes: &[u8]) -> &'static str { if bytes.starts_with(&[0xff, 0xd8]) { "image/jpeg" } else { vectorcraft_doc::links::PROXY_MIME } } +/// The JSON of a native file without the data after it (version 4 keeps images there): a +/// complete JSON value whose `images` give each image's MIME type and where its data was, without +/// the data. +pub fn json_part(file: &[u8]) -> &[u8] { + split_tail(file).0 +} + /// The JSON of a file and the data after it (v4), split at [`BLOB_MAGIC`] after the first JSON /// value. fn split_tail(text: &[u8]) -> (&[u8], &[u8]) { diff --git a/crates/format/tests/native_v4.rs b/crates/format/tests/native_v4.rs index 57f29c279e..a8071fa430 100644 --- a/crates/format/tests/native_v4.rs +++ b/crates/format/tests/native_v4.rs @@ -58,6 +58,19 @@ fn small_files_stay_plain_json_and_older_versions_inline() { assert_eq!(load(&v3).unwrap().images["big"].bytes, big.images["big"].bytes); } +/// `json_part` (what exporter plug-ins are given): the whole JSON value, without the data after +/// it; a file without such data is its JSON already. +#[test] +fn json_part_is_the_json_without_the_data_after_it() { + let big = save_with(&doc_with_image("big", INLINE_MAX + 10), &SaveOptions::default()).unwrap(); + let json = vectorcraft_format::json_part(&big); + assert!(json.len() < big.len() - INLINE_MAX && !has_tail(json)); + let v: Value = serde_json::from_slice(json).unwrap(); + assert!(v["images"]["big"].get("blob").is_some() && v["images"]["big"].get("data").is_none(), "{}", v["images"]); + let small = save_with(&doc_with_image("small", 100), &SaveOptions::default()).unwrap(); + assert_eq!(vectorcraft_format::json_part(&small), &small[..]); +} + #[test] fn damaged_offsets_are_refused_not_a_crash() { let d = doc_with_image("big", INLINE_MAX + 10); diff --git a/crates/geom/src/hit.rs b/crates/geom/src/hit.rs index 98242d9185..0358acac90 100644 --- a/crates/geom/src/hit.rs +++ b/crates/geom/src/hit.rs @@ -28,9 +28,11 @@ pub fn polygon_covers_rect(path: &BezPath, r: Rect, tol: f64) -> bool { // Convex: every turn goes the same way (straight runs allowed). let n = pts.len(); let mut sign = 0.0f64; + let mut turning = 0.0f64; for i in 0..n { let (a, b, c) = (pts[i], pts[(i + 1) % n], pts[(i + 2) % n]); let cross = (b - a).cross(c - b); + turning += cross.atan2((b - a).dot(c - b)); if cross.abs() <= 1e-9 { continue; } @@ -40,6 +42,10 @@ pub fn polygon_covers_rect(path: &BezPath, r: Rect, tol: f64) -> bool { return false; } } + // A simple convex polygon turns through exactly one full revolution; a star winds more. + if (turning.abs() - std::f64::consts::TAU).abs() > 1e-6 { + return false; + } let inner = r.inflate(-tol, -tol); sign != 0.0 && [Point::new(inner.x0, inner.y0), Point::new(inner.x1, inner.y0), Point::new(inner.x1, inner.y1), Point::new(inner.x0, inner.y1)] @@ -113,7 +119,8 @@ pub fn stroke_contains(path: &BezPath, width: f64, tol: f64, p: Point) -> bool { /// (#1103). pub fn intersects_rect(path: &PathData, r: Rect) -> bool { let Some(b) = path.bounds() else { return false }; - if b.intersect(r).area() <= 0.0 && !(b.width() == 0.0 || b.height() == 0.0) { + let degenerate = |x: Rect| x.width() == 0.0 || x.height() == 0.0; + if b.intersect(r).area() <= 0.0 && !degenerate(b) && !degenerate(r) { return false; } // Any anchor inside? @@ -221,6 +228,16 @@ mod tests { let l = shapes::line(Point::new(0.0, 0.0), Point::new(10.0, 10.0)); assert!(intersects_rect(&l, Rect::new(4.0, 0.0, 6.0, 10.0))); } + + #[test] + fn marquee_degenerate_rect() { + let p = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); + // zero-height / zero-width marquee crossing the shape + assert!(intersects_rect(&p, Rect::new(-5.0, 5.0, 15.0, 5.0))); + assert!(intersects_rect(&p, Rect::new(5.0, -5.0, 5.0, 15.0))); + // zero-height marquee missing it + assert!(!intersects_rect(&p, Rect::new(20.0, 5.0, 30.0, 5.0))); + } } #[cfg(test)] @@ -244,4 +261,20 @@ mod regress_tests { let worst = (0..=200).map(|i| distance_to_outline(&bp, c.eval(i as f64 / 200.0))).fold(0.0, f64::max); assert!(worst < 1e-6, "{worst}"); } + + #[test] + fn polygon_covers_rect_rejects_self_intersecting_star() { + let mut b = BezPath::new(); + for k in 0..5 { + let a = (-90.0 + 144.0 * k as f64).to_radians(); + let p = Point::new(100.0 * a.cos(), 100.0 * a.sin()); + if k == 0 { + b.move_to(p); + } else { + b.line_to(p); + } + } + b.close_path(); + assert!(!polygon_covers_rect(&b, Rect::new(-55.0, -20.0, 55.0, 78.0), 0.01)); + } } diff --git a/crates/metafile/src/scene.rs b/crates/metafile/src/scene.rs index 5654d44f3b..6f9ed1059c 100644 --- a/crates/metafile/src/scene.rs +++ b/crates/metafile/src/scene.rs @@ -17,6 +17,9 @@ use crate::dib::Rgba; /// How deep symbols, brush art and pattern tiles may nest in one another (deeper art is left out). const MAX_NEST: u32 = 8; +/// Most pattern tiles written in all. One fill tiles at most 250,000 (`PatternDef::offsets_covering`), +/// but a tile whose art is filled with a pattern again multiplies that at every level of nesting. +const MAX_TILES: usize = 250_000; /// Most pixels along a side of a gradient's image (its colours are smooth). const MAX_GRADIENT_PX: f64 = 512.0; /// Opacity at or above this is written as opaque. @@ -29,6 +32,7 @@ const RASTER_FX: &str = "raster effects (shadows, glows, blurs, feathering) are const CLIPPING: &str = "clipping masks are not applied: the art they clip is written whole"; const FLAT_GRADIENTS: &str = "gradients are written as one colour, the average of their stops"; const FLAT_PATTERNS: &str = "pattern fills are written as one colour"; +const TOO_MANY_TILES: &str = "pattern fills past 250,000 tiles in all are written as one colour"; /// A stroke as a pen draws it. #[derive(Clone, Debug, PartialEq)] @@ -115,6 +119,8 @@ pub(crate) struct Scene<'a> { opacity: f32, /// Symbols, brush art and pattern tiles being written inside one another. nest: u32, + /// Pattern tiles left to write ([`MAX_TILES`]). + tiles_left: usize, } impl<'a> Scene<'a> { @@ -130,6 +136,7 @@ impl<'a> Scene<'a> { brushes: None, opacity: 1.0, nest: 0, + tiles_left: MAX_TILES, } } @@ -296,9 +303,16 @@ impl<'a> Scene<'a> { match paint { Paint::None => {} Paint::Gradient(g) if self.clips => self.gradient(bp, rule, g, opacity, bounds), - Paint::Pattern { pattern, xf } if self.clips && self.nest < MAX_NEST && self.doc.pattern(pattern).is_some() => { + Paint::Pattern { pattern, xf } if self.clips && self.nest < MAX_NEST && self.tiles_left > 0 && self.doc.pattern(pattern).is_some() => { let area = bp.bounding_box().intersect(self.region); let tiles = self.doc.pattern(pattern).map(|def| def.instances_in(*xf, area)).unwrap_or_default(); + if tiles.len() > self.tiles_left { + self.tiles_left = 0; + self.warn(TOO_MANY_TILES); + self.flat_fill(bp, rule, paint, opacity); + return; + } + self.tiles_left -= tiles.len(); let outer = self.opacity; self.opacity *= opacity.clamp(0.0, 1.0); self.ops.push(Op::Clip { path: bp.clone(), rule }); @@ -308,14 +322,17 @@ impl<'a> Scene<'a> { self.ops.push(Op::Unclip); self.opacity = outer; } - p => { - let Some(rgb) = self.flat(p) else { return }; - self.check_opacity(opacity); - self.ops.push(Op::Fill { path: bp.clone(), rule, rgb }); - } + p => self.flat_fill(bp, rule, p, opacity), } } + /// Fill `bp` with one colour for `paint` at `opacity`. + fn flat_fill(&mut self, bp: &BezPath, rule: FillRule, paint: &Paint, opacity: f32) { + let Some(rgb) = self.flat(paint) else { return }; + self.check_opacity(opacity); + self.ops.push(Op::Fill { path: bp.clone(), rule, rgb }); + } + /// One colour for a paint: a solid colour, the average of a gradient's stops, or a pattern's /// first solid fill. fn flat(&mut self, p: &Paint) -> Option<[u8; 3]> { diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs index 013ea44b8a..330de5e7b6 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -4,7 +4,9 @@ use std::sync::Arc; use vectorcraft_color::{Color, Gradient, GradientPaint, Paint}; -use vectorcraft_doc::{Appearance, CharStyle, Dash, Document, ImageBlob, ImageObject, LineCap, LineJoin, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_doc::{ + Appearance, CharStyle, Dash, Document, ImageBlob, ImageObject, LineCap, LineJoin, Node, NodeId, NodeKind, PatternDef, TextObject, +}; use vectorcraft_geom::{Affine, PathData, Point, Rect, shapes}; use crate::*; @@ -340,3 +342,34 @@ fn an_instance_whose_art_reaches_the_artboard_is_written() { let k = kinds(&emf_records(&emf(&d).bytes)); assert!(k.contains(&39), "a brush fills the art: {k:?}"); } + +/// A pattern `name` repeating `art` every point. +fn point_tiles(name: &str, art: Node) -> PatternDef { + let mut def = PatternDef::new(name, vec![Arc::new(art)]); + def.tile = Rect::new(0.0, 0.0, 1.0, 1.0); + def +} + +fn pattern(name: &str) -> Paint { + Paint::Pattern { pattern: name.into(), xf: Affine::IDENTITY } +} + +#[test] +fn patterns_inside_pattern_tiles_share_one_tile_budget() { + // About 3,700 tiles of a 12 pt square, each filled with about 140 tiles of a dot: over half a + // million fills when every tile is written. + let square = path(shapes::rectangle(Rect::new(0.0, 0.0, 12.0, 12.0)), pattern("dots"), Paint::None, 0.0); + let mut d = doc_with(50.0, 50.0, vec![path(shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)), pattern("squares"), Paint::None, 0.0)]); + d.patterns.push(point_tiles("dots", path(shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), red(), Paint::None, 0.0))); + d.patterns.push(point_tiles("squares", square)); + let (ops, warnings) = crate::scene::Scene::new(&d, d.artboards[0].rect, true).run(); + assert!(ops.len() < 300_000, "{} operations", ops.len()); + assert!(warnings.iter().any(|w| w.contains("one colour")), "{warnings:?}"); + + // A tile filled with its own pattern multiplies at every level down to the nesting limit. + let square = path(shapes::rectangle(Rect::new(0.0, 0.0, 4.0, 4.0)), pattern("self"), Paint::None, 0.0); + let mut d = doc_with(10.0, 10.0, vec![path(shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), pattern("self"), Paint::None, 0.0)]); + d.patterns.push(point_tiles("self", square)); + let (ops, _) = crate::scene::Scene::new(&d, d.artboards[0].rect, true).run(); + assert!(ops.len() < 300_000, "{} operations", ops.len()); +} diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index 5cb30bcd7a..173d91882e 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -29,6 +29,30 @@ pub fn simplify(path: &PathData, tolerance: f64) -> PathData { simplify_with(path, &SimplifyOptions { tolerance, ..Default::default() }) } +/// The Simplify slider's level for a tolerance of 1 pt, where the slider opens. +pub const SIMPLIFY_LEVEL: f64 = 50.0; + +/// The tolerance (points) of Simplify slider level `level`, from 0 (the fewest anchor points) to +/// 100 (the closest to the original): 1 pt at [`SIMPLIFY_LEVEL`], doubled for every 10 levels below +/// it and halved for every 10 above, so level 0 is 32 pt and level 100 is 1/32 pt. A level outside +/// 0..=100 counts as the nearer end, and one that is not a number counts as [`SIMPLIFY_LEVEL`]. +pub fn simplify_level_tolerance(level: f64) -> f64 { + let level = if level.is_finite() { level.clamp(0.0, 100.0) } else { SIMPLIFY_LEVEL }; + ((SIMPLIFY_LEVEL - level) / 10.0).exp2() +} + +/// Auto-Simplify's level for paths whose bounds are `size` points on their longer side: the lowest +/// whole level whose tolerance ([`simplify_level_tolerance`]) is at most 1/400 of `size`. It returns +/// level 100 for a size of 0 or one that is not a number, and for a size under 12.5 pt, where no +/// level is that close. +pub fn auto_simplify_level(size: f64) -> f64 { + let target = size / 400.0; + if !(target.is_finite() && target > 0.0) { + return 100.0; + } + (SIMPLIFY_LEVEL - 10.0 * target.log2()).ceil().clamp(0.0, 100.0) +} + /// Simplify never adds anchors: keep whichever subpath is smaller. fn no_worse(original: &SubPath, fitted: SubPath) -> SubPath { if fitted.anchors.len() > original.anchors.len() { original.clone() } else { fitted } diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index 9cfc0bd5c1..29c9f2449e 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -15,8 +15,8 @@ mod planar; pub use boolean::{BoolOp, DEFAULT_PRECISION, area, boolean, boolean_n, normalize, try_boolean, try_normalize, unite_all}; pub use edit::{ - AverageAxis, SimplifyOptions, add_anchor_points, average, join, remove_anchor, remove_redundant_points, simplify, simplify_with, smooth, - split_into_grid, + AverageAxis, SIMPLIFY_LEVEL, SimplifyOptions, add_anchor_points, auto_simplify_level, average, join, remove_anchor, remove_redundant_points, + simplify, simplify_level_tolerance, simplify_with, smooth, split_into_grid, }; pub use offset::{Cap, Join, offset_path, outline_stroke, stroke_region}; pub use pathfinder::{FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, region_at, regions}; diff --git a/crates/pathops/src/pathfinder.rs b/crates/pathops/src/pathfinder.rs index fbd4ddfcc3..aa63f0381d 100644 --- a/crates/pathops/src/pathfinder.rs +++ b/crates/pathops/src/pathfinder.rs @@ -236,32 +236,13 @@ fn regions_of(arr: &Arrangement) -> Vec { // pass per mask for this batch. for (m, mask) in masks.iter().enumerate().filter(|(m, _)| batch[*m] == b) { let c = arr.contours(|k| k == mask.as_slice()); - faces[m].extend(c.grouped().into_iter().map(|g| contours_to_path(&c, g, &arr.tidy))); + let owner = vec![m; c.contours().count()]; + faces[m].extend(face_groups(&c, &owner).into_iter().map(|(_, g)| contours_to_path(&c, g, &arr.tidy))); } continue; }; - // A contour belongs under the nearest enclosing contour of the same mask, as in that - // mask's own pass. - let mut children = vec![Vec::new(); owner.len()]; - let mut roots = Vec::new(); - for (i, &m) in owner.iter().enumerate() { - let mut up = c[ContourIdx(i)].parent; - while let Some(p) = up.filter(|p| owner.get(p.0) != Some(&m)) { - up = c[p].parent; - } - match up { - Some(p) => children[p.0].push(i), - None => roots.push(i), - } - } - for r in roots { - let mut group = Vec::new(); - let mut stack = vec![r]; - while let Some(i) = stack.pop() { - group.push(ContourIdx(i)); - stack.extend(children[i].iter().rev()); - } - faces[owner[r]].push(contours_to_path(&c, group, &arr.tidy)); + for (m, group) in face_groups(&c, &owner) { + faces[m].push(contours_to_path(&c, group, &arr.tidy)); } } let mut out = Vec::new(); @@ -272,6 +253,39 @@ fn regions_of(arr: &Arrangement) -> Vec { out } +/// Splits a contour pass into faces: each face is an outer contour plus the holes of the same mask +/// directly inside it (`owner` gives each contour's mask). A hole belongs under the nearest +/// enclosing contour of its mask, as in that mask's own pass; an outer contour always starts a face +/// of its own, even inside a hole of its mask (an island left in a cutout is a separate face, not +/// part of the frame around it). +fn face_groups(c: &linesweeper::topology::Contours, owner: &[usize]) -> Vec<(usize, Vec)> { + let mut children = vec![Vec::new(); owner.len()]; + let mut roots = Vec::new(); + for (i, &m) in owner.iter().enumerate() { + let ct = &c[ContourIdx(i)]; + let mut up = if ct.outer { None } else { ct.parent }; + while let Some(p) = up.filter(|p| owner.get(p.0) != Some(&m)) { + up = c[p].parent; + } + match up { + Some(p) => children[p.0].push(i), + None => roots.push(i), + } + } + roots + .into_iter() + .map(|r| { + let mut group = Vec::new(); + let mut stack = vec![r]; + while let Some(i) = stack.pop() { + group.push(ContourIdx(i)); + stack.extend(children[i].iter().rev()); + } + (owner[r], group) + }) + .collect() +} + /// A point as a map key (the arrangement's vertices are exact). fn vertex_key(p: Point) -> (u64, u64) { (p.x.to_bits(), p.y.to_bits()) diff --git a/crates/pathops/tests/ops.rs b/crates/pathops/tests/ops.rs index d65fb5b834..52d1af8c8e 100644 --- a/crates/pathops/tests/ops.rs +++ b/crates/pathops/tests/ops.rs @@ -241,6 +241,26 @@ fn regions_and_region_at() { assert!(close(ar(&merge_regions(&refs)), 175.0, 1e-9)); } +#[test] +fn regions_split_an_island_inside_a_hole_from_the_frame_around_it() { + // A frame (0..200 minus 50..150) with an island (80..120) in its hole, as Minus Front leaves + // a rectangle behind a ring (#3132): the frame and the island are separate faces. + let mut p = rect(0.0, 0.0, 200.0, 200.0); + p.subpaths.extend(rect(50.0, 50.0, 100.0, 100.0).subpaths); + p.subpaths.extend(rect(80.0, 80.0, 40.0, 40.0).subpaths); + let s = vec![Shape::new(p, FillRule::EvenOdd, 1)]; + let rs = regions(&s); + let mut filled: Vec<(f64, Rect)> = rs.iter().filter(|r| r.sources == vec![0]).map(|r| (ar(&r.path).abs(), r.path.bounds().unwrap())).collect(); + filled.sort_by(|a, b| b.0.total_cmp(&a.0)); + assert_eq!(filled.len(), 2, "{filled:?}"); + assert!(close(filled[0].0, 30000.0, 1e-9), "{filled:?}"); + assert_eq!(filled[0].1, Rect::new(0.0, 0.0, 200.0, 200.0)); + assert!(close(filled[1].0, 1600.0, 1e-9), "{filled:?}"); + assert_eq!(filled[1].1, Rect::new(80.0, 80.0, 120.0, 120.0)); + let frame = region_at(&s, Point::new(10.0, 10.0)).unwrap(); + assert!(!frame.contains(Point::new(100.0, 100.0))); +} + #[test] fn offset_circle_grows() { let o = offset_path(&circle(0.0, 0.0, 10.0), 3.0, Join::Round, 4.0); @@ -343,6 +363,20 @@ fn simplify_straight_lines_option() { assert!(max_deviation(&c, &s) <= 1.0 + 1e-6); } +/// The Simplify slider's levels: 1 pt at 50, doubled for every 10 levels down and halved for every +/// 10 up; Auto-Simplify takes the lowest level whose tolerance is at most 1/400 of the size, and +/// level 100 for a size under 12.5 pt. +#[test] +fn simplify_levels_and_auto_simplify() { + assert_eq!(simplify_level_tolerance(SIMPLIFY_LEVEL), 1.0); + assert_eq!((simplify_level_tolerance(0.0), simplify_level_tolerance(100.0)), (32.0, 1.0 / 32.0)); + assert_eq!((simplify_level_tolerance(-5.0), simplify_level_tolerance(500.0), simplify_level_tolerance(f64::NAN)), (32.0, 1.0 / 32.0, 1.0)); + assert_eq!((auto_simplify_level(400.0), auto_simplify_level(100.0), auto_simplify_level(300.0)), (50.0, 70.0, 55.0)); + assert!(simplify_level_tolerance(auto_simplify_level(300.0)) <= 300.0 / 400.0); + assert_eq!((auto_simplify_level(12.5), auto_simplify_level(10.0)), (100.0, 100.0)); + assert_eq!((auto_simplify_level(0.0), auto_simplify_level(f64::INFINITY), auto_simplify_level(1e9)), (100.0, 100.0, 0.0)); +} + #[test] fn smooth_rounds_corners() { let s = smooth(&rect(0.0, 0.0, 10.0, 10.0), 1.0); diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs index 910ba44268..77be57d01c 100644 --- a/crates/pdf/src/export.rs +++ b/crates/pdf/src/export.rs @@ -130,10 +130,10 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha w.page(&mut ex, &sheet).map_err(|_| PdfError::BadArtboard(i))?; } vectorcraft_doc::cancel::check().map_err(|_| PdfError::Cancelled)?; - let (layers, overprinted) = (ex.layers, ex.overprinted); + let (layers, overprinted, invisible) = (ex.layers, ex.overprinted, ex.invisible); w.absorb(ex); let (bytes, more) = w.finish(left_out)?; - let bytes = crate::forms::finish(bytes, doc, set, layers, overprinted)?; + let bytes = crate::forms::finish(bytes, doc, set, layers, overprinted, invisible)?; // The writer gives the file its creation date as its modification date too. let bytes = match opts.modified.filter(|m| Some(*m) != created_at) { Some(modified) => crate::post::modification_date(bytes, modified)?, @@ -597,6 +597,8 @@ pub(crate) struct Exporter<'a> { pub overprint: bool, /// An overprinting fill or stroke was drawn so. pub overprinted: bool, + /// Characters with neither fill nor stroke were written as text in forms marked invisible. + pub invisible: bool, /// Inline graphics being drawn inside inline graphics (text in a symbol shown inline in /// text…): deeper ones are left out. inline_depth: u32, @@ -639,6 +641,7 @@ impl<'a> Exporter<'a> { in_layer: 0, overprint: false, overprinted: false, + invisible: false, inline_depth: 0, left_out: HashSet::new(), } @@ -1564,6 +1567,18 @@ impl Exporter<'_> { } s.pop(); }); + // Characters with neither fill nor stroke (a scanned page's recognized text) are still + // text: written invisible (rendering mode 3), so they can still be selected and searched. + if let Some(text) = plain.as_deref().filter(|_| fill.is_none() && !run.style.has_stroke()) { + self.invisible = true; + crate::forms::form(s, Mark::Invisible, |s| { + s.push_transform(&text_space); + // The paint only lets the writer write the text; the glyphs it can't write + // as text draw nothing. + self.glyph_text(s, &layout, i, text, &Paint::solid(Color::gray(0.0))); + s.pop(); + }); + } s.push_transform(&text_space); let path = run.style.has_stroke().then(|| to_path(s, &bp)).flatten(); s.pop(); diff --git a/crates/pdf/src/forms.rs b/crates/pdf/src/forms.rs index c9cfe82dce..e382ccb0fe 100644 --- a/crates/pdf/src/forms.rs +++ b/crates/pdf/src/forms.rs @@ -1,9 +1,10 @@ -//! What the PDF writer has no operators for — optional content (PDF layers) and overprint — drawn -//! as form XObjects of their own (without a transparency group, so they draw as if in place), -//! each starting with a mark: an empty clip whose first point says what the form is. Marked -//! forms also stay apart (the writer shares identical forms). [`finish`] completes them in the -//! written file: a layer's form is drawn as the layer's optional content (`/OC … BDC`), and an -//! overprinting form sets a graphics state that overprints first. +//! What the PDF writer has no operators for — optional content (PDF layers), overprint and +//! invisible text — drawn as form XObjects of their own (without a transparency group, so they +//! draw as if in place), each starting with a mark: an empty clip whose first point says what the +//! form is. Marked forms also stay apart (the writer shares identical forms). [`finish`] completes +//! them in the written file: a layer's form is drawn as the layer's optional content (`/OC … +//! BDC`), an overprinting form sets a graphics state that overprints first, and the text of an +//! invisible form is drawn in rendering mode 3 (neither filled nor stroked). use std::collections::HashMap; use std::io::Read; @@ -28,6 +29,8 @@ pub(crate) enum Mark { Layer(usize), /// A fill or stroke that overprints. Overprint, + /// Text that draws nothing (rendering mode 3): characters with neither fill nor stroke. + Invisible, } /// A layer written as a PDF layer (an optional content group). @@ -58,6 +61,8 @@ pub(crate) fn pdf_layers(doc: &Document) -> Vec> { const LAYER_X: i32 = -32000; /// The x coordinate of an overprint mark's first point. const OVERPRINT_X: i32 = -32001; +/// The x coordinate of an invisible text mark's first point. +const INVISIBLE_X: i32 = -32002; impl Mark { fn at(self) -> (f32, f32) { @@ -65,6 +70,7 @@ impl Mark { // Exact in `f32` up to 2^24 layers. Self::Layer(i) => (LAYER_X as f32, i as f32), Self::Overprint => (OVERPRINT_X as f32, 0.0), + Self::Invisible => (INVISIBLE_X as f32, 0.0), } } } @@ -100,7 +106,7 @@ const LAYER_OC: &str = "VCoc"; const HEAD: u64 = 64; fn bad(why: &str) -> PdfError { - PdfError::Write(format!("can't write PDF layers or overprint: {why}")) + PdfError::Write(format!("can't write PDF layers, overprint or invisible text: {why}")) } /// An object of the written file with a dictionary, and its stream's [`StreamSpans`]. @@ -149,6 +155,7 @@ impl Object<'_> { match x { _ if x == i64::from(LAYER_X) => usize::try_from(y).ok().map(Mark::Layer), _ if x == i64::from(OVERPRINT_X) && y == 0 => Some(Mark::Overprint), + _ if x == i64::from(INVISIBLE_X) && y == 0 => Some(Mark::Invisible), _ => None, } } @@ -225,14 +232,52 @@ fn mark_layers(content: &[u8], forms: &HashMap<&[u8], usize>) -> Option<(Vec Some((out, layers)) } +/// `content` (an invisible form's) with its text drawn in rendering mode 3: the mode set first, +/// and every mode the writer sets (it sets one for each run of glyphs) made 3. `None` when the +/// content can't be read to its end. +fn invisible_text(content: &[u8]) -> Option> { + let mut lx = Lexer::at(content, 0); + let mut operand = None; + let mut modes = vec![]; + let mut read = 0; + while let Some((tok, start, end)) = lx.next() { + read = end; + operand = match tok { + Tok::Word(b"Tr") => { + modes.extend(operand); + None + } + Tok::Word(w) if int(w).is_some() => Some((start, end)), + // Inline image data isn't PDF syntax (the writer writes none). + Tok::Word(b"ID") => return None, + _ => None, + }; + } + // The lexer also stops at a string it can't read: a mode after it would be missed. + if !content.get(read..)?.iter().all(u8::is_ascii_whitespace) { + return None; + } + let mut out = Vec::with_capacity(content.len() + 8); + out.extend_from_slice(b"3 Tr\n"); + let mut at = 0; + for (start, end) in modes { + out.extend_from_slice(content.get(at..start)?); + out.push(b'3'); + at = end; + } + out.extend_from_slice(content.get(at..)?); + Some(out) +} + /// Finish the marked forms of `pdf` (as [`crate::export`] writes `doc` with `set`): with /// `layers`, each layer and sublayer (but template layers) becomes an optional content group — /// named as the layer, off when it is hidden, not printed (`/PrintState /OFF`) when its Print /// option is off, locked when it is locked — and the uses of its forms its optional content; /// with `overprint`, the overprinting forms get a graphics state that overprints (`/OP`, `/op`, -/// `/OPM 1`; `/OPM 0` in PDF/A, which allows no other with ICC-based CMYK colours). -pub(crate) fn finish(pdf: Vec, doc: &Document, set: &PdfSettings, layers: bool, overprint: bool) -> Result, PdfError> { - if !layers && !overprint { +/// `/OPM 1`; `/OPM 0` in PDF/A, which allows no other with ICC-based CMYK colours); with +/// `invisible`, the text of the invisible forms is drawn in rendering mode 3. +pub(crate) fn finish(pdf: Vec, doc: &Document, set: &PdfSettings, layers: bool, overprint: bool, invisible: bool) -> Result, PdfError> { + if !layers && !overprint && !invisible { return Ok(pdf); } let xref = Xref::read(&pdf).ok_or_else(|| bad("the written PDF has no cross-reference table"))?; @@ -253,6 +298,13 @@ pub(crate) fn finish(pdf: Vec, doc: &Document, set: &PdfSettings, layers: bo add_resources(&mut patch, res, "ExtGState", &format!("/{OVERPRINT_GS} {gs} 0 R"))?; } } + if invisible { + for (n, _) in marks.iter().filter(|(_, m)| **m == Mark::Invisible) { + let Some(o) = objects.get(n) else { continue }; + let content = o.data(&pdf, u64::MAX).ok_or_else(|| bad("an invisible text form can't be read"))?; + o.rewrite(&mut patch, &invisible_text(&content).ok_or_else(|| bad("an invisible text form can't be read"))?)?; + } + } if layers { write_layers(&pdf, &xref, &objects, &marks, &mut patch, doc, set)?; for (n, _) in marks.iter().filter(|(_, m)| matches!(m, Mark::Layer(_))) { diff --git a/crates/pdf/src/import.rs b/crates/pdf/src/import.rs index 471e56cfe1..9bbb6257b1 100644 --- a/crates/pdf/src/import.rs +++ b/crates/pdf/src/import.rs @@ -149,6 +149,10 @@ pub const PAST_PAGE_NOTE: &str = "art reaching past the page was clipped to it, /// Warning: glyphs were kept as outlines rather than read as type. pub const OUTLINED_TEXT_NOTE: &str = "text was converted to outlines"; +/// Warning: text drawn invisibly (text rendering mode 3, as a scanned page's OCR layer is) that +/// can't come in as type (text read as outlines, or a Type 3 font) was left out: as outlines it +/// would draw nothing (#2675). +pub const INVISIBLE_TEXT_NOTE: &str = "invisible text (such as a scanned page's searchable OCR layer) that couldn't be read as type was left out"; /// Warning: glyphs that differ from the installed font of their name were kept as outlines. pub const UNMATCHED_GLYPHS_NOTE: &str = "text whose glyphs differ from the installed font of the same name was kept as outlines"; /// The end of the warning that glyphs whose characters the file doesn't name were kept as @@ -1650,13 +1654,14 @@ impl<'p> Builder<'p> { } /// Glyph `o` as type: added to the line being gathered (or starting one). `false`: it keeps - /// its outline (no Unicode text, mirrored, or not type mode). + /// its outline (no Unicode text, mirrored, or not type mode). No `paint`: invisible text, + /// type with neither fill nor stroke. fn type_glyph( &mut self, o: &craft_pdf::interpret::font::OutlineGlyph, m: Affine, scale: f64, - paint: &craft_pdf::interpret::Paint<'_>, + paint: Option<&craft_pdf::interpret::Paint<'_>>, stroke: Option<&StrokeProps>, overprint: bool, ) -> bool { @@ -1688,7 +1693,8 @@ impl<'p> Builder<'p> { Some(BfString::Char(c)) => c.to_string(), Some(BfString::String(s)) => s, None => { - if o.as_unicode().is_some_and(|u| replacement(&u)) { + // Invisible text isn't kept as outlines: the caller says it was left out. + if paint.is_some() && o.as_unicode().is_some_and(|u| replacement(&u)) { let name = self.font_name(key, o).family; self.warn(&format!("text in {name} {UNNAMED_CHARACTERS_NOTE}")); } @@ -1714,16 +1720,18 @@ impl<'p> Builder<'p> { { let decided = match self.matched.get(&key) { Some(m) => m.clone(), - // A glyph that can't be compared (several characters, a vertical form) decides - // nothing: it takes the face of its name until one that can be compared does. - None if comparable(&text, upright).is_none() => Some(face.clone()), + // A glyph that can't be compared (several characters, a vertical form) or that + // shows nothing (invisible text) decides nothing: it takes the face of its name + // until one that can be compared does. + None if paint.is_none() || comparable(&text, upright).is_none() => Some(face.clone()), None => { let m = matching_face(face, &text, o, upright); self.matched.insert(key, m.clone()); m } }; - let Some(f) = decided else { + // Invisible text shows no glyphs that could differ: it keeps the face of its name. + let Some(f) = decided.or_else(|| paint.is_none().then(|| face.clone())) else { self.warn(UNMATCHED_GLYPHS_NOTE); return false; }; @@ -1741,8 +1749,14 @@ impl<'p> Builder<'p> { None if self.matched.contains_key(&key) => self.versions.entry(key).or_insert_with(|| named(&info.face)).clone(), None => named(&info.face), }; - let (paint, opacity) = self.paint(paint, stroke.is_some(), self.walked(true)); - let stroke = stroke.map(|p| (paint.clone(), line_width(p, scale))); + let (paint, opacity) = match paint { + Some(p) => { + let (paint, opacity) = self.paint(p, stroke.is_some(), self.walked(true)); + (Some(paint), opacity) + } + None => (None, 1.0), + }; + let stroke = stroke.zip(paint.clone()).map(|(p, paint)| (paint, line_width(p, scale))); let look = Look { font: key, family: info.family, @@ -1752,7 +1766,7 @@ impl<'p> Builder<'p> { h_scale: at.h_scale, overprint_fill: stroke.is_none() && overprint, overprint_stroke: stroke.is_some() && overprint, - fill: stroke.is_none().then_some(paint), + fill: if stroke.is_none() { paint } else { None }, stroke, }; let advance = width.map_or(at.size * 0.5, |w| w as f64 / 1000.0 * at.size * at.h_scale / 100.0); @@ -1963,7 +1977,18 @@ impl<'a> Device<'a> for Builder<'_> { ) { self.pending = false; let stroke = match draw_mode { - GlyphDrawMode::Invisible => return, + // Invisible text (a scanned page's recognized text, over the scan) draws nothing but + // is still text: type with neither fill nor stroke, so it stays searchable. + GlyphDrawMode::Invisible => { + let typed = match glyph { + Glyph::Outline(o) => self.type_glyph(o, transform * glyph_transform, mean_scale(transform), None, None, false), + Glyph::Type3(_) => false, + }; + if !typed { + self.warn(INVISIBLE_TEXT_NOTE); + } + return; + } GlyphDrawMode::Fill => None, GlyphDrawMode::Stroke(p) => Some(p.clone()), }; @@ -1971,7 +1996,7 @@ impl<'a> Device<'a> for Builder<'_> { Glyph::Outline(o) => { let scale = mean_scale(transform); let overprint = self.glyph_overprint(stroke.is_some()); - if self.type_glyph(o, transform * glyph_transform, scale, paint, stroke.as_ref(), overprint) { + if self.type_glyph(o, transform * glyph_transform, scale, Some(paint), stroke.as_ref(), overprint) { return; } self.flush_text(); diff --git a/crates/pdf/src/import_text.rs b/crates/pdf/src/import_text.rs index 04c5b31291..f0dfaf4c8b 100644 --- a/crates/pdf/src/import_text.rs +++ b/crates/pdf/src/import_text.rs @@ -88,14 +88,15 @@ pub(crate) struct Look { impl Look { /// Can a glyph drawn with `other` join a run drawn with this? A fill joins a run whose - /// glyphs were also stroked over (fill and stroke rendering draws each glyph twice). + /// glyphs were also stroked over (fill and stroke rendering draws each glyph twice); invisible + /// text (neither fill nor stroke) joins only invisible text. fn takes(&self, other: &Look) -> bool { self.font == other.font && (self.size - other.size).abs() <= self.size * 0.01 && (self.h_scale - other.h_scale).abs() < 0.5 && self.fill == other.fill && self.overprint_fill == other.overprint_fill - && (other.stroke.is_none() || (self.stroke == other.stroke && self.overprint_stroke == other.overprint_stroke)) + && ((other.stroke.is_none() && other.fill.is_some()) || (self.stroke == other.stroke && self.overprint_stroke == other.overprint_stroke)) } fn style(&self) -> CharStyle { diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index ddec82ba47..b855fa2425 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -74,8 +74,8 @@ pub use encrypt::Encryption; pub use export::{export, export_with_report, page_areas}; pub use file_info::{FileInfo, file_info}; pub use import::{ - OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE, holds_outlines, import, - import_with_report, is_glyph_outlines, is_outlines_note, + INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE, holds_outlines, + import, import_with_report, is_glyph_outlines, is_outlines_note, }; pub use pages::{PageInfo, PdfInfo, has_illustrator_data, illustrator_data, info, is_postscript}; pub use post::{THUMBNAIL_SIZE, Thumbnail}; diff --git a/crates/pdf/src/print/mod.rs b/crates/pdf/src/print/mod.rs index 38e31b42a9..2bd8f01b0a 100644 --- a/crates/pdf/src/print/mod.rs +++ b/crates/pdf/src/print/mod.rs @@ -422,11 +422,12 @@ fn print_inner(doc: &Document, opts: &PrintOptions, left_out: &mut HashSet"))); } +/// Invisible text (rendering mode 3: a scanned page's recognized text, laid over the scan) is +/// type with neither fill nor stroke, and the visible text keeps its paint. On a line with +/// stroked text it is a run of its own, not stroked. As outlines it would draw nothing: it is left +/// out, and the open says so (#2675). +#[test] +fn invisible_text_becomes_type_without_paint() { + let bytes = one_page( + "0.5 g 10 40 80 40 re f \ + BT /F1 10 Tf 3 Tr 12 70 Td (Invisible one) Tj 0 -12 Td (Invisible two) Tj ET \ + BT /F1 10 Tf 0 g 0 Tr 12 20 Td (Visible) Tj ET \ + BT /F1 10 Tf 1 0 0 RG 1 Tr 12 90 Td (Out) Tj 3 Tr (line) Tj ET", + HELVETICA, + &[], + ); + let r = open_with(&bytes, |_| {}); + let t = texts(&r.document); + let text = |o: &vectorcraft_doc::TextObject| o.runs.iter().map(|r| r.text.as_str()).collect::(); + assert_eq!(t.iter().map(text).collect::>(), ["Invisible one", "Invisible two", "Visible", "Outline"], "{t:?}"); + let unpainted = |st: &vectorcraft_doc::CharStyle| st.fill.is_none() && !st.has_stroke(); + for o in &t[..2] { + assert!(o.runs.iter().all(|r| unpainted(&r.style)), "{:?}", o.runs); + } + assert!(t[2].runs.iter().all(|r| !r.style.fill.is_none()), "{:?}", t[2].runs); + let runs: Vec<(&str, bool)> = t[3].runs.iter().map(|r| (r.text.as_str(), unpainted(&r.style))).collect(); + assert_eq!(runs, [("Out", false), ("line", true)]); + assert!(t[3].runs[0].style.has_stroke()); + assert!(!r.warnings.iter().any(|w| w == INVISIBLE_TEXT_NOTE), "{:?}", r.warnings); + // As outlines: only the visible text's. + let r = open_with(&bytes, |o| o.text_as = TextAs::Outlines); + assert!(texts(&r.document).is_empty()); + assert!(r.warnings.iter().any(|w| w == INVISIBLE_TEXT_NOTE), "{:?}", r.warnings); + let outlines: Vec = + all(&r.document).iter().filter(|n| n.name.as_deref() == Some("")).filter_map(|n| n.geometric_bounds()).collect(); + // y down: "Visible" sits on 80, "Out" on 10; the invisible lines on 30 and 42 left nothing. + assert!(!outlines.is_empty() && outlines.iter().all(|b| b.y1 < 20.0 || b.y0 > 70.0), "{outlines:?}"); +} + #[test] fn font_names_resolve_to_available_families() { let f = crate::import_text::Families::available(); diff --git a/crates/pdf/src/tests_live_text.rs b/crates/pdf/src/tests_live_text.rs index 63ebb0dff8..b61dcb8473 100644 --- a/crates/pdf/src/tests_live_text.rs +++ b/crates/pdf/src/tests_live_text.rs @@ -160,6 +160,32 @@ fn a_glyph_whose_unicode_names_another_letter_stays_outlined() { assert!(r.warnings.iter().any(|w| w.contains("differ from the installed font")), "{:?}", r.warnings); } +/// Invisible text (rendering mode 3) shows no glyphs that could differ from the installed font: +/// the glyph of `l` labelled `W` comes in as type showing `W`, and nothing is said to be kept as +/// outlines (#2675). +#[test] +fn invisible_text_is_type_whatever_its_glyphs_look_like() { + let font = vectorcraft_text::FontDb::global().find_postscript("SourceSans3-Regular").unwrap(); + let l = font.glyph_for('l'); + let mut pdf = krilla::Document::new_with(krilla::SerializeSettings { compress_content_streams: false, ..Default::default() }); + let mut page = pdf.start_page_with(PageSettings::from_wh(300.0, 200.0).unwrap()); + let mut s = page.surface(); + let kfont = Font::new(SOURCE_SANS.into(), 0).unwrap(); + let glyph = krilla::text::KrillaGlyph::new(krilla::text::GlyphId::new(l), 0.25, 0.0, 0.0, 0.0, 0..1, None); + s.draw_glyphs(KPoint::from_xy(20.0, 50.0), &[glyph], kfont, "W", 24.0, false); + s.finish(); + page.finish(); + let mut bytes = pdf.finish().unwrap(); + // Filled (mode 0) made invisible: the same length, so the cross-reference table still holds. + let at = bytes.windows(4).position(|w| w == b"0 Tr").expect("a rendering mode"); + bytes[at] = b'3'; + let r = import_with_report(&bytes, &ImportOptions::default()).unwrap(); + let t = texts(&r.document); + assert_eq!(t.iter().map(TextObject::plain_text).collect::>(), ["W"]); + assert!(t[0].runs.iter().all(|r| r.style.fill.is_none() && !r.style.has_stroke()), "{:?}", t[0].runs); + assert!(!r.warnings.iter().any(|w| is_outlines_note(w) || w == INVISIBLE_TEXT_NOTE), "{:?}", r.warnings); +} + /// `font` with each of `names` (`from`, `to`, the same length) replaced, in ASCII and UTF-16. fn renamed(font: &[u8], names: &[(&str, &str)]) -> Vec { let mut bytes = font.to_vec(); diff --git a/crates/pdf/src/tests_reader_compat.rs b/crates/pdf/src/tests_reader_compat.rs index a98674ea32..83933393ee 100644 --- a/crates/pdf/src/tests_reader_compat.rs +++ b/crates/pdf/src/tests_reader_compat.rs @@ -177,3 +177,46 @@ pub(crate) fn transfer_contract() { fn soft_mask_inversion_uses_quantized_transfer_endpoints() { transfer_contract(); } + +/// #2675: text in rendering mode 3 (invisible, as a scanned page's OCR layer) comes in as type +/// with neither fill nor stroke. Where it can't come in as type (text read as outlines) it is +/// left out, and the import says so. Visible text beside it still comes in, and a page without +/// invisible text gets no such warning. +#[test] +fn invisible_text_is_reported_when_left_out() { + let open = |content: &str, text_as: TextAs| import_with_report(&text_pdf(content), &ImportOptions { text_as, ..Default::default() }).unwrap(); + let invisible = "BT /F1 20 Tf 3 Tr 1 0 0 1 10 40 Tm (AB) Tj 0 Tr 1 0 0 1 10 10 Tm (CA) Tj ET"; + for text_as in [TextAs::Text, TextAs::Outlines] { + let r = open(invisible, text_as); + let warned = r.warnings.iter().any(|w| w == crate::INVISIBLE_TEXT_NOTE); + assert_eq!(warned, text_as == TextAs::Outlines, "{text_as:?}: {:?}", r.warnings); + // What came in: the type's text and whether it is painted, and where the painted art + // lies. On the 60 pt page the visible line (baseline 10 pt up) lies 35–50 pt down, the + // invisible one (40 pt up) 5–20 pt down. + let (mut painted, mut unpainted, mut tops) = (String::new(), String::new(), vec![]); + r.document.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + for run in &t.runs { + let out = if run.style.fill.is_none() && !run.style.has_stroke() { &mut unpainted } else { &mut painted }; + out.push_str(&run.text); + } + } + let shows = !matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().all(|r| r.style.fill.is_none() && !r.style.has_stroke())); + if shows + && matches!(n.kind, NodeKind::Text(_) | NodeKind::Path { .. } | NodeKind::Compound { .. }) + && let Some(b) = n.visual_bounds() + { + tops.push(b.y0); + } + }); + if text_as == TextAs::Text { + assert_eq!((painted.as_str(), unpainted.as_str()), ("CA", "AB"), "{text_as:?}"); + } else { + assert_eq!(unpainted, "", "{text_as:?}"); + } + assert!(!tops.is_empty(), "{text_as:?}: the visible line still comes in"); + assert!(tops.iter().all(|y| *y > 25.0), "{text_as:?}: only the visible line's art, tops at {tops:?}"); + let visible = open("BT /F1 20 Tf 1 0 0 1 10 10 Tm (CA) Tj ET", text_as); + assert!(!visible.warnings.iter().any(|w| w == crate::INVISIBLE_TEXT_NOTE), "{text_as:?}: {:?}", visible.warnings); + } +} diff --git a/crates/pdf/src/tests_realtext.rs b/crates/pdf/src/tests_realtext.rs index 45ae748306..d88e064f77 100644 --- a/crates/pdf/src/tests_realtext.rs +++ b/crates/pdf/src/tests_realtext.rs @@ -315,6 +315,50 @@ fn subset_thresholds_below_100_percent_are_accepted_with_a_warning() { assert_eq!(texts(&import_as(&r.bytes, TextAs::Text)), ["Subset"]); } +/// Characters with neither fill nor stroke (a scanned page's recognized text, as a PDF opens) are +/// written as invisible text, in rendering mode 3: searchable, drawing nothing, and type without +/// paint again when the file opens. Compressed or not, in PDF/X-1a and PDF/A too (#2675). +#[test] +fn type_without_paint_is_written_as_invisible_text() { + let unpainted = CharStyle { fill: Paint::None, ..style(24.0) }; + let d = doc(vec![ + TextObject::point(Point::new(20.0, 60.0), "Recognized", unpainted), + TextObject::point(Point::new(20.0, 160.0), "Visible", style(24.0)), + ]); + let r = pdf(&d, false); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let ops = String::from_utf8_lossy(&r.bytes).split_whitespace().collect::>().join(" "); + assert!(ops.contains("3 Tr") && ops.contains("0 Tr"), "the invisible text in mode 3, the visible in mode 0"); + let written = |v: serde_json::Value| { + let settings: PdfSettings = serde_json::from_value(v).unwrap(); + export(&d, &PdfOptions { settings, created: Some(0), ..Default::default() }).unwrap() + }; + let files = [ + ("uncompressed", r.bytes.clone()), + ("compressed", written(json!({"advanced": {"outlineText": false}}))), + ("PDF/X-1a", written(json!({"standard": "pdfX1a", "compatibility": "1.3", "advanced": {"outlineText": false}}))), + ("PDF/A-2b", written(json!({"standard": "pdfA2b", "advanced": {"outlineText": false}}))), + ]; + for (what, bytes) in files { + let back = import_as(&bytes, TextAs::Text); + assert_eq!(texts(&back), ["Recognized", "Visible"], "{what}"); + let mut paints = vec![]; + back.walk(|n| { + if let NodeKind::Text(t) = &n.kind { + paints.push(t.runs.iter().all(|r| r.style.fill.is_none() && !r.style.has_stroke())); + } + }); + assert_eq!(paints, [true, false], "{what}: only the recognized text has no paint"); + // It draws nothing: as outlines, only the visible text is there (its baseline on 160). + let drawn = ink(&import_as(&bytes, TextAs::Outlines)); + assert!(drawn.y0 > 100.0, "{what}: {drawn:?}"); + } + // Text exported as outlines has no invisible text: there is nothing to draw. + let outlined = import_as(&pdf(&d, true).bytes, TextAs::Text); + assert!(texts(&outlined).is_empty()); + assert!(ink(&outlined).y0 > 100.0); +} + #[test] fn pdf_a_takes_real_text() { let d = doc(vec![TextObject::point(Point::new(20.0, 60.0), "Archive", style(24.0))]); diff --git a/crates/plugins/src/dialog.rs b/crates/plugins/src/dialog.rs new file mode 100644 index 0000000000..3777dab2e0 --- /dev/null +++ b/crates/plugins/src/dialog.rs @@ -0,0 +1,307 @@ +//! How the host's generated dialogs show a plug-in's parameters: the optional `label`, `unit`, +//! `group`, `help`, `helpUrl` and `visibleWhen` keys of each one (docs/plugins.md › Parameters). +//! +//! These keys are presentation only. A host from before them ignores them, so a plug-in that +//! declares them still installs there, and a plug-in is given every parameter whether its dialog +//! showed it or not: a run never depends on what was on screen. The dialogs of filters, live +//! effects and exporters draw the parameters outside any group first, then each group as a section, +//! in the order the groups first appear, and leave out a parameter while its `visibleWhen` isn't met. +//! +//! `visibleWhen` names parameters declared before the one it belongs to, so the parameter that +//! decides comes first in the dialog and conditions can't go round in a circle. A parameter is shown +//! when each one it names is shown and has one of the values listed for it. + +use std::collections::{BTreeMap, BTreeSet}; + +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +use crate::manifest::{Manifest, Param, ParamSpec}; +use crate::{Error, Result}; + +/// Longest `label` or `group`, in characters. +pub const MAX_LABEL: usize = 64; +/// Longest `unit`, in characters. +pub const MAX_UNIT: usize = 16; +/// Longest `help`, in characters. +pub const MAX_HELP: usize = 1_000; +/// Longest `helpUrl`, in bytes. +pub const MAX_HELP_URL: usize = 512; +/// Most parameters one `visibleWhen` names. +pub const MAX_CONDITIONS: usize = 8; +/// Most values a `visibleWhen` lists for one parameter. +pub const MAX_CONDITION_VALUES: usize = 64; + +/// One section of a dialog ([`Manifest::sections`]): its group (`None`: the parameters outside any +/// group) and its parameters, in declaration order. +pub type Section<'a> = (Option<&'a str>, Vec<&'a (String, Param)>); + +/// How dialogs show one parameter (every key optional). +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ParamUi { + /// The field's label; without one, the name spaced out (`rowSpacing` → "Row Spacing"). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub label: Option, + /// The unit the value is in, shown after the field (the plug-in's own: nothing is converted). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub unit: Option, + /// The section of the dialog the parameter is in. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub group: Option, + /// What the parameter does, shown when the pointer rests on its label. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub help: Option, + /// An `https://` page about the parameter, opened by the help button after its field. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub help_url: Option, + /// Shown only while each parameter named here has one of the values listed for it. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub visible_when: BTreeMap>, +} + +/// Is `s` 1 to `max` characters, not all spaces, without control characters (`\n` too, unless +/// `lines`)? +fn printable(s: &str, max: usize, lines: bool) -> bool { + !s.trim().is_empty() && s.chars().count() <= max && s.chars().all(|c| !c.is_control() || (lines && c == '\n')) +} + +impl ParamUi { + /// Checks the keys of parameter `name`, the `index`th of manifest `m`'s parameters. + pub(crate) fn validate(&self, m: &Manifest, index: usize, name: &str) -> Result<()> { + let bad = |what: &str| Err(Error::Manifest(format!("parameter `{name}`: {what}"))); + let text = |v: &Option, max: usize, lines: bool| v.as_deref().is_none_or(|s| printable(s, max, lines)); + if !text(&self.label, MAX_LABEL, false) || !text(&self.group, MAX_LABEL, false) { + return bad(&format!("`label` and `group` must be 1-{MAX_LABEL} printable characters")); + } + if !text(&self.unit, MAX_UNIT, false) { + return bad(&format!("`unit` must be 1-{MAX_UNIT} printable characters")); + } + if !text(&self.help, MAX_HELP, true) { + return bad(&format!("`help` must be 1-{MAX_HELP} printable characters")); + } + if let Some(url) = &self.help_url { + let rest = url.strip_prefix("https://").unwrap_or_default(); + if rest.is_empty() || url.len() > MAX_HELP_URL || url.chars().any(|c| c.is_whitespace() || c.is_control()) { + return bad(&format!("`helpUrl` must be an https:// address of at most {MAX_HELP_URL} bytes")); + } + } + if self.visible_when.len() > MAX_CONDITIONS { + return bad(&format!("`visibleWhen` names at most {MAX_CONDITIONS} parameters")); + } + let before = m.params.get(..index).unwrap_or_default(); + for (other, values) in &self.visible_when { + let Some((_, p)) = before.iter().find(|(k, _)| k == other) else { + return bad(&format!("`visibleWhen` names `{other}`, which isn't a parameter declared before this one")); + }; + if values.is_empty() || values.len() > MAX_CONDITION_VALUES { + return bad(&format!("`visibleWhen` lists 1 to {MAX_CONDITION_VALUES} values for `{other}`")); + } + let fits = |v: &Value| match &p.spec { + ParamSpec::Bool { .. } => v.is_boolean(), + ParamSpec::Choice { options, .. } => v.as_str().is_some_and(|s| options.iter().any(|o| o == s)), + _ => false, + }; + if !values.iter().all(fits) { + return bad(&format!("`visibleWhen` takes `{other}`'s values, of a checkbox or a choice")); + } + } + Ok(()) + } +} + +impl Manifest { + /// The names of the parameters shown while the dialog's values are `values` (missing ones at + /// their defaults): those whose `visibleWhen` names only shown parameters, each with one of the + /// values listed for it. + /// + /// One pass in declaration order decides each parameter once, from the parameters before it. + /// Following the conditions back instead would revisit a parameter once per path to it, and + /// overlapping conditions have exponentially many. A condition on a parameter declared later, + /// which only a manifest built in code can have, hides the parameter, so conditions that go + /// round in a circle hide every parameter on it. + pub fn visible(&self, values: &Map) -> BTreeSet<&str> { + let mut shown = BTreeSet::new(); + for (name, p) in &self.params { + let met = p.ui.visible_when.iter().all(|(other, allowed)| { + shown.contains(other.as_str()) + && match values.get(other) { + Some(v) => allowed.contains(v), + None => self.param(other).is_some_and(|o| allowed.contains(&o.spec.default_value())), + } + }); + if met { + shown.insert(name.as_str()); + } + } + shown + } + + /// Is parameter `name` shown while the dialog's values are `values`? See [`Manifest::visible`], + /// which a dialog calls once for all its parameters. + pub fn shown(&self, name: &str, values: &Map) -> bool { + self.visible(values).contains(name) + } + + /// The parameter named `name`. + pub fn param(&self, name: &str) -> Option<&Param> { + self.params.iter().find(|(k, _)| k == name).map(|(_, p)| p) + } + + /// The dialog's sections in order: the parameters outside any group (`None`), then each group + /// in the order it first appears, each with its parameters in declaration order. + pub fn sections(&self) -> Vec> { + let mut out: Vec

= Vec::new(); + let ungrouped: Vec<_> = self.params.iter().filter(|(_, p)| p.ui.group.is_none()).collect(); + if !ungrouped.is_empty() { + out.push((None, ungrouped)); + } + for entry in &self.params { + let Some(group) = entry.1.ui.group.as_deref() else { continue }; + match out.iter_mut().find(|(g, _)| *g == Some(group)) { + Some((_, members)) => members.push(entry), + None => out.push((Some(group), vec![entry])), + } + } + out + } +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + const RICH: &str = r#"{"id":"org.example.hatch","name":"Hatch","kind":"effect","params":{ + "pattern":{"type":"choice","options":["lines","crosshatch","dots"],"default":"lines", + "label":"Pattern","group":"Fill","help":"How the shape is filled."}, + "spacing":{"type":"number","min":0.1,"max":10,"default":0.25,"label":"Spacing","unit":"mm","group":"Fill", + "help":"Distance between the lines.\nSmaller is denser.","helpUrl":"https://example.org/params/spacing", + "visibleWhen":{"pattern":["lines","crosshatch"]}}, + "outline":{"type":"bool","default":true,"label":"Outline"}, + "outline_width":{"type":"number","min":0,"max":10,"default":0.5,"unit":"pt","group":"Outline","visibleWhen":{"outline":[true]}}, + "outline_passes":{"type":"int","min":1,"max":4,"default":1,"group":"Outline", + "visibleWhen":{"outline":[true],"pattern":["lines"]}}, + "seed":{"type":"int","min":0,"max":9}}}"#; + + fn rich() -> Manifest { + Manifest::parse(RICH.as_bytes()).unwrap() + } + + #[test] + fn keys_parse_and_round_trip_with_the_parameters() { + let m = rich(); + let spacing = m.param("spacing").unwrap(); + assert_eq!( + (spacing.ui.label.as_deref(), spacing.ui.unit.as_deref(), spacing.ui.group.as_deref()), + (Some("Spacing"), Some("mm"), Some("Fill")) + ); + assert_eq!(spacing.ui.help_url.as_deref(), Some("https://example.org/params/spacing")); + assert_eq!(spacing.spec, ParamSpec::Number { min: 0.1, max: 10.0, default: 0.25 }); + assert_eq!(m.param("seed").unwrap().ui, ParamUi::default()); + // Written out, the manifest reads back as it was, parameters in their order. + assert_eq!(Manifest::parse(&serde_json::to_vec(&m).unwrap()).unwrap(), m); + assert_eq!(serde_json::to_value(&m).unwrap()["params"]["seed"], json!({"type": "int", "min": 0, "max": 9, "default": 0})); + } + + #[test] + fn sections_put_ungrouped_parameters_first_then_groups_as_they_appear() { + let m = rich(); + let names: Vec<(Option<&str>, Vec<&str>)> = + m.sections().into_iter().map(|(g, ps)| (g, ps.into_iter().map(|(k, _)| k.as_str()).collect())).collect(); + assert_eq!( + names, + [(None, vec!["outline", "seed"]), (Some("Fill"), vec!["pattern", "spacing"]), (Some("Outline"), vec!["outline_width", "outline_passes"])] + ); + } + + #[test] + fn visible_when_follows_the_values_and_the_parameters_it_names() { + let m = rich(); + let shown = |values: Value| -> Vec<&str> { + let values = values.as_object().cloned().unwrap_or_default(); + m.params.iter().filter(|(k, _)| m.shown(k, &values)).map(|(k, _)| k.as_str()).collect() + }; + // At the defaults: lines, with an outline. + assert_eq!(shown(json!({})), ["pattern", "spacing", "outline", "outline_width", "outline_passes", "seed"]); + assert_eq!(shown(json!({"pattern": "dots"})), ["pattern", "outline", "outline_width", "seed"]); + assert_eq!(shown(json!({"outline": false})), ["pattern", "spacing", "outline", "seed"]); + assert!(!m.shown("no_such_parameter", &Map::new())); + } + + /// A manifest built in code rather than parsed can name parameters in a circle: they are + /// hidden instead of recursing forever. + #[test] + fn conditions_in_a_circle_hide_their_parameters() { + let mut m = rich(); + let outline = m.params.iter().position(|(k, _)| k == "outline").unwrap(); + // `outline` names `outline_width`, which names `outline`. + m.params[outline].1.ui.visible_when.insert("outline_width".into(), vec![json!(0.5)]); + assert!(!m.shown("outline", &Map::new()) && !m.shown("outline_width", &Map::new())); + assert!(m.shown("seed", &Map::new()) && m.shown("pattern", &Map::new())); + } + + /// Conditions that each name several earlier parameters are checked once per parameter, not + /// once per path through them: 256 checkboxes, each shown while the 8 before it are checked, + /// would otherwise take longer than the age of the universe on every frame of the dialog. + #[test] + fn overlapping_conditions_are_checked_once_per_parameter() { + let params: Vec = (0..256) + .map(|i: usize| { + let when: Vec = (i.saturating_sub(MAX_CONDITIONS)..i).map(|j| format!(r#""p{j}":[true]"#)).collect(); + format!(r#""p{i}":{{"type":"bool","default":true,"group":"G","visibleWhen":{{{}}}}}"#, when.join(",")) + }) + .collect(); + let m = Manifest::parse(format!(r#"{{"id":"a","name":"x","kind":"filter","params":{{{}}}}}"#, params.join(",")).as_bytes()).unwrap(); + let (done, finished) = std::sync::mpsc::channel(); + std::thread::spawn(move || done.send(m.visible(&Map::new()).len())); + let shown = finished.recv_timeout(std::time::Duration::from_secs(10)).expect("the check took more than 10 s"); + assert_eq!(shown, 256, "every checkbox is checked, so every parameter is shown"); + // Unchecking the first hides the rest: each names it or one it hides. + let m = Manifest::parse(format!(r#"{{"id":"a","name":"x","kind":"filter","params":{{{}}}}}"#, params.join(",")).as_bytes()).unwrap(); + let values = json!({"p0": false}).as_object().cloned().unwrap(); + assert_eq!(m.visible(&values).into_iter().collect::>(), ["p0"]); + } + + #[test] + fn bad_keys_are_refused() { + let with = |key: &str, value: &str| { + format!( + r#"{{"id":"a","name":"x","kind":"filter","params":{{"mode":{{"type":"choice","options":["a","b"]}}, + "on":{{"type":"bool"}},"n":{{"type":"number","min":0,"max":1,"default":0,"{key}":{value}}}}}}}"# + ) + }; + let long = format!("\"{}\"", "x".repeat(MAX_LABEL + 1)); + for (key, value) in [ + ("label", r#""""#), + ("label", r#"" ""#), + ("label", r#""a\u0007b""#), + ("label", long.as_str()), + ("group", r#""line\nbreak""#), + ("unit", r#""millimetres and more""#), + ("help", r#""""#), + ("helpUrl", r#""http://example.org""#), + ("helpUrl", r#""https://""#), + ("helpUrl", r#""https://exa mple.org""#), + ("helpUrl", r#""javascript:alert(1)""#), + ("visibleWhen", r#"{"missing":[true]}"#), + ("visibleWhen", r#"{"n":[0]}"#), + ("visibleWhen", r#"{"on":["yes"]}"#), + ("visibleWhen", r#"{"mode":["c"]}"#), + ("visibleWhen", r#"{"mode":[]}"#), + ] { + let manifest = with(key, value); + assert!(Manifest::parse(manifest.as_bytes()).is_err(), "{key}: {value}"); + } + // A parameter declared after the one that names it, and one naming itself. + let later = r#"{"id":"a","name":"x","kind":"filter","params":{"n":{"type":"number","min":0,"max":1,"default":0, + "visibleWhen":{"on":[true]}},"on":{"type":"bool"}}}"#; + let itself = r#"{"id":"a","name":"x","kind":"filter","params":{"on":{"type":"bool","visibleWhen":{"on":[true]}}}}"#; + for bad in [later, itself] { + assert!(Manifest::parse(bad.as_bytes()).is_err(), "{bad}"); + } + let fine = with("help", r#""Two\nlines.""#); + assert!(Manifest::parse(fine.as_bytes()).is_ok()); + } +} diff --git a/crates/plugins/src/effect.rs b/crates/plugins/src/effect.rs index b95f12a0fd..8796745f60 100644 --- a/crates/plugins/src/effect.rs +++ b/crates/plugins/src/effect.rs @@ -1,23 +1,28 @@ //! Live-effect plug-ins: a plug-in of kind `effect` rewrites one object's geometry each time it is //! drawn, from its appearance stack (an `Effect` record with id `plugin.`). //! +//! The plug-in is given the geometry and, read only, the object's fills and strokes as a filter +//! sees them ([`Paints`]): an effect can draw as wide as the stroke it sits on, or tell its fills +//! apart, without asking for them again as parameters. +//! //! Drawing evaluates effects often (every frame, hit tests, bounds), so results are cached by -//! plug-in installation, parameters and input geometry: the plug-in runs again only when one of -//! them changes. Failures are cached too (the geometry is then drawn unchanged) and reported by -//! [`last_error`]. +//! plug-in installation, parameters, input geometry and paints: the plug-in runs again only when +//! one of them changes. Failures are cached too (the geometry is then drawn unchanged) and +//! reported by [`last_error`]. use std::collections::HashMap; use std::hash::{Hash, Hasher}; use std::sync::Mutex; use serde_json::{Value, json}; +use vectorcraft_doc::{Appearance, AppearanceItem}; use vectorcraft_geom::{FillRule, PathData, Rect}; -use crate::objects::{decode, output_geometry}; +use crate::objects::{decode, output_geometry, paint_lists}; use crate::{Error, Kind, Limits, Result, registry}; /// The effect id prefix of live-effect plug-ins: `plugin.`. -pub const PREFIX: &str = "plugin."; +pub const PREFIX: &str = crate::PREFIX; /// Wall-clock budget of one live-effect run (drawing waits for it), in milliseconds. pub const WALL_TIME_MS: u64 = 5_000; @@ -40,10 +45,47 @@ pub fn installed(effect_id: &str) -> Option> { registry::get(plugin_id(effect_id)?).filter(|p| p.manifest().kind == Kind::Effect) } +/// What a live effect is given besides its geometry: the object's appearance and where in it the +/// effect sits. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Paints<'a> { + /// The object's fills and strokes (`None`: an object without, given as empty lists). + pub appearance: Option<&'a Appearance>, + /// The index in `appearance.items` of the fill or stroke whose own effects hold this one; + /// `None`: one of the object's effects. + pub item: Option, +} + +/// [`Paints`] as the plug-in is given them: the input object's `fills` and `strokes`, and +/// `_context.item`. +struct Given { + fills: Vec, + strokes: Vec, + item: Value, +} + +impl Paints<'_> { + /// What the plug-in is given: `item` is `"object"`, or `{"fill": i}` / `{"stroke": i}` with `i` + /// counting the object's fills or strokes from the bottom. + fn given(&self) -> Given { + let Some(ap) = self.appearance else { return Given { fills: Vec::new(), strokes: Vec::new(), item: json!("object") } }; + let (fills, strokes) = paint_lists(ap); + let at = self.item.and_then(|i| Some((ap.items.get(i)?, ap.items.get(..i)?))); + let item = match at { + Some((AppearanceItem::Fill(_), below)) => json!({"fill": below.iter().filter(|i| i.is_fill()).count()}), + Some((AppearanceItem::Stroke(_), below)) => json!({"stroke": below.iter().filter(|i| !i.is_fill()).count()}), + None => json!("object"), + }; + Given { fills, strokes, item } + } +} + #[derive(PartialEq)] struct Key { serial: u64, params: String, + /// The paints and `_context.item`, as the plug-in is given them. + paints: String, bounds: [u64; 4], rule: FillRule, path: PathData, @@ -52,7 +94,7 @@ struct Key { impl Key { fn hash64(&self) -> u64 { let mut h = std::collections::hash_map::DefaultHasher::new(); - (self.serial, &self.params, self.bounds, self.rule).hash(&mut h); + (self.serial, &self.params, &self.paints, self.bounds, self.rule).hash(&mut h); for sp in &self.path.subpaths { sp.closed.hash(&mut h); for a in &sp.anchors { @@ -84,15 +126,17 @@ fn note(id: &str, r: &Result) { }; } -/// Runs live-effect plug-in `id` on `path` (whose reference box is `bounds`): the new geometry, -/// or `None` when the plug-in isn't installed, isn't an effect, or fails (the caller then keeps -/// the geometry). -pub fn apply(id: &str, params: &Value, path: &PathData, bounds: Rect, rule: FillRule) -> Option { +/// Runs live-effect plug-in `id` on `path` (whose reference box is `bounds`), of an object painted +/// with `paints`: the new geometry, or `None` when the plug-in isn't installed, isn't an effect, or +/// fails (the caller then keeps the geometry). +pub fn apply(id: &str, params: &Value, path: &PathData, bounds: Rect, rule: FillRule, paints: Paints) -> Option { let plugin = registry::get(id).filter(|p| p.manifest().kind == Kind::Effect)?; let resolved = Value::Object(plugin.manifest().resolve_params(params).ok()?); + let given = paints.given(); let key = Key { serial: plugin.serial(), params: resolved.to_string(), + paints: json!([given.fills, given.strokes, given.item]).to_string(), bounds: [bounds.x0, bounds.y0, bounds.x1, bounds.y1].map(f64::to_bits), rule, path: path.clone(), @@ -103,7 +147,12 @@ pub fn apply(id: &str, params: &Value, path: &PathData, bounds: Rect, rule: Fill { return out.clone(); } - let r = run(&plugin, resolved, path, bounds, rule); + let r = run(&plugin, resolved, path, bounds, rule, given); + // A drawing that was cancelled (an export stopped half way) says nothing about the plug-in: + // the next drawing runs it again. + if matches!(r, Err(Error::Cancelled)) { + return None; + } note(id, &r); let out = r.ok(); let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner()); @@ -115,16 +164,45 @@ pub fn apply(id: &str, params: &Value, path: &PathData, bounds: Rect, rule: Fill out } -fn run(plugin: &crate::Plugin, mut params: Value, path: &PathData, bounds: Rect, rule: FillRule) -> Result { +/// One run of `plugin` on `path`, with the object's paints as `given`. +fn run(plugin: &crate::Plugin, mut params: Value, path: &PathData, bounds: Rect, rule: FillRule, given: Given) -> Result { let b = json!([bounds.x0, bounds.y0, bounds.x1, bounds.y1]); - params["_context"] = json!({"mode": "effect", "bounds": b}); + params["_context"] = json!({"mode": "effect", "bounds": b, "item": given.item}); let rule = match rule { FillRule::NonZero => "nonzero", FillRule::EvenOdd => "evenodd", }; - let input = json!({"objects": [{"type": "path", "path": path, "fillRule": rule, "bounds": b}]}); + let input = json!({"objects": [{"type": "path", "path": path, "fillRule": rule, "bounds": b, "fills": given.fills, "strokes": given.strokes}]}); let (input, params) = (serde_json::to_vec(&input), serde_json::to_vec(¶ms)); let (Ok(input), Ok(params)) = (input, params) else { return Err(Error::Params("can't encode the input".into())) }; let limits = Limits { wall_time_ms: WALL_TIME_MS, ..plugin.limits().clone() }; Ok(output_geometry(decode(&plugin.run_limited(&input, ¶ms, &limits)?)?)) } + +#[cfg(test)] +mod tests { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{FillLayer, StrokeLayer}; + + use super::*; + + /// Fills and strokes come in paint order, and the item an effect sits on is counted among the + /// fills or among the strokes. + #[test] + fn the_paints_and_the_item_given() { + let fill = |c| AppearanceItem::Fill(FillLayer::new(Paint::solid(c))); + let stroke = |w| AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), w)); + let ap = Appearance { items: vec![fill(Color::WHITE), stroke(2.0), fill(Color::BLACK), stroke(5.0)], ..Appearance::default() }; + let given = |item| Paints { appearance: Some(&ap), item }.given(); + let g = given(None); + assert_eq!((g.fills.len(), g.strokes.len(), &g.item), (2, 2, &json!("object"))); + assert_eq!(g.strokes.iter().map(|s| s["width"].clone()).collect::>(), [json!(2.0), json!(5.0)]); + assert_eq!(g.fills[0], serde_json::to_value(Paint::solid(Color::WHITE)).unwrap()); + assert_eq!(given(Some(3)).item, json!({"stroke": 1})); + assert_eq!(given(Some(2)).item, json!({"fill": 1})); + assert_eq!(given(Some(0)).item, json!({"fill": 0})); + assert_eq!(given(Some(9)).item, json!("object"), "no such item"); + let none = Paints::default().given(); + assert_eq!((none.fills, none.strokes, none.item), (vec![], vec![], json!("object"))); + } +} diff --git a/crates/plugins/src/export.rs b/crates/plugins/src/export.rs new file mode 100644 index 0000000000..9ecc76277b --- /dev/null +++ b/crates/plugins/src/export.rs @@ -0,0 +1,141 @@ +//! Exporter plug-ins: a plug-in of kind `exporter` writes the document in a file format of its +//! own, such as a pen plotter's or a cutting machine's. +//! +//! File › Export › Export As lists each installed exporter after the built-in formats, under its +//! name, and `document.export` writes it by its format id (`plugin.`) or by one of the +//! extensions its manifest lists. A built-in format keeps its extension: an exporter that lists +//! `svg` too is picked by its format id. The host hands the exporter the document as the native +//! file's JSON (`vectorcraft_format::json_part`: images of `INLINE_MAX` bytes or more without +//! their data) and writes the bytes it returns. +//! +//! An export is one run the user asked for, often of a whole document, so it gets a larger budget +//! than a filter: [`FUEL`] instructions, plus [`Limits::fuel_per_byte`] for each byte of input, +//! and [`WALL_TIME_MS`]. It runs where the export runs: with Background Export on the export's +//! worker, whose Cancel stops it between two slices of the budget ([`Error::Cancelled`]). + +use std::sync::Arc; + +use serde_json::{Value, json}; + +use crate::objects::{declined, printable}; +use crate::{Error, Kind, Limits, Plugin, Result, registry}; + +/// Instructions an export may use, besides [`Limits::fuel_per_byte`] for each byte of the +/// document: 200 times a filter's base budget. +pub const FUEL: u64 = 10_000_000_000; + +/// Wall-clock budget of one export, in milliseconds (native builds; the web build has no clock, +/// and the instruction budget alone bounds it there). +pub const WALL_TIME_MS: u64 = 300_000; + +/// Most warnings an export reports. +pub const MAX_WARNINGS: usize = 100; + +/// Longest warning, in characters. +pub const MAX_WARNING_CHARS: usize = 500; + +/// The format id of exporter `plugin_id`: `plugin.`. +pub fn format_id(plugin_id: &str) -> String { + format!("{}{plugin_id}", crate::PREFIX) +} + +/// The plug-in id in format id `format_id`. +pub fn plugin_id(format_id: &str) -> Option<&str> { + format_id.strip_prefix(crate::PREFIX) +} + +/// The installed exporters, by plug-in id. +pub fn installed() -> Vec> { + registry::list().into_iter().filter(|p| p.manifest().kind == Kind::Exporter).collect() +} + +/// The installed exporter of format id `format_id`. +pub fn by_format(format_id: &str) -> Option> { + registry::get(plugin_id(format_id)?).filter(|p| p.manifest().kind == Kind::Exporter) +} + +/// What an exporter returned. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Exported { + /// The file, base64 encoded, as the plug-in returned it (the host decodes it: this crate has + /// no base64 of its own). + pub data_base64: String, + /// What the export left out or changed, for the user (at most [`MAX_WARNINGS`]). + pub warnings: Vec, +} + +/// The file an export writes, as the exporter is told in `_context`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Target<'a> { + /// Its extension, without the dot: one the exporter lists. + pub extension: &'a str, + /// Its name without the extension (some formats keep a name in their header). + pub name: &'a str, +} + +/// The limits of an export by `plugin`: its own, with the budgets of an export. +pub fn limits(plugin: &Plugin) -> Limits { + Limits { fuel_base: FUEL, wall_time_ms: WALL_TIME_MS, ..plugin.limits().clone() } +} + +/// Runs exporter `plugin` on `document`, the native file's JSON, with `params` (checked against +/// its manifest: missing ones take their defaults) for the file `target`. +pub fn run(plugin: &Plugin, document: &[u8], params: &Value, target: Target) -> Result { + let m = plugin.manifest(); + if m.kind != Kind::Exporter { + return Err(Error::Params(format!("`{}` is a {}, not an exporter", m.id, m.kind.name()))); + } + let mut params = Value::Object(m.resolve_params(params)?); + params["_context"] = json!({"mode": "export", "extension": target.extension, "name": target.name}); + let params = serde_json::to_vec(¶ms).map_err(|e| Error::Params(e.to_string()))?; + decode(&plugin.run_limited(document, ¶ms, &limits(plugin))?) +} + +/// An exporter's output: `{"dataBase64": "…", "warnings"?: ["…"]}`, or `{"error": "…"}` to decline +/// with a message for the user. +pub fn decode(bytes: &[u8]) -> Result { + let v: Value = serde_json::from_slice(bytes).map_err(|e| Error::Output(format!("not JSON: {e}")))?; + if let Some(e) = declined(&v) { + return Err(e); + } + let data = v.get("dataBase64").and_then(Value::as_str).ok_or_else(|| Error::Output("expected {\"dataBase64\": \"…\"}".into()))?; + let warnings = match v.get("warnings") { + None | Some(Value::Null) => Vec::new(), + Some(Value::Array(w)) => w.iter().take(MAX_WARNINGS).map(|w| printable(w, MAX_WARNING_CHARS)).collect(), + Some(_) => return Err(Error::Output("`warnings` must be a list of strings".into())), + }; + Ok(Exported { data_base64: data.to_string(), warnings }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn format_ids_name_the_plug_in() { + assert_eq!(format_id("org.example.plotter"), "plugin.org.example.plotter"); + assert_eq!(plugin_id("plugin.org.example.plotter"), Some("org.example.plotter")); + assert_eq!(plugin_id("png"), None); + } + + #[test] + fn output_is_the_data_and_the_warnings_or_a_decline() { + let out = decode(br#"{"dataBase64": "SGk=", "warnings": ["a", 2]}"#).unwrap(); + assert_eq!(out, Exported { data_base64: "SGk=".into(), warnings: vec!["a".into(), "2".into()] }); + assert_eq!(decode(br#"{"dataBase64": ""}"#).unwrap().warnings, Vec::::new()); + assert_eq!(decode(br#"{"error": "Nothing to\nwrite."}"#), Err(Error::Failed("Nothing towrite.".into()))); + for bad in [&b"[]"[..], b"{}", b"not json", br#"{"dataBase64": 1}"#, br#"{"dataBase64": "", "warnings": "x"}"#] { + assert!(matches!(decode(bad), Err(Error::Output(_))), "{}", String::from_utf8_lossy(bad)); + } + } + + #[test] + fn warnings_are_capped_in_number_and_length() { + let many: Vec = (0..MAX_WARNINGS + 5).map(|i| format!("w{i}")).collect(); + let long = "x".repeat(MAX_WARNING_CHARS + 1); + let out = decode(json!({"dataBase64": "", "warnings": many}).to_string().as_bytes()).unwrap(); + assert_eq!(out.warnings.len(), MAX_WARNINGS); + let out = decode(json!({"dataBase64": "", "warnings": [long]}).to_string().as_bytes()).unwrap(); + assert_eq!(out.warnings.first().map(|w| w.chars().count()), Some(MAX_WARNING_CHARS)); + } +} diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index beafd045bd..ecd1893649 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -17,20 +17,29 @@ //! their geometry, fills, strokes (gradients included) and opacity. An **object filter** returns //! the objects to keep, change or add, applied to the document as one edit //! ([`objects::apply_output`]); a **live effect** ([`effect`]) rewrites one object's geometry each -//! time it is drawn, from an appearance stack. The process-wide [`registry`] holds the installed -//! plug-ins. +//! time it is drawn, from an appearance stack; an **exporter** ([`export`]) writes the whole +//! document in a file format of its own. The process-wide [`registry`] holds the installed +//! plug-ins. A plug-in's parameters ([`manifest`]) come with what the host's dialogs need to show +//! them well: labels, units, groups, help and conditions ([`dialog`]). #![forbid(unsafe_code)] +pub mod dialog; pub mod effect; +pub mod export; pub mod manifest; pub mod objects; pub mod registry; mod runtime; pub mod wat; -pub use manifest::{Kind, Manifest, ParamSpec}; +pub use dialog::ParamUi; +pub use manifest::{Kind, Manifest, Param, ParamSpec}; pub use runtime::{ABI_VERSION, Limits, Plugin}; +/// What the host puts before a plug-in's id to name what it adds: its live effect +/// (`plugin.`, [`effect`]) or its file format ([`export`]). +pub const PREFIX: &str = "plugin."; + /// A plug-in error. Every way a module can misbehave ends here, never in a panic. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum Error { @@ -52,6 +61,10 @@ pub enum Error { Failed(String), #[error("no plug-in {0:?} is installed")] NotFound(String), + /// The caller asked the run to stop ([`vectorcraft_doc::cancel`]), between two slices of + /// its instruction budget. + #[error("cancelled")] + Cancelled, #[error("{0}")] Io(String), } diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index d74458ca35..609e20a84c 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -1,14 +1,24 @@ -//! The plug-in manifest (`vc_manifest`) and parameter schema. +//! The plug-in manifest (`vc_manifest`) and parameter schema: what each parameter holds +//! ([`ParamSpec`]) and how dialogs show it ([`ParamUi`], in [`crate::dialog`]). use serde::{Deserialize, Serialize}; use serde_json::{Map, Value, json}; +use crate::dialog::ParamUi; use crate::{Error, Result}; /// Longest manifest the host reads. pub const MAX_MANIFEST_BYTES: usize = 64 * 1024; /// Most parameters a plug-in may declare. -pub const MAX_PARAMS: usize = 64; +pub const MAX_PARAMS: usize = 256; +/// Most parameters outside groups (`group`): a dialog of more is sorted into sections. +pub const MAX_UNGROUPED: usize = 64; +/// Longest text a `string` parameter may hold, in characters. +pub const MAX_TEXT: usize = 4_096; +/// Most numbers a `numberList` parameter may hold. +pub const MAX_LIST: usize = 256; +/// Most file extensions an exporter may declare. +pub const MAX_EXTENSIONS: usize = 8; /// What a plug-in is. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -20,6 +30,9 @@ pub enum Kind { /// A live effect: rewrites one object's geometry each time it is drawn, from its appearance /// stack (Effect › Plug-ins, `effect.apply`). Effect, + /// An exporter: writes the document in a file format of its own, whose extensions the manifest + /// lists (File › Export › Export As, `document.export`; see [`crate::export`]). + Exporter, } impl Kind { @@ -27,6 +40,7 @@ impl Kind { match self { Kind::Filter => "filter", Kind::Effect => "effect", + Kind::Exporter => "exporter", } } } @@ -57,6 +71,27 @@ pub enum ParamSpec { #[serde(default)] default: Option, }, + /// Text of at most `max_length` characters (a text field). + #[serde(rename = "string")] + Text { + #[serde(default)] + default: String, + #[serde(default = "text_max", rename = "maxLength")] + max_length: usize, + }, + /// `min_items` to `max_items` numbers, each in `min..=max` (a field of numbers separated by + /// commas or spaces). + #[serde(rename_all = "camelCase")] + NumberList { + min: f64, + max: f64, + #[serde(default)] + default: Vec, + #[serde(default)] + min_items: usize, + #[serde(default = "list_max")] + max_items: usize, + }, } fn int_min() -> i64 { @@ -65,6 +100,28 @@ fn int_min() -> i64 { fn int_max() -> i64 { 1_000_000 } +fn text_max() -> usize { + 256 +} +fn list_max() -> usize { + 16 +} + +/// One declared parameter: what it holds, and how dialogs show it. In the manifest both are keys of +/// the same object: `{"type": "number", "min": 0, "max": 10, "default": 1, "unit": "mm"}`. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Param { + #[serde(flatten)] + pub spec: ParamSpec, + #[serde(flatten)] + pub ui: ParamUi, +} + +impl From for Param { + fn from(spec: ParamSpec) -> Self { + Param { spec, ui: ParamUi::default() } + } +} impl ParamSpec { /// The value a parameter takes when it isn't given (numeric defaults clamped into range). @@ -74,6 +131,40 @@ impl ParamSpec { ParamSpec::Int { min, max, default } => json!((*default).clamp(*min, *max)), ParamSpec::Bool { default } => json!(default), ParamSpec::Choice { options, default } => json!(default.clone().or_else(|| options.first().cloned()).unwrap_or_default()), + ParamSpec::Text { default, max_length } => json!(default.chars().take(*max_length).collect::()), + ParamSpec::NumberList { min, max, default, .. } => json!(default.iter().map(|x| x.clamp(*min, *max)).collect::>()), + } + } + + /// Checks the spec of parameter `k`. + fn validate(&self, k: &str) -> Result<()> { + let bad = |what: &str| Err(Error::Manifest(format!("parameter `{k}`: {what}"))); + match self { + ParamSpec::Number { min, max, default } if !(min.is_finite() && max.is_finite() && default.is_finite()) || min > max => bad("bad range"), + ParamSpec::Int { min, max, .. } if min > max => bad("bad range"), + ParamSpec::Choice { options, default } => { + if options.is_empty() || options.len() > 64 || options.iter().any(|o| o.is_empty() || o.len() > 64 || o.chars().any(char::is_control)) + { + return bad("choices must be 1-64 non-empty, printable strings"); + } + if default.as_ref().is_some_and(|d| !options.contains(d)) { + return bad("default is not one of the options"); + } + Ok(()) + } + ParamSpec::Text { default, max_length } if !(1..=MAX_TEXT).contains(max_length) || default.chars().count() > *max_length => { + bad(&format!("`maxLength` must be 1-{MAX_TEXT}, and the default no longer")) + } + ParamSpec::NumberList { min, max, default, min_items, max_items } => { + if !(min.is_finite() && max.is_finite()) || min > max || default.iter().any(|x| !x.is_finite()) { + return bad("bad range"); + } + if !(1..=MAX_LIST).contains(max_items) || min_items > max_items || !(*min_items..=*max_items).contains(&default.len()) { + return bad(&format!("`minItems` and `maxItems` must be 0-{MAX_LIST}, `maxItems` at least 1, and the default that many")); + } + Ok(()) + } + _ => Ok(()), } } } @@ -95,7 +186,11 @@ pub struct Manifest { pub author: String, /// Parameters in declaration (dialog) order; a JSON object `{"name": spec, …}` in the manifest. #[serde(default, deserialize_with = "ordered_params", serialize_with = "params_as_object")] - pub params: Vec<(String, ParamSpec)>, + pub params: Vec<(String, Param)>, + /// An exporter's file extensions, lower case and without the dot; the first is the one its + /// files get. Only exporters declare them. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub extensions: Vec, } impl Manifest { @@ -120,6 +215,7 @@ impl Manifest { description: String::new(), author: String::new(), params: Vec::new(), + extensions: Vec::new(), } } @@ -134,27 +230,38 @@ impl Manifest { if self.version.len() > 32 || self.description.len() > 1024 || self.author.len() > 128 { return Err(Error::Manifest("`version`, `description` or `author` is too long".into())); } - for (k, spec) in &self.params { + self.validate_extensions()?; + for (i, (k, p)) in self.params.iter().enumerate() { if !valid_key(k) { return Err(Error::Manifest(format!("invalid parameter name {k:?}"))); } - match spec { - ParamSpec::Number { min, max, default } if !(min.is_finite() && max.is_finite() && default.is_finite()) || min > max => { - return Err(Error::Manifest(format!("parameter `{k}`: bad range"))); - } - ParamSpec::Int { min, max, .. } if min > max => return Err(Error::Manifest(format!("parameter `{k}`: bad range"))), - ParamSpec::Choice { options, default } => { - if options.is_empty() - || options.len() > 64 - || options.iter().any(|o| o.is_empty() || o.len() > 64 || o.chars().any(char::is_control)) - { - return Err(Error::Manifest(format!("parameter `{k}`: choices must be 1-64 non-empty, printable strings"))); - } - if default.as_ref().is_some_and(|d| !options.contains(d)) { - return Err(Error::Manifest(format!("parameter `{k}`: default is not one of the options"))); - } - } - _ => {} + p.spec.validate(k)?; + p.ui.validate(self, i, k)?; + } + if self.params.iter().filter(|(_, p)| p.ui.group.is_none()).count() > MAX_UNGROUPED { + return Err(Error::Manifest(format!("at most {MAX_UNGROUPED} parameters outside groups: give the others a `group`"))); + } + Ok(()) + } + + /// An exporter lists 1 to [`MAX_EXTENSIONS`] distinct extensions of 1 to 16 lower-case + /// letters and digits; other kinds list none. + fn validate_extensions(&self) -> Result<()> { + let exts = &self.extensions; + match self.kind { + Kind::Exporter => {} + _ if exts.is_empty() => return Ok(()), + _ => return Err(Error::Manifest("only an exporter declares `extensions`".into())), + } + if exts.is_empty() || exts.len() > MAX_EXTENSIONS { + return Err(Error::Manifest(format!("an exporter declares 1 to {MAX_EXTENSIONS} `extensions`"))); + } + for (i, e) in exts.iter().enumerate() { + if !(1..=16).contains(&e.len()) || !e.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()) { + return Err(Error::Manifest(format!("extension {e:?}: use 1-16 lower-case letters and digits, without the dot"))); + } + if exts.get(..i).is_some_and(|before| before.contains(e)) { + return Err(Error::Manifest(format!("extension {e:?} is listed twice"))); } } Ok(()) @@ -166,13 +273,17 @@ impl Manifest { let parts: Vec = self .params .iter() - .map(|(k, spec)| match spec { + .map(|(k, p)| match &p.spec { ParamSpec::Number { min, max, default } => format!("{k}: {min}..{max} ({})", default.clamp(*min, *max)), ParamSpec::Int { min, max, default } => format!("{k}: int {min}..{max} ({})", (*default).clamp(*min, *max)), ParamSpec::Bool { default } => format!("{k}: bool ({default})"), ParamSpec::Choice { options, .. } => { let opts: Vec = options.iter().map(|o| format!("{o:?}")).collect(); - format!("{k}: {} ({})", opts.join("|"), spec.default_value().as_str().unwrap_or_default()) + format!("{k}: {} ({})", opts.join("|"), p.spec.default_value().as_str().unwrap_or_default()) + } + ParamSpec::Text { max_length, .. } => format!("{k}: string of at most {max_length} ({})", p.spec.default_value()), + ParamSpec::NumberList { min, max, min_items, max_items, .. } => { + format!("{k}: {min_items} to {max_items} numbers {min}..{max} ({})", p.spec.default_value()) } }) .collect(); @@ -181,7 +292,7 @@ impl Manifest { /// Every parameter at its default value. pub fn defaults(&self) -> Map { - self.params.iter().map(|(k, spec)| (k.clone(), spec.default_value())).collect() + self.params.iter().map(|(k, p)| (k.clone(), p.spec.default_value())).collect() } /// Validates user `params` against the schema: missing keys take their defaults, numbers are @@ -194,7 +305,8 @@ impl Manifest { _ => return Err(Error::Params("plug-in parameters must be a JSON object".into())), }; let mut out = Map::new(); - for (k, spec) in &self.params { + for (k, p) in &self.params { + let spec = &p.spec; let Some(v) = given.get(k).filter(|v| !v.is_null()) else { out.insert(k.clone(), spec.default_value()); continue; @@ -223,6 +335,17 @@ impl Manifest { } json!(s) } + ParamSpec::Text { max_length, .. } => { + json!(v.as_str().ok_or_else(|| wrong("a string"))?.chars().take(*max_length).collect::()) + } + ParamSpec::NumberList { min, max, min_items, max_items, .. } => { + let items = v.as_array().ok_or_else(|| wrong("a list of numbers"))?; + if !(*min_items..=*max_items).contains(&items.len()) { + return Err(wrong(&format!("a list of {min_items} to {max_items} numbers"))); + } + let numbers: Option> = items.iter().map(|x| x.as_f64().filter(|f| f.is_finite()).map(|f| f.clamp(*min, *max))).collect(); + json!(numbers.ok_or_else(|| wrong("a list of numbers"))?) + } }; out.insert(k.clone(), resolved); } @@ -231,10 +354,10 @@ impl Manifest { } /// Reads the `params` object keeping its key order (serde_json's `Map` would sort it). -fn ordered_params<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result, D::Error> { +fn ordered_params<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result, D::Error> { struct V; impl<'de> serde::de::Visitor<'de> for V { - type Value = Vec<(String, ParamSpec)>; + type Value = Vec<(String, Param)>; fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.write_str("an object of parameter specs") } @@ -242,8 +365,8 @@ fn ordered_params<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result Ok(Vec::new()) } fn visit_map>(self, mut map: A) -> std::result::Result { - let mut out: Vec<(String, ParamSpec)> = Vec::new(); - while let Some((k, v)) = map.next_entry::()? { + let mut out: Vec<(String, Param)> = Vec::new(); + while let Some((k, v)) = map.next_entry::()? { if out.len() >= MAX_PARAMS { return Err(serde::de::Error::custom(format!("too many parameters (limit {MAX_PARAMS})"))); } @@ -258,7 +381,7 @@ fn ordered_params<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result d.deserialize_any(V) } -fn params_as_object(p: &[(String, ParamSpec)], s: S) -> std::result::Result { +fn params_as_object(p: &[(String, Param)], s: S) -> std::result::Result { use serde::ser::SerializeMap; let mut m = s.serialize_map(Some(p.len()))?; for (k, v) in p { @@ -355,6 +478,68 @@ mod tests { } } + #[test] + fn an_exporter_lists_its_extensions_and_other_kinds_list_none() { + let m = Manifest::parse(br#"{"id":"org.example.plotter","name":"Plotter","kind":"exporter","extensions":["plt","plot"]}"#).unwrap(); + assert_eq!((m.kind, m.extensions.as_slice()), (Kind::Exporter, &["plt".to_string(), "plot".to_string()][..])); + assert_eq!(serde_json::to_value(&m).unwrap()["extensions"], json!(["plt", "plot"])); + let filter = Manifest::parse(br#"{"id":"a","name":"x","kind":"filter"}"#).unwrap(); + assert!(serde_json::to_value(&filter).unwrap().get("extensions").is_none()); + for bad in [ + r#"{"id":"a","name":"x","kind":"exporter"}"#, + r#"{"id":"a","name":"x","kind":"exporter","extensions":[]}"#, + r#"{"id":"a","name":"x","kind":"exporter","extensions":["PLT"]}"#, + r#"{"id":"a","name":"x","kind":"exporter","extensions":[".plt"]}"#, + r#"{"id":"a","name":"x","kind":"exporter","extensions":[""]}"#, + r#"{"id":"a","name":"x","kind":"exporter","extensions":["abcdefghijklmnopq"]}"#, + r#"{"id":"a","name":"x","kind":"exporter","extensions":["plt","plt"]}"#, + r#"{"id":"a","name":"x","kind":"exporter","extensions":["a","b","c","d","e","f","g","h","i"]}"#, + r#"{"id":"a","name":"x","kind":"filter","extensions":["plt"]}"#, + r#"{"id":"a","name":"x","kind":"effect","extensions":["plt"]}"#, + ] { + assert!(Manifest::parse(bad.as_bytes()).is_err(), "{bad}"); + } + } + + #[test] + fn strings_and_number_lists_resolve_like_the_other_types() { + let m = Manifest::parse( + br#"{"id":"org.example.text","name":"Text","kind":"filter","params":{ + "label":{"type":"string","default":"Rose","maxLength":8}, + "angles":{"type":"numberList","min":0,"max":360,"default":[45,135],"minItems":1,"maxItems":3}, + "free":{"type":"string"}}}"#, + ) + .unwrap(); + assert_eq!(Value::Object(m.defaults()), json!({"label": "Rose", "angles": [45.0, 135.0], "free": ""})); + let p = m.resolve_params(&json!({"label": "Sunflowers", "angles": [-10, 90, 400]})).unwrap(); + assert_eq!((&p["label"], &p["angles"]), (&json!("Sunflowe"), &json!([0.0, 90.0, 360.0])), "cut and clamped"); + for bad in [json!({"label": 3}), json!({"angles": []}), json!({"angles": [1, 2, 3, 4]}), json!({"angles": [1, "x"]}), json!({"angles": 5})] { + assert!(m.resolve_params(&bad).is_err(), "{bad}"); + } + assert_eq!( + m.params_doc(), + r#"{label: string of at most 8 ("Rose"), angles: 1 to 3 numbers 0..360 ([45.0,135.0]), free: string of at most 256 ("")}"# + ); + } + + #[test] + fn up_to_256_parameters_with_at_most_64_outside_groups() { + let manifest = |n: usize, grouped: usize| { + let params: Vec = (0..n) + .map(|i| match i < grouped { + true => format!(r#""p{i}":{{"type":"bool","group":"G{}"}}"#, i % 4), + false => format!(r#""p{i}":{{"type":"bool"}}"#), + }) + .collect(); + format!(r#"{{"id":"a","name":"x","kind":"filter","params":{{{}}}}}"#, params.join(",")) + }; + assert!(Manifest::parse(manifest(MAX_UNGROUPED, 0).as_bytes()).is_ok()); + assert!(Manifest::parse(manifest(MAX_UNGROUPED + 1, 0).as_bytes()).is_err(), "too many outside groups"); + let all = Manifest::parse(manifest(MAX_PARAMS, MAX_PARAMS - MAX_UNGROUPED).as_bytes()).unwrap(); + assert_eq!(all.params.len(), MAX_PARAMS); + assert!(Manifest::parse(manifest(MAX_PARAMS + 1, MAX_PARAMS).as_bytes()).is_err(), "too many in all"); + } + #[test] fn rejects_bad_manifests() { for bad in [ @@ -372,6 +557,13 @@ mod tests { r#"{"id":"a","name":"x","kind":"filter","params":{"preview":{"type":"bool"}}}"#, r#"{"id":"a","name":"x","kind":"filter","params":{"a":{"type":"bool"},"a":{"type":"bool"}}}"#, r#"{"id":"a","name":"x","kind":"filter","params":[1]}"#, + r#"{"id":"a","name":"x","kind":"filter","params":{"t":{"type":"string","maxLength":0}}}"#, + r#"{"id":"a","name":"x","kind":"filter","params":{"t":{"type":"string","default":"abc","maxLength":2}}}"#, + r#"{"id":"a","name":"x","kind":"filter","params":{"l":{"type":"numberList","min":1,"max":0}}}"#, + r#"{"id":"a","name":"x","kind":"filter","params":{"l":{"type":"numberList","min":0,"max":1,"maxItems":0}}}"#, + r#"{"id":"a","name":"x","kind":"filter","params":{"l":{"type":"numberList","min":0,"max":1,"maxItems":257}}}"#, + r#"{"id":"a","name":"x","kind":"filter","params":{"l":{"type":"numberList","min":0,"max":1,"minItems":2,"maxItems":1}}}"#, + r#"{"id":"a","name":"x","kind":"filter","params":{"l":{"type":"numberList","min":0,"max":1,"minItems":2,"default":[1]}}}"#, ] { assert!(Manifest::parse(bad.as_bytes()).is_err(), "{bad}"); } diff --git a/crates/plugins/src/objects.rs b/crates/plugins/src/objects.rs index 7c0d60f021..c98dc5595c 100644 --- a/crates/plugins/src/objects.rs +++ b/crates/plugins/src/objects.rs @@ -83,18 +83,23 @@ pub fn geometry(n: &Node) -> Option<(PathData, FillRule, bool)> { } } -/// A path or compound path as plug-ins see it (`None` for other objects): `{id, type, name?, path, -/// fillRule, fills, strokes, opacity, bounds}`. -pub fn encode(n: &Node) -> Option { - let (path, rule, compound) = geometry(n)?; - let fills: Vec = - n.appearance.items.iter().filter_map(|i| if let AppearanceItem::Fill(f) = i { Some(paint_json(&f.paint)) } else { None }).collect(); - let strokes: Vec = n - .appearance +/// The fills and strokes of appearance `ap` as plug-ins see them, each in paint order: a fill is +/// its paint, a stroke `{paint, width}`. Filters and live effects are given the same. +pub(crate) fn paint_lists(ap: &Appearance) -> (Vec, Vec) { + let fills = ap.items.iter().filter_map(|i| if let AppearanceItem::Fill(f) = i { Some(paint_json(&f.paint)) } else { None }).collect(); + let strokes = ap .items .iter() .filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(json!({"paint": paint_json(&s.paint), "width": s.width})) } else { None }) .collect(); + (fills, strokes) +} + +/// A path or compound path as plug-ins see it (`None` for other objects): `{id, type, name?, path, +/// fillRule, fills, strokes, opacity, bounds}`. +pub fn encode(n: &Node) -> Option { + let (path, rule, compound) = geometry(n)?; + let (fills, strokes) = paint_lists(&n.appearance); let mut o = json!({ "id": n.id.0, "type": if compound { "compound" } else { "path" }, "path": path, "fillRule": rule_name(rule), "fills": fills, "strokes": strokes, "opacity": n.opacity, "bounds": rect_json(path.bounds()), @@ -286,9 +291,8 @@ fn decode_object(v: &Value, at: &str, anchors: &mut usize) -> Result /// declined (the message reaches the user). pub fn decode(bytes: &[u8]) -> Result> { let v: Value = serde_json::from_slice(bytes).map_err(|e| Error::Output(format!("not JSON: {e}")))?; - if let Some(e) = v.get("error").filter(|e| !e.is_null()) { - let msg: String = e.as_str().map_or_else(|| e.to_string(), str::to_string).chars().filter(|c| !c.is_control()).take(300).collect(); - return Err(Error::Failed(msg)); + if let Some(e) = declined(&v) { + return Err(e); } let objects = v.get("objects").and_then(Value::as_array).ok_or_else(|| Error::Output("expected {\"objects\": [...]}".into()))?; if objects.len() > MAX_OBJECTS { @@ -298,6 +302,20 @@ pub fn decode(bytes: &[u8]) -> Result> { objects.iter().enumerate().map(|(i, o)| decode_object(o, &format!("objects[{i}]"), &mut anchors)).collect() } +/// The decline in a plug-in's output `v`, `{"error": "…"}`: its message as the user reads it, +/// without control characters and at most 300 of them. +pub(crate) fn declined(v: &Value) -> Option { + let e = v.get("error").filter(|e| !e.is_null())?; + Some(Error::Failed(printable(e, 300))) +} + +/// A plug-in's text the user reads: `v` as a string (any other JSON as its text), without control +/// characters, at most `max` characters of it. +pub(crate) fn printable(v: &Value, max: usize) -> String { + let s = v.as_str().map_or_else(|| v.to_string(), str::to_string); + s.chars().filter(|c| !c.is_control()).take(max).collect() +} + /// The paints of `ap`'s fills (`fill`) or strokes, in paint order. fn paints(ap: &Appearance, fill: bool) -> Vec<&Paint> { ap.items.iter().filter(|i| i.is_fill() == fill).map(AppearanceItem::paint).collect() diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index d33aab7ef2..311d296ce8 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -206,7 +206,8 @@ impl Plugin { Ok(Live { store, instance, memory }) } - /// Calls `f` with at most `fuel` instructions, in slices, checking the deadline between them. + /// Calls `f` with at most `fuel` instructions, in slices, checking the deadline and the + /// caller's cancellation ([`vectorcraft_doc::cancel`]) between them. fn call(&self, live: &mut Live, f: &TypedFunc, params: P, fuel: u64, deadline: &Deadline) -> Result { let mut left = fuel; let give = left.min(FUEL_SLICE); @@ -223,6 +224,7 @@ impl Plugin { return Err(Error::Limit("instruction budget".into())); } deadline.check()?; + vectorcraft_doc::cancel::check().map_err(|_| Error::Cancelled)?; let give = left.min(FUEL_SLICE.max(need)); left -= give; live.store.set_fuel(give).map_err(wasm_err)?; diff --git a/crates/plugins/src/wat.rs b/crates/plugins/src/wat.rs index df544a8e63..5118d9cd69 100644 --- a/crates/plugins/src/wat.rs +++ b/crates/plugins/src/wat.rs @@ -41,7 +41,132 @@ pub fn returning(manifest: &str, output: &str) -> String { module(manifest, &run, &extra, (OUTPUT_AT + output.len()).div_ceil(0x1_0000) as u32 + 1) } +/// What [`when_given`] looks through. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Given { + /// The input JSON (the objects). + Input, + /// The parameters JSON, `_context` included. + Params, +} + +/// Where [`when_given`] keeps the text it looks for. +const NEEDLE_AT: usize = 0x8000; + +/// A plug-in that returns `output` when what it is given (`given`) holds the text `needle`, and +/// its input unchanged otherwise. A live effect made from it draws one shape or the other, so a +/// test sees from the geometry whether the host handed the plug-in something. +pub fn when_given(manifest: &str, given: Given, needle: &str, output: &str) -> String { + let (src, len) = match given { + Given::Input => ("$in", "$il"), + Given::Params => ("$pp", "$pl"), + }; + let n = needle.len(); + // For each place `$i` the needle fits, compare it byte by byte (`$j`). + let run = format!( + r#"(local $i i32) (local $j i32) + (block $found + (block $none + (loop $at + (br_if $none (i32.gt_u (i32.add (local.get $i) (i32.const {n})) (local.get {len}))) + (local.set $j (i32.const 0)) + (block $next + (loop $cmp + (br_if $found (i32.eq (local.get $j) (i32.const {n}))) + (br_if $next (i32.ne (i32.load8_u (i32.add (local.get {src}) (i32.add (local.get $i) (local.get $j)))) + (i32.load8_u (i32.add (i32.const {NEEDLE_AT}) (local.get $j))))) + (local.set $j (i32.add (local.get $j) (i32.const 1))) + (br $cmp))) + (local.set $i (i32.add (local.get $i) (i32.const 1))) + (br $at))) + (return {ECHO})) + (i64.or (i64.shl (i64.const {out}) (i64.const 32)) (i64.const {OUTPUT_AT}))"#, + out = output.len(), + ); + let extra = format!(r#"(data (i32.const {NEEDLE_AT}) "{}") (data (i32.const {OUTPUT_AT}) "{}")"#, string(needle), string(output)); + module(manifest, &run, &extra, (OUTPUT_AT + output.len()).div_ceil(0x1_0000) as u32 + 1) +} + /// The manifest of a test plug-in `id` of `kind` with `params` (a JSON object of specs). pub fn manifest(id: &str, kind: &str, params: &str) -> String { format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"{kind}","params":{params}}}"#) } + +/// The manifest of a test exporter `id` writing `extensions` (a JSON list) with `params`. +pub fn exporter(id: &str, extensions: &str, params: &str) -> String { + format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"exporter","extensions":{extensions},"params":{params}}}"#) +} + +/// What [`echo_exporter`] writes as its file. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Echo { + /// The input: the document, as the host hands it over. + Input, + /// The parameters JSON, `_context` included. + Params, +} + +/// Where [`echo_exporter`] keeps the base64 alphabet, then its output's opening and closing text. +const ALPHABET_AT: usize = 0x8000; + +/// An exporter (manifest `manifest`) whose file is exactly what it is given (`echo`), so a test +/// reads back what the host hands a plug-in: it returns `{"dataBase64": "…"}`, encoding the bytes +/// in base64 itself, three bytes to four characters, the last group padded with `=`. +pub fn echo_exporter(manifest: &str, echo: Echo) -> String { + let (src, len) = match echo { + Echo::Input => ("$in", "$il"), + Echo::Params => ("$pp", "$pl"), + }; + let (open, close) = (r#"{"dataBase64":""#, r#""}"#); + let (open_at, close_at) = (ALPHABET_AT + 64, ALPHABET_AT + 96); + // One character of the alphabet: the six bits of `$b` from `shift` up. + let char_at = |shift: u32| { + format!("(i32.load8_u (i32.add (i32.const {ALPHABET_AT}) (i32.and (i32.shr_u (local.get $b) (i32.const {shift})) (i32.const 63))))") + }; + let byte = |k: u32| format!("(i32.load8_u (i32.add (local.get {src}) (i32.add (local.get $i) (i32.const {k}))))"); + let run = format!( + r#"(local $o i32) (local $n i32) (local $w i32) (local $i i32) (local $b i32) (local $rest i32) + (local.set $n (i32.add (i32.const {frame}) (i32.mul (i32.const 4) (i32.div_u (i32.add (local.get {len}) (i32.const 2)) (i32.const 3))))) + (local.set $o (memory.grow (i32.add (i32.shr_u (local.get $n) (i32.const 16)) (i32.const 1)))) + (if (i32.eq (local.get $o) (i32.const -1)) (then (return (i64.const -1)))) + (local.set $o (i32.mul (local.get $o) (i32.const 65536))) + (memory.copy (local.get $o) (i32.const {open_at}) (i32.const {open_len})) + (local.set $w (i32.add (local.get $o) (i32.const {open_len}))) + (block $done (loop $triple + (br_if $done (i32.gt_u (i32.add (local.get $i) (i32.const 3)) (local.get {len}))) + (local.set $b (i32.or (i32.or (i32.shl {b0} (i32.const 16)) (i32.shl {b1} (i32.const 8))) {b2})) + (i32.store8 (local.get $w) {c18}) (i32.store8 offset=1 (local.get $w) {c12}) + (i32.store8 offset=2 (local.get $w) {c6}) (i32.store8 offset=3 (local.get $w) {c0}) + (local.set $w (i32.add (local.get $w) (i32.const 4))) + (local.set $i (i32.add (local.get $i) (i32.const 3))) + (br $triple))) + (local.set $rest (i32.sub (local.get {len}) (local.get $i))) + (if (i32.ne (local.get $rest) (i32.const 0)) (then + (local.set $b (i32.shl {b0} (i32.const 16))) + (if (i32.eq (local.get $rest) (i32.const 2)) (then (local.set $b (i32.or (local.get $b) (i32.shl {b1} (i32.const 8)))))) + (i32.store8 (local.get $w) {c18}) (i32.store8 offset=1 (local.get $w) {c12}) + (i32.store8 offset=2 (local.get $w) (if (result i32) (i32.eq (local.get $rest) (i32.const 2)) (then {c6}) (else (i32.const 61)))) + (i32.store8 offset=3 (local.get $w) (i32.const 61)) + (local.set $w (i32.add (local.get $w) (i32.const 4))))) + (memory.copy (local.get $w) (i32.const {close_at}) (i32.const {close_len})) + (i64.or (i64.shl (i64.extend_i32_u (local.get $n)) (i64.const 32)) (i64.extend_i32_u (local.get $o)))"#, + frame = open.len() + close.len(), + open_len = open.len(), + close_len = close.len(), + b0 = byte(0), + b1 = byte(1), + b2 = byte(2), + c18 = char_at(18), + c12 = char_at(12), + c6 = char_at(6), + c0 = char_at(0), + ); + let extra = format!( + r#"(data (i32.const {ALPHABET_AT}) "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/") + (data (i32.const {open_at}) "{}") + (data (i32.const {close_at}) "{}")"#, + string(open), + string(close) + ); + module(manifest, &run, &extra, 1) +} diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index 337254b684..5ddd8efb32 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -164,6 +164,67 @@ fn wall_clock_budget_stops_runaway_plugins() { assert!(t < Duration::from_secs(3), "{t:?}"); } +#[test] +fn cancelling_stops_a_run_between_two_slices_of_its_budget() { + let spin = ok_module("(loop $l (br $l)) (i64.const 0)"); + let p = Plugin::load(&spin, Limits { fuel_base: u64::MAX / 4, ..Limits::default() }).unwrap(); + let token = vectorcraft_doc::cancel::CancelToken::new(); + token.cancel(); + let t = Instant::now(); + let r = vectorcraft_doc::cancel::scope(&token, None, || p.run(INPUT.as_bytes(), b"{}")); + assert_eq!(r, Err(Error::Cancelled)); + assert!(t.elapsed() < Duration::from_secs(3), "{:?}", t.elapsed()); + // Outside a cancelled scope the same module still runs to its budget. + let (e, _) = run_err(&spin, Limits { fuel_base: 1_000_000, ..Limits::default() }); + assert_eq!(e, Error::Limit("instruction budget".into())); +} + +#[test] +fn an_exporter_returns_its_file_with_an_export_s_budget() { + use vectorcraft_plugins::export::{self, Target}; + let target = Target { extension: "tst", name: "Poster" }; + let manifest = tpl::exporter("test.exporter", r#"["tst"]"#, r#"{"level":{"type":"int","min":1,"max":3,"default":2}}"#); + let p = Plugin::load(&build(&tpl::returning(&manifest, r#"{"dataBase64":"SGk=","warnings":["note"]}"#)), Limits::default()).unwrap(); + assert_eq!((p.manifest().kind, p.manifest().extensions.clone()), (Kind::Exporter, vec!["tst".to_string()])); + let out = export::run(&p, br#"{"format":"vectorcraft"}"#, &json!({"level": 9}), target).unwrap(); + assert_eq!((out.data_base64.as_str(), out.warnings), ("SGk=", vec!["note".to_string()])); + let limits = export::limits(&p); + assert_eq!((limits.fuel_base, limits.wall_time_ms), (export::FUEL, export::WALL_TIME_MS)); + // Its parameters are checked, and a filter is not an exporter. + assert!(matches!(export::run(&p, b"{}", &json!({"level": "high"}), target), Err(Error::Params(_)))); + let filter = Plugin::load(&ok_module("(i64.const 0)"), Limits::default()).unwrap(); + assert!(matches!(export::run(&filter, b"{}", &Value::Null, target), Err(Error::Params(_)))); +} + +/// The echo exporter the engine and UI tests read back what they hand a plug-in with: its file is +/// its input, or its parameters, byte for byte, whatever their length modulo three. +#[test] +fn the_echo_exporter_writes_what_it_is_given() { + use vectorcraft_plugins::export::{self, Target}; + let manifest = tpl::exporter("test.echo", r#"["txt"]"#, "{}"); + let input = Plugin::load(&build(&tpl::echo_exporter(&manifest, tpl::Echo::Input)), Limits::default()).unwrap(); + let params = Plugin::load(&build(&tpl::echo_exporter(&manifest, tpl::Echo::Params)), Limits::default()).unwrap(); + let target = Target { extension: "txt", name: "a" }; + let decoded = |out: export::Exported| String::from_utf8(base64_decode(&out.data_base64)).unwrap(); + for doc in ["{}", r#"{"a":1}"#, r#"{"ab":12}"#, r#"{"format":"vectorcraft","é":"\u0000"}"#] { + assert_eq!(decoded(export::run(&input, doc.as_bytes(), &Value::Null, target).unwrap()), doc); + } + let sent: Value = serde_json::from_str(&decoded(export::run(¶ms, b"{}", &Value::Null, target).unwrap())).unwrap(); + assert_eq!(sent, json!({"_context": {"mode": "export", "extension": "txt", "name": "a"}})); +} + +/// Standard base64 (RFC 4648, padded), decoded here so the test needs no other crate. +fn base64_decode(s: &str) -> Vec { + const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let sextets: Vec = s.bytes().filter(|b| *b != b'=').map(|b| ALPHABET.iter().position(|a| *a == b).unwrap() as u32).collect(); + let mut out = Vec::new(); + for group in sextets.chunks(4) { + let bits = group.iter().enumerate().fold(0u32, |acc, (i, v)| acc | v << (18 - 6 * i)); + out.extend(bits.to_be_bytes()[1..].iter().take(group.len() - 1)); + } + out +} + #[test] fn memory_cap_limits_input_and_growth() { let echo = build(&tpl::module(MANIFEST, tpl::ECHO, "", 1)); diff --git a/crates/render/src/encode/jpeg.rs b/crates/render/src/encode/jpeg.rs index c6f74cb5cc..596399c3e7 100644 --- a/crates/render/src/encode/jpeg.rs +++ b/crates/render/src/encode/jpeg.rs @@ -155,9 +155,68 @@ pub fn encode(px: &[u8], width: u32, height: u32, quality: u8, ppi: Option, ColorModel::Gray => ColorType::Luma, }; enc.encode(px, w, h, ty).map_err(fail)?; + // JFIF describes one- and three-component images (greyscale and YCbCr), so its APP0 segment + // must not head a four-component CMYK frame: the file then says two different things about + // its colours, and a strict reader rejects it rather than guessing. Adobe's own CMYK JPEGs + // carry the APP14 marker the encoder already writes, and no JFIF (#3084). + if o.color_model == ColorModel::Cmyk { + unlabel_jfif(&mut buf, ppi); + } Ok(buf) } +/// Replace the leading APP0/JFIF segment, which the encoder always writes, with an EXIF segment +/// carrying the same resolution (TIFF `XResolution`, `YResolution` and `ResolutionUnit`, which is +/// where a reader looks when there is no JFIF). Without a resolution the segment is simply +/// dropped. +fn unlabel_jfif(buf: &mut Vec, ppi: Option) { + // SOI, then APP0 with its two length bytes and the tag it is identified by. + let Some(head) = buf.get(..13) else { return }; + if head[..4] != [0xFF, 0xD8, 0xFF, 0xE0] || &head[6..11] != b"JFIF\0" { + return; + } + let len = usize::from(u16::from_be_bytes([head[4], head[5]])); + if 4 + len > buf.len() { + return; + } + let exif = ppi.filter(|p| p.is_finite() && *p >= 1.0).map(|p| exif_resolution(p.round() as u32)).unwrap_or_default(); + buf.splice(2..4 + len, exif); +} + +/// An APP1 EXIF segment holding `dpi` as IFD0's resolution: big-endian TIFF, three entries, each +/// rational pointing past the directory. +fn exif_resolution(dpi: u32) -> Vec { + let mut tiff = Vec::new(); + tiff.extend_from_slice(b"MM\0*"); // big-endian, TIFF magic + tiff.extend_from_slice(&8u32.to_be_bytes()); // IFD0 right after the header + tiff.extend_from_slice(&3u16.to_be_bytes()); // three entries + // Entry: tag, type (5 = rational, 3 = short), count, then the value or its offset. + let entry = |tag: u16, ty: u16, value: [u8; 4]| { + let mut e = Vec::with_capacity(12); + e.extend_from_slice(&tag.to_be_bytes()); + e.extend_from_slice(&ty.to_be_bytes()); + e.extend_from_slice(&1u32.to_be_bytes()); + e.extend_from_slice(&value); + e + }; + // The two rationals sit after the directory: header 8 + count 2 + 3 entries + next-IFD 4. + let after = 8 + 2 + 3 * 12 + 4; + tiff.extend(entry(282, 5, (after as u32).to_be_bytes())); // XResolution + tiff.extend(entry(283, 5, (after as u32 + 8).to_be_bytes())); // YResolution + tiff.extend(entry(296, 3, [0, 2, 0, 0])); // ResolutionUnit: inches + tiff.extend_from_slice(&0u32.to_be_bytes()); // no next IFD + for _ in 0..2 { + tiff.extend_from_slice(&dpi.to_be_bytes()); + tiff.extend_from_slice(&1u32.to_be_bytes()); + } + let mut seg = vec![0xFF, 0xE1]; + let body_len = 6 + tiff.len() + 2; + seg.extend_from_slice(&u16::try_from(body_len).unwrap_or(u16::MAX).to_be_bytes()); + seg.extend_from_slice(b"Exif\0\0"); + seg.extend_from_slice(&tiff); + seg +} + /// `img` flattened on white as RGB, or as grey with each colour's lightness. pub(crate) fn screen_pixels(img: &Rendered, gray: bool) -> Vec { let px = img.to_straight(); diff --git a/crates/render/src/encode/tests_jpeg.rs b/crates/render/src/encode/tests_jpeg.rs index 32366ed5a4..2bba70330e 100644 --- a/crates/render/src/encode/tests_jpeg.rs +++ b/crates/render/src/encode/tests_jpeg.rs @@ -48,6 +48,44 @@ fn noise(w: u32, h: u32, channels: usize) -> Vec { .collect() } +/// JFIF describes one- and three-component images, so its APP0 segment must not head a CMYK +/// frame: the file would say two different things about its colours and a strict reader rejects +/// it. A CMYK JPEG carries the Adobe APP14 marker instead, as Adobe's own do (#3084). +#[test] +fn a_cmyk_jpeg_is_not_labelled_jfif() { + let px = noise(16, 16, 4); + let o = JpegOptions { color_model: ColorModel::Cmyk, ..Default::default() }; + let file = jpeg::encode(&px, 16, 16, 90, Some(300.0), &o).unwrap(); + let markers: Vec = segments(&file).into_iter().map(|(m, _)| m).collect(); + assert_eq!(frame(&file).1, 4, "four components"); + assert!(!markers.contains(&0xE0), "no APP0/JFIF: {markers:02x?}"); + assert!(markers.contains(&0xEE), "the Adobe APP14 marker names the colours: {markers:02x?}"); + assert!(icc(&file).is_some(), "the CMYK profile is still embedded"); + assert_eq!(&file[..2], &[0xFF, 0xD8], "the file still starts at SOI"); + // The resolution JFIF carried moves to EXIF, where a reader looks when there is no JFIF. + let exif = segments(&file).into_iter().find(|(m, _)| *m == 0xE1).expect("APP1/EXIF").1; + assert!(exif.starts_with(b"Exif\0\0"), "{:02x?}", &exif[..8.min(exif.len())]); + // Big-endian TIFF with XResolution (282), YResolution (283) and ResolutionUnit (296). + assert_eq!(&exif[6..10], b"MM\0*"); + // "Exif\0\0" then the TIFF header (8 bytes) and the entry count (2), so entries start at 16. + let tags: Vec = (0..3).map(|i| u16::from_be_bytes([exif[16 + i * 12], exif[17 + i * 12]])).collect(); + assert_eq!(tags, [282, 283, 296], "{tags:?}"); + // No resolution asked for: nothing stands in for the dropped segment. + let plain = jpeg::encode(&px, 16, 16, 90, None, &o).unwrap(); + let markers: Vec = segments(&plain).into_iter().map(|(m, _)| m).collect(); + assert!(!markers.contains(&0xE0) && !markers.contains(&0xE1), "{markers:02x?}"); + + // Three- and one-component files keep JFIF, which is what it is for, and their resolution. + for (model, channels) in [(ColorModel::Rgb, 3), (ColorModel::Gray, 1)] { + let px = noise(16, 16, channels); + let o = JpegOptions { color_model: model, ..Default::default() }; + let file = jpeg::encode(&px, 16, 16, 90, Some(300.0), &o).unwrap(); + let markers: Vec = segments(&file).into_iter().map(|(m, _)| m).collect(); + assert!(markers.contains(&0xE0), "{model:?} keeps JFIF: {markers:02x?}"); + assert_eq!(frame(&file).1, channels as u8); + } +} + #[test] fn size_falls_with_quality() { let px = noise(64, 48, 3); @@ -85,9 +123,18 @@ fn colour_models_write_their_components_and_profiles() { assert_eq!(frame(&file).1, comps, "{model:?}"); let p = IccProfile::from_bytes(None, &icc(&file).expect("APP2 ICC")).unwrap(); assert_eq!(p.kind, kind, "{model:?}"); - let app0 = segments(&file).into_iter().find(|(m, _)| *m == 0xE0).unwrap().1; - assert_eq!(&app0[..5], b"JFIF\0"); - assert_eq!(app0[7..12], [1, 0, 150, 0, 150], "dots per inch"); + // JFIF describes one- and three-component images, so a CMYK file says its resolution in + // EXIF instead (see `a_cmyk_jpeg_is_not_labelled_jfif`). + if model == ColorModel::Cmyk { + let exif = segments(&file).into_iter().find(|(m, _)| *m == 0xE1).expect("APP1/EXIF").1; + assert!(exif.starts_with(b"Exif\0\0")); + // "Exif\0\0" (6) + TIFF header (8) + count (2) + three entries (36) + next IFD (4). + assert_eq!(&exif[56..64], &[0, 0, 0, 150, 0, 0, 0, 1], "150 dots per inch, as a rational"); + } else { + let app0 = segments(&file).into_iter().find(|(m, _)| *m == 0xE0).unwrap().1; + assert_eq!(&app0[..5], b"JFIF\0"); + assert_eq!(app0[7..12], [1, 0, 150, 0, 150], "dots per inch"); + } let none = jpeg::encode(&noise(16, 8, model.channels()), 16, 8, 90, None, &JpegOptions { embed_icc: false, ..o }).unwrap(); assert!(icc(&none).is_none()); } diff --git a/crates/render/src/fx.rs b/crates/render/src/fx.rs index 0d0adf794e..cc95cb9f61 100644 --- a/crates/render/src/fx.rs +++ b/crates/render/src/fx.rs @@ -79,9 +79,10 @@ pub(crate) fn has_fx(n: &Node) -> bool { /// Does `n` carry visible object-level effects that only apply through its art (type, images, /// symbol instances, live objects; Crop Marks and colour adjustments on anything), is it type with -/// a geometry effect on a fill or stroke of its own ([`effects::has_item_geometry`]), is it a path -/// whose Transform effect copies it with a gradient ([`effects::has_gradient_copies`]), or is it a -/// group or layer with an appearance of its own (see [`Renderer::draw_object_fx`])? +/// a geometry effect on a fill or stroke of its own or an image with a fill or stroke of its own +/// that paints a shape ([`effects::has_item_geometry`]), is it a path whose Transform effect copies +/// it with a gradient ([`effects::has_gradient_copies`]), 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 { (effects::needs_outline(n) && (visible(&n.appearance.effects) || n.projection().is_some())) || effects::has_item_geometry(n) @@ -108,6 +109,23 @@ fn evaluates_live(n: &Node) -> bool { is_live(n) || (is_container(n) && to_members && !effects::has_pathfinder(n) && subtree_has_live(n)) } +/// Can the art [`Renderer::fx_art`] makes for `n` change while `n` stays the same, other than +/// through live objects it evaluates? It can when `n` holds type (laid out in the fonts installed), +/// a symbol instance (made from its symbol's art), or an object with a 3D effect or a color +/// adjustment (shaded or recolored through the color settings), in it or in the opacity masks of +/// the objects in it. +fn reads_outside(n: &Node) -> bool { + let mut reads = false; + n.walk(&mut |c| { + reads |= matches!(c.kind, NodeKind::Text(_) | NodeKind::SymbolInstance { .. }) + || effects::has_revolve(c) + || effects::has_solid(c) + || effects::has_adjustment(c) + || c.extras().mask.as_ref().is_some_and(|m| reads_outside(&m.art)) + }); + reads +} + /// What [`Renderer::raster_fx`] paints effects around. struct Content<'a> { /// The object the effects belong to (cached shadows are checked against it). @@ -324,9 +342,9 @@ fn shape_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { r } // As [`cull_bounds_in`] measures them, without the object's own raster effects: the - // reshaped art (type's outlines measured one by one with the effects of its own fills and - // strokes), grown by how far the effects in a symbol's art and a live object's content - // paint past it. + // reshaped art (type's outlines, and an image and the paths of its own fills and strokes, + // measured one by one with the effects of those fills and strokes), grown by how far the + // effects in a symbol's art and a live object's content paint past it. _ if has_object_fx(n) => { let symbol = match &n.kind { NodeKind::SymbolInstance { symbol, .. } => symbols.document().symbols.iter().find(|s| s.name == *symbol).map(|s| s.art.clone()), @@ -334,7 +352,7 @@ fn shape_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { }; let reshaped = effects::reshape(n, symbol.as_deref()); let b = match &reshaped { - Some(r) if matches!(n.kind, NodeKind::Text(_)) => { + Some(r) if matches!(n.kind, NodeKind::Text(_)) || (matches!(n.kind, NodeKind::Image(_)) && !r.clips()) => { r.children().into_iter().flatten().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, painted_reach(symbols, c))) } Some(r) => r.visual_bounds_with(symbols), @@ -427,8 +445,9 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool) -> Optio } _ if has_fx(n) => visual_bounds(symbols, n), // The reshaped art (a symbol instance's reshaped art is made from its symbol's art; type's - // outlines measured one by one with the geometry effects of its own fills and strokes), - // grown by how far the effects in a symbol instance's art paint past that art. + // outlines, and an image and the paths of its own fills and strokes, measured one by one + // with the geometry effects of those fills and strokes), grown by how far the effects in a + // symbol instance's art paint past that art. _ if has_object_fx(n) => { let symbol = match &n.kind { NodeKind::SymbolInstance { symbol, .. } => symbols.document().symbols.iter().find(|s| s.name == *symbol).map(|s| s.art.clone()), @@ -436,7 +455,7 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool) -> Optio }; let reshaped = effects::reshape(n, symbol.as_deref()); let b = match &reshaped { - Some(r) if matches!(n.kind, NodeKind::Text(_)) => { + Some(r) if matches!(n.kind, NodeKind::Text(_)) || (matches!(n.kind, NodeKind::Image(_)) && !r.clips()) => { r.children().into_iter().flatten().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, inner(c))) } Some(r) => r.visual_bounds_with(symbols), @@ -620,6 +639,11 @@ pub(crate) struct PixelEntry { rel: (f64, f64), k: f64, image: std::sync::Arc, + /// For a raster of the content's whole reach at full size, `None`: it draws after a pan too. + /// For one cropped to the view, or made at a lower resolution, the view and the rect it was + /// made for: it draws only there, so dragging other art over the object keeps it (a wide blur, + /// or any blur zoomed in, reaches past the pixel budget). + view: Option, made: Made, /// What the content read when the raster was made, with the channels the effects ran on and, /// under De-Interlace, the raster resolution. @@ -648,6 +672,15 @@ fn linear_key(view: Affine) -> [u64; 4] { [c[0].to_bits(), c[1].to_bits(), c[2].to_bits(), c[3].to_bits()] } +/// A view's six coefficients (its pan included) and the device-pixel rect a frame draws in, as a +/// cache key: a raster cropped to that rect, or made at a lower resolution than the view's, draws +/// only in that view of that rect ([`PixelEntry::view`], [`ShadowEntry::view`]). +type ViewKey = ([u64; 6], [u64; 4]); + +fn view_key(view: Affine, screen: Rect) -> ViewKey { + (view.as_coeffs().map(f64::to_bits), [screen.x0, screen.y0, screen.x1, screen.y1].map(f64::to_bits)) +} + /// Most pixels a raster of [`Renderer::pixel_content`] or [`Renderer::with_filters`] holds while /// [`crate::RenderOptions::dragging`] (a 1000 × 1000 raster's), when the frame does not draw a raster /// kept from an earlier frame instead (#2558). @@ -732,6 +765,10 @@ pub(crate) struct ShadowEntry { image: std::sync::Arc, /// View pixels per raster pixel: more than 1 for a glow made coarser to fit the budget. scale: f64, + /// `None` for a raster of the whole silhouette's reach: it draws after a pan too. For one + /// cropped to the view, or made over such a raster, the view and the rect it was made for: it + /// draws only there ([`PixelEntry::view`]). + view: Option, made: Made, /// What the silhouette read when the raster was made. inputs: Inputs, @@ -749,6 +786,8 @@ struct Shadow { mode: vectorcraft_doc::color::BlendMode, /// Made before its object moved ([`ShadowEntry::moved`]). moved: bool, + /// Cropped to the view, or made over a raster that is ([`ShadowEntry::view`]). + cropped: bool, } impl ShadowEntry { @@ -1012,8 +1051,13 @@ impl Renderer { /// silhouette `paint` draws is rendered once into a small crop, blurred and tinted on the CPU, /// and reused while the object, the zoom/rotation and what the silhouette reads ([`Inputs`]) are /// unchanged (pans only move it), and while interacting after the object only moved - /// ([`Self::move_shadow`]). `None` when the effect isn't a shadow/glow or the raster would be - /// too large (caller falls back to [`Self::draw_shadow_filter`]). + /// ([`Self::move_shadow`]). A raster of the whole reach too large for the budget is cropped to + /// what can show in the `screen` (device pixels): the view, and around it the blur's spread and + /// `around` (document units: how far the shadows and glows stacked over this one look), made + /// coarser to fit the budget where the blur hides the coarser grid. Such a raster, and one + /// made over it (`over_cropped`), is reused only in the same view. `None` when the effect isn't + /// a shadow/glow or the raster would still be too large (caller falls back to + /// [`Self::draw_shadow_filter`]). /// While dragging on a multithreaded context, a raster that has to be made again counts as too /// large when it would hold more than [`DRAG_PIXEL_BUDGET`] pixels. #[allow(clippy::too_many_arguments)] @@ -1025,6 +1069,7 @@ impl Renderer { fx: &RasterFx, reach: Rect, owner: Option<&Arc>, + (screen, around, over_cropped): (Rect, f64, bool), paint: &mut dyn FnMut(&mut Self, &mut RenderContext, &Frame), ) -> Option { let (mode, opacity, dx, dy, blur, color, darkness) = match fx { @@ -1039,37 +1084,54 @@ impl Renderer { // What the silhouette reads: as the raster kept for `n` found it, else found now. let reads = self.shadows.get(&key).filter(|e| e.node.is(n)).map_or_else(|| Reads::of(n), |e| e.inputs.reads); let inputs = self.raster_inputs(f, n, reads); - let exact = |e: &ShadowEntry| e.linear == linear && e.node.is(n) && e.inputs == inputs && (interacting || !e.moved); + let in_view = view_key(f.view, screen); + let exact = |e: &ShadowEntry| { + e.linear == linear && e.node.is(n) && e.inputs == inputs && (interacting || !e.moved) && e.view.is_none_or(|v| v == in_view) + }; if interacting && !self.shadows.get(&key).is_some_and(exact) { self.move_shadow(f, n, key, fx, reach + Vec2::new(dx, dy), owner, &inputs, paint); } let hit = self.shadows.get_mut(&key).filter(|e| exact(e)); - let (image, x, y, scale, moved) = match hit { + let (image, x, y, scale, moved, cropped) = match hit { Some(e) => { e.stamp = stamp; self.stats.moved += usize::from(e.moved); let p = f.view * e.anchor; - (e.image.clone(), (p.x + e.rel.0).round(), (p.y + e.rel.1).round(), e.scale, e.moved) + (e.image.clone(), (p.x + e.rel.0).round(), (p.y + e.rel.1).round(), e.scale, e.moved, e.view.is_some()) } None => { // An Outer Glow's silhouette grows by a quarter of a pixel of the document's raster grid first. let grow = if matches!(fx, RasterFx::OuterGlow { .. }) { 18.0 / doc_raster_ppi(f.doc) } else { 0.0 }; let spread = (blur.max(0.0) * 1.5 + grow) / f.px + 2.0; let reach = reach + Vec2::new(dx, dy); - let r = f.view.transform_rect_bbox(reach).inflate(spread, spread); - let (x0, y0) = (r.x0.floor(), r.y0.floor()); - let (w, h) = (r.x1.ceil() - x0, r.y1.ceil() - y0); + let whole = f.view.transform_rect_bbox(reach).inflate(spread, spread); + // The raster's region and scale within `budget` pixels: `None` when over the limits. + let region = |r: Rect, coarser: bool, budget: f64| { + let (x0, y0) = (r.x0.floor(), r.y0.floor()); + let (w, h) = (r.x1.ceil() - x0, r.y1.ceil() - y0); + let scale = if coarser { (w * h / budget).sqrt().ceil().max(1.0) } else { 1.0 }; + if !scale.is_finite() || scale > 1.0 && blur / 2.0 / f.px / scale < 2.0 { + return None; + } + let (w, h) = ((w / scale).ceil(), (h / scale).ceil()); + ((1.0..=8192.0).contains(&w) && (1.0..=8192.0).contains(&h) && w * h <= budget).then_some((x0, y0, w, h, scale)) + }; // A glow too large for the budget is made coarser, where its blur hides the coarser grid: the filter // layer the caller falls back to can't make its silhouette solid. - let scale = if matches!(fx, RasterFx::OuterGlow { .. }) { (w * h / 4.0e6).sqrt().ceil().max(1.0) } else { 1.0 }; - if scale > 1.0 && blur / 2.0 / f.px / scale < 2.0 { - return None; - } - - let (w, h) = ((w / scale).ceil(), (h / scale).ceil()); - if !(1.0..=8192.0).contains(&w) || !(1.0..=8192.0).contains(&h) || w * h > 4.0e6 { - return None; - } + let full = region(whole, matches!(fx, RasterFx::OuterGlow { .. }), 4.0e6).filter(|_| !over_cropped); + // Else it is cropped to what can show in the view, within the budget of the filter + // layer it would otherwise be drawn through, and made coarser in the same way. + let ((x0, y0, w, h, scale), cropped) = match full { + Some(r) => (r, false), + None => { + let m = spread + around / f.px; + let r = whole.intersect(screen.inflate(m, m)); + if r.width() <= 0.0 || r.height() <= 0.0 { + return None; + } + (region(r, true, PIXEL_BUDGET)?, true) + } + }; // During a drag, a larger shadow on a multithreaded context is filtered within the // drag's budget (`with_filters`), and no raster is kept. if f.opts.dragging && f.mt && w * h > DRAG_PIXEL_BUDGET { @@ -1128,12 +1190,13 @@ impl Renderer { let p = f.view * anchor; let node = Drawn::of(n, owner); let rel = (x0 - p.x, y0 - p.y); - self.shadows.insert(key, ShadowEntry { node, linear, anchor, rel, image: image.clone(), scale, made, inputs, moved, stamp }); + let view = cropped.then_some(in_view); + self.shadows.insert(key, ShadowEntry { node, linear, anchor, rel, image: image.clone(), scale, view, made, inputs, moved, stamp }); self.trim_fx_rasters(FX_RASTER_BUDGET); - (image, x0, y0, scale, moved) + (image, x0, y0, scale, moved, cropped) } }; - Some(Shadow { image, at: Affine::translate((x, y)) * Affine::scale(scale), mode, moved }) + Some(Shadow { image, at: Affine::translate((x, y)) * Affine::scale(scale), mode, moved, cropped }) } /// Draw shadow raster `s` through `to`, from the view the raster was made for to the one `ctx` @@ -1224,6 +1287,7 @@ impl Renderer { (k.1, k.2) == (key.1, key.2) && e.stamp < stamp && e.linear == linear + && e.view.is_none() && e.node.id() == n.id && e.inputs == *inputs && e.made.fits(&[fx], size, None, None) @@ -1358,8 +1422,9 @@ impl Renderer { /// as their evaluated art (groups and layers: [`effects::evaluate_container`], keeping their /// knockout setting), recoloured by the colour adjustments in it ([`Self::adjusted_art`]); /// without the object's transparency and effects (a path keeps its geometry effects). Art that - /// is made from live objects it evaluated ([`evaluates_live`]) is kept only while the inputs of - /// their evaluation stay the same ([`Self::live_found`]). + /// is made from live objects it evaluated ([`evaluates_live`]), or from type, symbol art or + /// colors shaded through the color settings ([`reads_outside`]), is kept only while what it + /// reads from outside `a` stays the same ([`Self::live_found`]). fn fx_art(&mut self, doc: &vectorcraft_doc::Document, a: &Arc, cache: bool) -> Arc { let key = Arc::as_ptr(a) as usize; let mut kept = None; @@ -1372,7 +1437,7 @@ impl Renderer { Some(was) => kept = Some((art.clone(), was.0)), } } - let found = (kept.is_some() || (cache && evaluates_live(a))).then(|| self.live_found(doc, a)); + let found = (kept.is_some() || (cache && (evaluates_live(a) || reads_outside(a)))).then(|| self.live_found(doc, a)); if let Some((art, was)) = kept && found.as_ref().is_some_and(|f| f.0 == was) { @@ -1565,7 +1630,17 @@ impl Renderer { // through a filter layer from the content alone, and goes into the later silhouettes that way. let mut made: Vec<(&RasterFx, Option)> = vec![]; let mut stacked = reach; + let screen = Rect::new(0.0, 0.0, f64::from(ctx.width()), f64::from(ctx.height())); + // How far (document units) a shadow or glow looks from a pixel to the silhouette under it. + let looks = |fx: &RasterFx| match fx { + RasterFx::DropShadow { dx, dy, blur, .. } => blur.max(0.0) * 1.5 + dx.abs() + dy.abs(), + RasterFx::OuterGlow { blur, .. } => blur.max(0.0) * 1.5, + _ => 0.0, + }; for (i, fx) in rfx.iter().enumerate().filter(|(_, x)| x.is_below()) { + // A raster cropped to the view covers what the shadows and glows stacked over it read. + let around: f64 = rfx.iter().skip(i + 1).filter(|x| x.is_below()).map(looks).sum(); + let over_cropped = made.iter().any(|(_, s)| s.as_ref().is_some_and(|s| s.cropped)); let shadow = { let earlier = &made; let view = f.view; @@ -1582,7 +1657,8 @@ impl Renderer { } paint(r, c, fr); }; - content.cache.and_then(|slot| self.shadow_raster(f, content.node, slot + i, fx, stacked, owner.as_ref(), &mut art)) + let view = (screen, around, over_cropped); + content.cache.and_then(|slot| self.shadow_raster(f, content.node, slot + i, fx, stacked, owner.as_ref(), view, &mut art)) }; stacked = match fx { RasterFx::DropShadow { dx, dy, blur, .. } => stacked.union((stacked + Vec2::new(*dx, *dy)).inflate(blur * 1.5, blur * 1.5)), @@ -1652,7 +1728,10 @@ impl Renderer { /// every effect only looks nearby, and content still over either limit is rendered at a lower /// resolution. A whole raster at full resolution is cached while the object, the /// zoom and what the content reads ([`Inputs`]) stay the same (panning only moves it), and - /// while interacting after the content only moved ([`Self::move_pixel_content`]). + /// while interacting after the content only moved ([`Self::move_pixel_content`]). A cropped or + /// lower-resolution raster is cached while the object, the view (its pan included) and what the + /// content reads stay the same ([`PixelEntry::view`]); a lower-resolution one is kept resampled to + /// the view's pixels ([`Self::resampled`]). /// While dragging, content without such a raster to draw renders within [`DRAG_PIXEL_BUDGET`] /// pixels and is not cached. fn pixel_content( @@ -1702,9 +1781,11 @@ impl Renderer { let side = f64::from(crate::MAX_RASTER_SIDE); let k = (PIXEL_BUDGET / (rw * rh)).sqrt().min(side / rw).min(side / rh).min(1.0); let (w, h) = ((rw * k).ceil().clamp(1.0, side), (rh * k).ceil().clamp(1.0, side)); - // The cached raster, when the whole content was rendered at full size at this zoom. + // The cached raster: of the whole content at full size at this zoom, else of this view. let linear = linear_key(f.view); - let key = content.cache.filter(|_| fits && k >= 1.0).map(|slot| (content.node as *const Node as usize, slot, f.ink)); + let whole = fits && k >= 1.0; + let in_view = (!whole).then(|| view_key(f.view, screen)); + let key = content.cache.map(|slot| (content.node as *const Node as usize, slot, f.ink)); let stamp = self.stamp; let channels = match f.ink { Ink::Cmy => effects::pixel::Channels::CmyPlane, @@ -1722,8 +1803,11 @@ impl Renderer { self.raster_inputs(f, content.node, reads).with((std::mem::discriminant(&channels), interlaced.then_some(ppi.to_bits()))) }); let interacting = f.opts.interacting; - let exact = |e: &PixelEntry| e.linear == linear && e.node.is(content.node) && Some(&e.inputs) == inputs.as_ref() && (interacting || !e.moved); + let exact = |e: &PixelEntry| { + e.linear == linear && e.view == in_view && e.node.is(content.node) && Some(&e.inputs) == inputs.as_ref() && (interacting || !e.moved) + }; if interacting + && whole && let Some(key) = key && let Some(inputs) = &inputs && !self.pixel_fx.get(&key).is_some_and(exact) @@ -1797,9 +1881,10 @@ impl Renderer { let failed = crate::paint::decode_failures() - decoded; // Content drawn over moved rasters makes a moved raster. let moved = self.stats.moved > before; - // What the raster is made from, for its object once it moves (`move_pixel_content`). + // What the raster is made from, for its object once it moves (`move_pixel_content`): a + // cropped or coarser raster never moves. let made = key.map(|_| Made { - pixels: pm.data_as_u8_slice().to_vec(), + pixels: if whole { pm.data_as_u8_slice().to_vec() } else { Vec::new() }, fx: chain.iter().map(|fx| (*fx).clone()).collect(), size: content.reach.size(), channels: Some(channels), @@ -1845,6 +1930,14 @@ impl Renderer { } } let image = std::sync::Arc::new(pm); + // A raster kept for this view alone at a lower resolution than the view's is resampled to the + // view's pixels once: each frame that draws it then copies it pixel for pixel, where sampling + // it again across the whole view cost several times as much as a plain fill. + let view_raster = key.is_some() && in_view.is_some() && k < 1.0 && content.kept.is_none(); + let (image, x0, y0, k) = match view_raster.then(|| self.resampled(f, image.clone(), (x0, y0), k, screen)).flatten() { + Some((image, x, y)) => (image, x, y, 1.0), + None => (image, x0, y0, k), + }; // A cancelled export drew part of the content: that raster isn't kept for later frames. if !vectorcraft_doc::cancel::is_cancelled() && let Some(((key, made), inputs)) = key.zip(made).zip(inputs) @@ -1854,7 +1947,8 @@ impl Renderer { let rel = (x0 - p.x, y0 - p.y); let owner = content.owner.cloned().or_else(|| self.fx_owner.clone().filter(|o| std::ptr::eq(&**o, content.node))); let node = Drawn::of(content.node, owner.as_ref()); - self.pixel_fx.insert(key, PixelEntry { node, linear, anchor, rel, k, image: image.clone(), made, inputs, moved, failed, stamp }); + let entry = PixelEntry { node, linear, anchor, rel, k, image: image.clone(), view: in_view, made, inputs, moved, failed, stamp }; + self.pixel_fx.insert(key, entry); self.trim_fx_rasters(FX_RASTER_BUDGET); } // An image over the limits was drawn at a frame's resolution: its raster is kept. @@ -1868,6 +1962,33 @@ impl Renderer { } } + /// `image` as [`draw_scaled`] draws it with its top-left at (`x`, `y`) device pixels, `1 / k` + /// device pixels a pixel, resampled to the device pixels it covers of `screen`, with their + /// top-left. `None` when it covers none of them. + fn resampled( + &mut self, + f: &Frame, + image: std::sync::Arc, + (x, y): (f64, f64), + k: f64, + screen: Rect, + ) -> Option<(std::sync::Arc, f64, f64)> { + let covered = Rect::new(x, y, x + f64::from(image.width()) / k, y + f64::from(image.height()) / k).intersect(screen); + let (x0, y0) = (covered.x0.floor(), covered.y0.floor()); + let (w, h) = (covered.x1.ceil() - x0, covered.y1.ceil() - y0); + let side = f64::from(crate::MAX_RASTER_SIDE); + if !((1.0..=side).contains(&w) && (1.0..=side).contains(&h)) { + return None; + } + let (w, h) = (w as u16, h as u16); + let mut off = f.offscreen_context(w, h); + draw_scaled(&mut off, image, (x - x0, y - y0), k); + off.flush(); + let mut pm = vello_cpu::Pixmap::new(w, h); + off.render(&mut pm, &mut self.resources); + Some((std::sync::Arc::new(pm), x0, y0)) + } + /// While interacting, give `content` (cache key `key`) the filtered raster an earlier frame /// made at full size for its object (the same id, slot and ink, at this zoom and rotation, with /// the same `inputs`) when only the content's place changed after that frame: made by the same @@ -1898,6 +2019,7 @@ impl Renderer { && e.stamp < stamp && e.linear == linear && e.k >= 1.0 + && e.view.is_none() && e.node.id() == content.node.id && e.inputs == *inputs && e.made.fits(chain, content.reach.size(), Some(channels), outline.as_ref()) @@ -2372,6 +2494,45 @@ mod tests { assert!(r.render(&d, 400, 400, Affine::scale(2.0), &opts).pixels == first.pixels, "made again alike"); } + /// An Outer Glow whose whole reach is over the budget is made coarser over that whole reach and + /// kept for any pan: its grid starts at the reach's first whole device pixel, which a pan by whole + /// pixels moves with the art, so the raster drawn after the pan is the one a fresh renderer makes, + /// also for pans that aren't multiples of the raster's scale. A pan by a fraction of a pixel + /// places the raster at the nearest whole pixel, as a full-size raster kept whole is placed, and + /// here draws as a fresh renderer draws too. A 100 pt glow at 500% (scale 2) and a 2 pt glow + /// round the page at 800% (scale 3, near the narrowest blur made coarser). + #[test] + fn a_coarser_glow_kept_whole_draws_after_a_pan_as_made_again() { + let size = (640, 360); + for (rect, blur, zoom, center, scale) in [ + (Rect::new(200.0, 300.0, 400.0, 500.0), 100.0, 5.0, (440.0, 400.0), 2.0), + (Rect::new(0.0, 0.0, 595.0, 842.0), 2.0, 8.0, (595.0, 421.0), 3.0), + ] { + let mut d = Document::new(595.0, 842.0); + let layer = d.layers[0].id; + let mut n = + Node::path(d.alloc_id(), shapes::rectangle(rect), Appearance::basic(Paint::solid(Color::rgb(0.1, 0.3, 0.9)), Paint::None, 0.0)); + n.appearance.effects = vec![Effect { id: "stylize.outerGlow".into(), params: json!({"blur": blur}), visible: true }]; + d.insert(Some(layer), 0, n).unwrap(); + let base = Affine::translate((320.0, 180.0)) * Affine::scale(zoom) * Affine::translate((-center.0, -center.1)); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let mut r = Renderer::new(); + r.threads = 2; + r.render(&d, size.0, size.1, base, &opts); + let image = |r: &Renderer| r.shadows.values().map(|e| std::sync::Arc::as_ptr(&e.image)).collect::>(); + let kept = image(&r); + assert!(r.shadows.values().all(|e| e.scale == scale && e.view.is_none()), "blur {blur}: coarser, over the whole reach"); + for pan in [(37.0, -21.0), (1.0, 0.0), (-3.0, 5.0), (0.5, 0.0), (37.3, -21.6)] { + let xf = Affine::translate(pan) * base; + let panned = r.render(&d, size.0, size.1, xf, &opts); + assert_eq!(image(&r), kept, "blur {blur}, pan {pan:?}: the raster kept is drawn"); + let mut fresh = Renderer::new(); + fresh.threads = 2; + assert!(panned.pixels == fresh.render(&d, size.0, size.1, xf, &opts).pixels, "blur {blur}, pan {pan:?}"); + } + } + } + /// The multithreaded rasterizer draws the same pixels with any number of workers, so the /// automatic thread count can follow the machine. #[test] @@ -2854,8 +3015,9 @@ mod tests { /// While dragging (#2558), filtered content and a drop shadow that the frame does not draw from a /// raster of an earlier frame render within the drag's budget and keep no raster. At 6400% a - /// rectangle with Drop Shadow and Texturizer covers more than the raster budget, so no raster is - /// kept for either, and a 1600 × 1000 view near its corner needs more than the drag's budget. The + /// rectangle with Drop Shadow and Texturizer covers more than the raster budget, so the still + /// frame keeps rasters cropped to its view, which the moved rectangle can't take along, and a + /// 1600 × 1000 view near its corner needs more than the drag's budget. The /// frame after the drag, of the same document, is what a fresh renderer draws, as is a frame /// rendered while interacting without a drag (a dialog's preview). #[test] @@ -2885,7 +3047,7 @@ mod tests { let dragged = r.render(&d, 1600, 1000, view, &drag).pixels; assert_eq!(r.stats.previewed, 2, "the shadow and the filtered content"); assert_eq!(r.stats.moved, 2, "counted as moved: the frame after the drag renders them again"); - assert!(r.pixel_fx.is_empty() && r.shadows.is_empty(), "no raster kept"); + assert!(r.pixel_fx.is_empty() && r.shadows.values().all(|e| e.stamp < r.stamp), "no raster kept"); assert!(dragged != fresh, "at the drag's lower resolution"); let after = r.render(&d, 1600, 1000, view, &still).pixels; assert_eq!((r.stats.previewed, r.stats.moved), (0, 0)); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 0169a35930..442e156cb5 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -410,8 +410,9 @@ type ClipEntry = (Arc, Option>); /// A clipping path (kept alive) and what it paints: its fills and its strokes ([`Node::clip_paint`]). type ClipPaintEntry = (Arc, Option>, Option>); /// An object with effects (kept alive), the art drawn for it ([`Renderer::fx_art`]), and, when that -/// art can be made from evaluated live objects (`fx::evaluates_live`), the inputs of their -/// evaluation ([`live::Found`]). +/// art can be made from evaluated live objects (`fx::evaluates_live`) or from type, symbol art or +/// colors shaded through the color settings (`fx::reads_outside`), the inputs it was made with +/// ([`live::Found`]). type FxArtEntry = (Arc, Arc, Option); /// What symbol art placed by [`Renderer::placed_art`] is kept under: the art's address, the bits /// of the transform's coefficients, whether strokes scale with it, and the stain ([`stain_bits`]). @@ -2527,3 +2528,5 @@ mod tests_setup; mod tests_strokegradient; #[cfg(test)] mod tests_tileedge; +#[cfg(test)] +mod tests_viewraster; diff --git a/crates/render/src/live.rs b/crates/render/src/live.rs index 285aaab5f2..ad25aeb8a9 100644 --- a/crates/render/src/live.rs +++ b/crates/render/src/live.rs @@ -68,8 +68,8 @@ pub fn expand_live(n: &Node) -> Vec { crate::effects::expand_live(None, n) } -/// What the evaluation of `n` (a live node, or an object whose effect art can be made from -/// evaluated live objects, see [`Renderer::live_found`]) reads from the document, placed files, +/// What the evaluation of `n` (a live node, or an object whose effect art the renderer keeps with +/// its inputs, see [`Renderer::live_found`]) reads from the document, placed files, /// the fonts, the plug-ins and the color settings, hashed: the art of the symbols, the tilings of /// the patterns and the reads of the placed files it shows ([`hash_resources`]), the font /// generation ([`vectorcraft_text::FontDb::generation`]) when it shows type or a placed file, the @@ -343,7 +343,7 @@ fn spread_to_edges(px: &mut [vello_cpu::color::PremulRgba8], filled: Vec, impl Renderer { /// The [`resources_key`] of `n` in `doc`, with the frame's [`DocInputs`] ([`Found`]): `n` is a /// live node, or an object with effects whose art ([`Renderer::fx_art`]) can be made from - /// evaluated live objects. + /// evaluated live objects, type, symbol art or colors shaded through the color settings. pub(crate) fn live_found(&mut self, doc: &Document, n: &Node) -> Found { let inputs = self.doc_inputs(doc); let (key, reads) = resources_key(doc, inputs.cms, n); diff --git a/crates/render/src/tests_fontchange.rs b/crates/render/src/tests_fontchange.rs index 26af4830a5..9f7b543b7a 100644 --- a/crates/render/src/tests_fontchange.rs +++ b/crates/render/src/tests_fontchange.rs @@ -155,6 +155,60 @@ fn symbol_type_redraws_when_its_font_becomes_available() { assert_eq!(after, Renderer::new().render(&d, 300, 150, Affine::IDENTITY, &opts).pixels, "as a new renderer draws it"); } +/// Type that a geometry effect outlines redraws in a font that becomes available: the art drawn for +/// the effects of the type, of a group that holds it and of a symbol instance whose art holds it +/// is made again when the fonts change. +#[test] +fn type_with_geometry_effects_redraws_when_its_font_becomes_available() { + let _adding = adding_fonts(); + use vectorcraft_doc::Effect; + let moved = || Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 0.0}), visible: true }; + let cases = [ + ("Moving Serif 4", "the type with a Transform effect"), + ("Shadow Serif 5", "the type with a Transform effect and a drop shadow"), + ("Massed Serif 4", "the group with a Transform effect"), + ("Stamps Serif 4", "the symbol instance with a Transform effect"), + ("Darker Serif 4", "the type with a Transform effect in Multiply"), + ]; + for (i, (family, what)) in cases.into_iter().enumerate() { + let mut d = Document::new(300.0, 150.0); + let style = CharStyle { size: 50.0, font_family: family.into(), ..Default::default() }; + let at = if i == 3 { Point::new(-140.0, 20.0) } else { Point::new(10.0, 80.0) }; + let mut object = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(at, "Hamburg", style)))); + match i { + 0 => object.appearance.effects.push(moved()), + 1 => { + object.appearance.effects.push(moved()); + let params = serde_json::json!({"x": 4, "y": 4, "blur": 1, "opacity": 100}); + object.appearance.effects.push(Effect { id: "stylize.dropShadow".into(), params, visible: true }); + } + 2 => { + object = Node::group(d.alloc_id(), vec![Arc::new(object)]); + object.appearance.effects.push(moved()); + } + 3 => { + let art = Node::group(d.alloc_id(), vec![Arc::new(object)]); + d.symbols.push(vectorcraft_doc::Symbol { name: "Word".into(), art: Arc::new(art) }); + object = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Word".into(), xf: Affine::translate((150.0, 75.0)) }); + object.appearance.effects.push(moved()); + } + _ => { + object.appearance.effects.push(moved()); + object.blend = vectorcraft_color::BlendMode::Multiply; + } + } + let l = d.layers[0].id; + d.insert(Some(l), 0, object).unwrap(); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let mut r = Renderer::new(); + let before = r.render(&d, 300, 150, Affine::IDENTITY, &opts).pixels; + assert!(vectorcraft_text::FontDb::global().add_font(serif_as(family)) > 0); + let after = r.render(&d, 300, 150, Affine::IDENTITY, &opts).pixels; + assert_ne!(before, after, "{what}: drawn in the font that arrived"); + assert_eq!(after, Renderer::new().render(&d, 300, 150, Affine::IDENTITY, &opts).pixels, "{what}: as a new renderer draws it"); + } +} + /// Type that an envelope bends redraws in a font that becomes available, in the envelope and in /// the art of a symbol whose instance an envelope bends: the envelopes are evaluated again when the /// fonts change. diff --git a/crates/render/src/tests_objectfx.rs b/crates/render/src/tests_objectfx.rs index f4c72553f8..24d941d265 100644 --- a/crates/render/src/tests_objectfx.rs +++ b/crates/render/src/tests_objectfx.rs @@ -8,7 +8,7 @@ use serde_json::{Value, json}; use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint}; use vectorcraft_doc::pattern::{PatternDef, pattern_paint}; use vectorcraft_doc::text::{CharStyle, TextObject}; -use vectorcraft_doc::{Appearance, AppearanceItem, Effect, FillLayer, ImageBlob, ImageObject, Node, NodeKind, Symbol}; +use vectorcraft_doc::{Appearance, AppearanceItem, Effect, FillLayer, ImageBlob, ImageObject, Node, NodeKind, StrokeLayer, Symbol}; use vectorcraft_geom::{Point, shapes}; use super::*; @@ -679,6 +679,65 @@ fn a_rectangle_on_a_fill_below_type_with_outline_object_fits_the_glyphs() { assert_eq!(lum(img.pixel(x, glyphs.y1 as u32 + 12)), WHITE); } +/// [`image_doc`] with a black 4 pt stroke of its own that carries the effects `row`, below the +/// image when `below`. +fn stroked_image_doc(row: Vec, below: bool) -> Document { + let mut d = image_doc(vec![]); + let id = d.layers[0].children().unwrap()[0].id; + let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 4.0); + stroke.effects = row; + let ap = &mut d.node_mut(id).unwrap().appearance; + ap.items.push(AppearanceItem::Stroke(stroke)); + ap.set_contents_at(usize::from(below)); + d +} + +#[test] +fn an_images_stroke_draws_only_the_shape_convert_to_shape_or_outline_object_gives_it() { + // The image's frame runs from 20 to 50. Without an effect the stroke draws nothing. + for below in [false, true] { + let img = render(&stroked_image_doc(vec![], below)); + assert_eq!((lum(img.pixel(18, 35)), img.pixel(21, 35)), (WHITE, [255, 0, 0, 255])); + } + let rectangle = fx("convertToShape.rectangle", json!({"relative": true, "extraW": 0, "extraH": 0})); + let outline = fx("path.outlineObject", json!({})); + for effect in [rectangle, outline] { + // Below the image only the stroke's outer half shows, above it both halves. + let img = render(&stroked_image_doc(vec![effect.clone()], true)); + assert_eq!((lum(img.pixel(17, 35)), lum(img.pixel(18, 35)), img.pixel(21, 35)), (WHITE, 0, [255, 0, 0, 255]), "{}", effect.id); + let img = render(&stroked_image_doc(vec![effect.clone()], false)); + assert_eq!((lum(img.pixel(18, 35)), lum(img.pixel(21, 35)), img.pixel(23, 35)), (0, 0, [255, 0, 0, 255]), "{}", effect.id); + // An effect before it is left out. + let first = fx("path.offsetPath", json!({"offset": 10})); + let img = render(&stroked_image_doc(vec![first, effect.clone()], true)); + assert_eq!((lum(img.pixel(10, 35)), lum(img.pixel(18, 35))), (WHITE, 0), "{}", effect.id); + } + // An Offset Path of 2 pt after Outline Object moves the stroke 2 pt out. + let img = render(&stroked_image_doc(vec![fx("path.outlineObject", json!({})), fx("path.offsetPath", json!({"offset": 2}))], true)); + assert_eq!((lum(img.pixel(15, 35)), lum(img.pixel(16, 35)), lum(img.pixel(19, 35))), (WHITE, 0, 0)); +} + +#[test] +fn an_images_stroke_is_drawn_when_only_it_is_in_view() { + // The stroke runs 8 pt outside the frame, from 10 to 14; the view shows x 15 and less. + let row = vec![fx("path.outlineObject", json!({})), fx("path.offsetPath", json!({"offset": 8}))]; + let d = stroked_image_doc(row, true); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let img = Renderer::new().render(&d, 100, 100, Affine::translate((85.0, 0.0)), &opts); + assert_eq!((lum(img.pixel(96, 35)), lum(img.pixel(99, 35))), (0, WHITE)); +} + +#[test] +fn rasterize_on_an_image_takes_in_its_strokes_shape() { + // The stroke runs 8 pt outside the frame, from 10 to 14; Rasterize at 72 ppi keeps it. + let row = vec![fx("path.outlineObject", json!({})), fx("path.offsetPath", json!({"offset": 8}))]; + let mut d = stroked_image_doc(row, true); + let id = d.layers[0].children().unwrap()[0].id; + d.node_mut(id).unwrap().appearance.effects.push(fx("rasterize", json!({"useDocumentResolution": false, "resolution": 72}))); + let img = render(&d); + assert_eq!((lum(img.pixel(8, 35)), lum(img.pixel(12, 35)), img.pixel(35, 35)), (WHITE, 0, [255, 0, 0, 255])); +} + #[test] fn a_strokes_own_glow_paints_around_that_stroke_only() { let mut d = Document::new(100.0, 100.0); diff --git a/crates/render/src/tests_viewraster.rs b/crates/render/src/tests_viewraster.rs new file mode 100644 index 0000000000..37374ef2b9 --- /dev/null +++ b/crates/render/src/tests_viewraster.rs @@ -0,0 +1,161 @@ +//! Effect rasters cropped to the view, or made at a lower resolution, are kept while the view +//! stays as it is: dragging other art over an object whose effects reach far past the view (a wide +//! blur, or any blur zoomed in) draws its raster from the last frame. + +use serde_json::json; +use vectorcraft_doc::color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId}; +use vectorcraft_geom::{Affine, Rect, shapes}; + +use crate::{RenderOptions, Renderer}; + +/// An A4 page filled by a blue rectangle under `effects`, and a small orange square over it +/// (returned with the document): the square is the art a drag moves. +fn backdrop(effects: &[(&str, serde_json::Value)]) -> (Document, NodeId) { + let mut d = Document::new(595.0, 842.0); + let layer = d.layers[0].id; + let mut back = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(0.0, 0.0, 595.0, 842.0)), + Appearance::basic(Paint::solid(Color::rgb(0.1, 0.3, 0.9)), Paint::None, 0.0), + ); + back.appearance.effects = effects.iter().map(|(id, p)| Effect { id: (*id).into(), params: p.clone(), visible: true }).collect(); + d.insert(Some(layer), 0, back).unwrap(); + let id = d.alloc_id(); + let square = Node::path( + id, + shapes::rectangle(Rect::new(280.0, 400.0, 300.0, 420.0)), + Appearance::basic(Paint::solid(Color::rgb(0.9, 0.4, 0.1)), Paint::None, 0.0), + ); + d.insert(Some(layer), 1, square).unwrap(); + (d, id) +} + +/// A `w` × `h` view at `zoom`, centered on the page. +fn view(zoom: f64, (w, h): (u32, u32)) -> Affine { + Affine::translate((f64::from(w) / 2.0, f64::from(h) / 2.0)) * Affine::scale(zoom) * Affine::translate((-297.5, -421.0)) +} + +/// `base` with the square moved by `step` steps of a drag. +fn moved(base: &Document, id: NodeId, step: u32, zoom: f64) -> Document { + let mut d = base.clone(); + let by = (f64::from(step) * 3.0 / zoom, f64::from(step) * 2.0 / zoom); + d.node_mut(id).unwrap().transform(Affine::translate(by), false); + d +} + +/// A case's name, its effects (id and params) and its zoom. +type Case = (&'static str, Vec<(&'static str, serde_json::Value)>, f64); + +/// Every effect whose raster can be cropped to the view or made coarser, with a zoom at which it +/// is: wide blurs at the fit zoom, narrow ones zoomed in, a Photoshop-style filter, a shadow and a +/// glow. +fn cases() -> Vec { + vec![ + ("Gaussian Blur 500 pt", vec![("blur.gaussian", json!({"radius": 500}))], 1.6), + ("Gaussian Blur 100 pt", vec![("blur.gaussian", json!({"radius": 100}))], 1.6), + ("Gaussian Blur 20 pt", vec![("blur.gaussian", json!({"radius": 20}))], 4.0), + ("Gaussian Blur 8 pt", vec![("blur.gaussian", json!({"radius": 8}))], 16.0), + ("Feather 20 pt", vec![("stylize.feather", json!({"radius": 20}))], 4.0), + ("Craquelure", vec![("texture.craquelure", json!({}))], 4.0), + ("Drop Shadow blur 100 pt", vec![("stylize.dropShadow", json!({"blur": 100, "x": 20, "y": 20}))], 1.6), + ("Drop Shadow blur 10 pt", vec![("stylize.dropShadow", json!({"blur": 10, "x": 5, "y": 5}))], 8.0), + ("Outer Glow blur 100 pt", vec![("stylize.outerGlow", json!({"blur": 100}))], 1.6), + ] +} + +/// A drag of the square over the backdrop draws the backdrop's effects from the rasters of the +/// frame before the drag, at full resolution: no frame of the drag previews them at a drag's lower +/// resolution, and each draws as a fresh renderer draws its still frame. +#[test] +fn a_drag_over_art_with_effects_past_the_view_draws_their_rasters_kept() { + let size = (640, 360); + for (name, effects, zoom) in cases() { + let (base, id) = backdrop(&effects); + let xf = view(zoom, size); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let live = RenderOptions { interacting: true, dragging: true, ..opts.clone() }; + let mut r = Renderer::new(); + r.threads = 2; + r.render(&base, size.0, size.1, xf, &opts); + for step in 1..4 { + let d = moved(&base, id, step, zoom); + let drag = r.render(&d, size.0, size.1, xf, &live); + assert_eq!(r.stats.previewed, 0, "{name}: drag frame {step} drew the backdrop's effects from the rasters kept"); + let mut fresh = Renderer::new(); + fresh.threads = 2; + let still = fresh.render(&d, size.0, size.1, xf, &opts); + assert!(drag.pixels == still.pixels, "{name}: drag frame {step} draws as a still frame"); + } + } +} + +/// A pan by whole pixels or a zoom makes the rasters cropped to the view again: the frame after it draws as a +/// fresh renderer draws it. +#[test] +fn rasters_cropped_to_the_view_follow_a_pan_and_a_zoom() { + let size = (640, 360); + for (name, effects, zoom) in cases() { + let (d, _) = backdrop(&effects); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let mut r = Renderer::new(); + r.threads = 2; + r.render(&d, size.0, size.1, view(zoom, size), &opts); + for xf in [Affine::translate((37.0, -21.0)) * view(zoom, size), view(zoom * 1.25, size)] { + let image = r.render(&d, size.0, size.1, xf, &opts); + let mut fresh = Renderer::new(); + fresh.threads = 2; + assert!(image.pixels == fresh.render(&d, size.0, size.1, xf, &opts).pixels, "{name}"); + } + } +} + +/// Time a drag of the square over each backdrop in a 2560 × 1440 view: the first frame renders as +/// before a drag, the next eight as a drag's frames (`interacting` and `dragging`, as the canvas +/// renders them), then the frame after the drag. The hashes of that frame and of a fresh renderer's +/// frame compare builds. +/// Run with `cargo test --release -p vectorcraft-render backdrop_drag_perf -- --ignored --nocapture`. +#[test] +#[ignore = "manual timing probe; wall-clock performance depends on machine load"] +fn backdrop_drag_perf() { + let hash = |px: &[u8]| { + use std::hash::{Hash, Hasher}; + let mut h = std::hash::DefaultHasher::new(); + px.hash(&mut h); + h.finish() + }; + let size = (2560, 1440); + for (name, effects, zoom) in cases() { + let (base, id) = backdrop(&effects); + let xf = view(zoom, size); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let live = RenderOptions { interacting: true, dragging: true, ..opts.clone() }; + let mut r = Renderer::new(); + r.threads = crate::default_threads(); + let start = std::time::Instant::now(); + std::hint::black_box(r.render(&base, size.0, size.1, xf, &opts)); + let first = start.elapsed().as_secs_f64() * 1000.0; + let (mut ms, mut previewed, mut doc) = (vec![], 0, base.clone()); + for step in 1..9 { + doc = moved(&base, id, step, zoom); + let start = std::time::Instant::now(); + std::hint::black_box(r.render(&doc, size.0, size.1, xf, &live)); + ms.push(start.elapsed().as_secs_f64() * 1000.0); + previewed += r.stats.previewed; + } + let start = std::time::Instant::now(); + let still = r.render(&doc, size.0, size.1, xf, &opts); + let after = start.elapsed().as_secs_f64() * 1000.0; + let fresh = Renderer::new().render(&doc, size.0, size.1, xf, &opts); + ms.sort_by(f64::total_cmp); + println!( + "{name} at {:.0}%: first frame {first:.1} ms; drag frames median {:.1} ms (min {:.1}, max {:.1}), {previewed} previewed; the frame after the drag {after:.1} ms; hashes {:016x} {:016x}", + zoom * 100.0, + (ms[3] + ms[4]) * 0.5, + ms[0], + ms[7], + hash(&still.pixels), + hash(&fresh.pixels) + ); + } +} diff --git a/crates/svg/src/css.rs b/crates/svg/src/css.rs index c0876400d2..e9b4ef67a1 100644 --- a/crates/svg/src/css.rs +++ b/crates/svg/src/css.rs @@ -85,6 +85,22 @@ pub(crate) fn font_stretch(st: &CharStyle) -> Option { st.font_axes.get("wdth").copied().filter(|w| w.is_finite() && *w > 0.0) } +/// The generic family to list after `family`, with its leading comma, so a viewer without the font draws +/// the kind of face it was (the font's class, as the font menu's filters know it) rather than its default +/// serif. Nothing when `family` is a generic family itself. +fn generic_fallback(family: &str) -> &'static str { + const GENERIC: [&str; 5] = ["serif", "sans-serif", "monospace", "cursive", "fantasy"]; + if GENERIC.iter().any(|g| family.trim().eq_ignore_ascii_case(g)) { + return ""; + } + match vectorcraft_text::FontDb::global().family_traits(family).class { + vectorcraft_text::FontClass::Serif => ", serif", + vectorcraft_text::FontClass::Monospaced => ", monospace", + vectorcraft_text::FontClass::Script => ", cursive", + _ => ", sans-serif", + } +} + /// The font of character style `st`: family, size (the vertical scale; writers stretch the /// horizontal one), weight and style, and its Variable Font settings, lengths written by `len`. /// The weight is the style's number (600 for Semibold, 300 for Light) or the `wght` setting, @@ -98,7 +114,7 @@ pub(crate) fn font_props(st: &CharStyle, len: &dyn Fn(f64) -> String) -> Props { } else { st.font_family.clone() }; - p.push(("font-family", fam)); + p.push(("font-family", format!("{fam}{}", generic_fallback(&st.font_family)))); p.push(("font-size", len(st.size * st.v_scale / 100.0))); let (weight, italic) = font_descriptor(st); match weight { diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index 661b6381e8..1f9f79ac0c 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -135,12 +135,12 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: } if !doc.title.is_empty() { out.push_str(&w.indent(1)); - out.push_str(&format!("{}{nl}", xml_escape(&doc.title))); + out.push_str(&format!("{}{nl}", xml_text(&doc.title))); } // File Info's description. if !doc.metadata.description.trim().is_empty() { out.push_str(&w.indent(1)); - out.push_str(&format!("{}{nl}", xml_escape(&doc.metadata.description))); + out.push_str(&format!("{}{nl}", xml_text(&doc.metadata.description))); } // Window › SVG Interactivity › Link JavaScript Files. for file in &doc.svg_scripts { diff --git a/crates/svg/tests/css_rules.rs b/crates/svg/tests/css_rules.rs index 036f1bd914..79eebd3509 100644 --- a/crates/svg/tests/css_rules.rs +++ b/crates/svg/tests/css_rules.rs @@ -163,7 +163,7 @@ fn type_gives_font_properties() { let id = add(&mut d, n); let r = one(&d, id, &CssOptions::default()); assert_eq!(r.selector, ".type"); - assert_eq!(prop(&r, "font-family"), Some("'Source Sans 3'")); + assert_eq!(prop(&r, "font-family"), Some("'Source Sans 3', sans-serif")); assert_eq!(prop(&r, "font-size"), Some("18px")); assert_eq!(prop(&r, "font-weight"), Some("bold")); assert_eq!(prop(&r, "font-style"), Some("italic")); @@ -281,9 +281,26 @@ fn groups_stand_for_their_objects_and_hidden_ones_are_left_out() { assert_eq!(sheet.text(), sheet.rules[0].text()); } +#[test] +fn font_family_ends_with_a_generic_family_for_viewers_without_the_font() { + let family = |name: &str| { + let mut d = doc(); + let st = CharStyle { font_family: name.into(), size: 18.0, ..CharStyle::default() }; + let n = text(&mut d, "Hello", st); + let id = add(&mut d, n); + prop(&one(&d, id, &CssOptions::default()), "font-family").map(str::to_string) + }; + // Source Sans 3 is a sans face; an unknown family gets the same default; a generic family stands alone. + assert_eq!(family("Source Sans 3").as_deref(), Some("'Source Sans 3', sans-serif")); + assert_eq!(family("No Such Font").as_deref(), Some("'No Such Font', sans-serif")); + assert_eq!(family("serif").as_deref(), Some("serif")); +} + #[test] fn font_family_with_quote_or_backslash_is_escaped() { - for (family, want) in [("Bob's Font", r"'Bob\'s Font'"), (r"Back\slash Font", r"'Back\\slash Font'"), ("Bob's", r"'Bob\'s'")] { + for (family, want) in + [("Bob's Font", r"'Bob\'s Font', sans-serif"), (r"Back\slash Font", r"'Back\\slash Font', sans-serif"), ("Bob's", r"'Bob\'s', sans-serif")] + { let mut d = doc(); let st = CharStyle { font_family: family.into(), size: 18.0, ..CharStyle::default() }; let n = text(&mut d, "Hello", st); diff --git a/crates/svg/tests/text_layout.rs b/crates/svg/tests/text_layout.rs index e99bc822e4..649aadf473 100644 --- a/crates/svg/tests/text_layout.rs +++ b/crates/svg/tests/text_layout.rs @@ -300,7 +300,7 @@ fn lines_without_moved_characters_are_written_as_before() { } let open = |x: &str, anchor: &str| { format!( - r##""## + r##""## ) }; let words = diff --git a/crates/svg/tests/title_control_chars.rs b/crates/svg/tests/title_control_chars.rs new file mode 100644 index 0000000000..c7f842c0b2 --- /dev/null +++ b/crates/svg/tests/title_control_chars.rs @@ -0,0 +1,26 @@ +// Integration tests: 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 vectorcraft_doc::Document; +use vectorcraft_svg::{ExportOptions, export, import}; + +#[test] +fn title_and_description_control_chars_are_filtered() { + let mut d = Document::new(200.0, 200.0); + d.title = "Poster\u{b}v2".into(); + d.metadata.description = "a\u{1}b".into(); + let svg = export(&d, &ExportOptions::default()); + assert!(import(&svg).is_ok(), "export wrote invalid XML: {svg}"); + assert!(svg.contains("Poster v2")); + assert!(svg.contains("ab")); +} + +#[test] +fn title_and_description_markup_is_escaped() { + let mut d = Document::new(200.0, 200.0); + d.title = "A & ".into(); + d.metadata.description = "x & y".into(); + let svg = export(&d, &ExportOptions::default()); + assert!(import(&svg).is_ok(), "export wrote invalid XML: {svg}"); + assert!(svg.contains("A & <B>")); + assert!(svg.contains("x & y")); +} diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 286fc0e174..f7701b3a16 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -484,6 +484,23 @@ pub fn selection_quads(layout: &TextLayout, a: usize, b: usize) -> Vec<[Point; 4 /// Going right, the caret takes them in increasing order on left-to-right glyphs and in /// decreasing order on right-to-left glyphs; going left, it takes them in the reverse order. pub fn caret_horizontal(layout: &TextLayout, byte: usize, right: bool) -> usize { + caret_horizontal_filtered(layout, byte, right, |_| true) +} + +/// Like [`caret_horizontal`], but exclude glyph stops and line edges inside a grapheme of `text`. +pub fn caret_horizontal_cluster(layout: &TextLayout, text: &str, byte: usize, right: bool) -> usize { + use unicode_segmentation::GraphemeCursor; + let valid = |b| text.is_char_boundary(b) && GraphemeCursor::new(b, text.len(), true).is_boundary(text, 0).unwrap_or(false); + let to = caret_horizontal_filtered(layout, byte, right, valid); + if to == byte || valid(to) { + return to; + } + // Wrapping can split a grapheme; normalize only the fallback in its logical direction. + let Some(line) = layout.lines.get(layout.line_of(byte)) else { return byte }; + if right != line.rtl { edit::next_cluster(text, to) } else { edit::prev_cluster(text, to) } +} + +fn caret_horizontal_filtered(layout: &TextLayout, byte: usize, right: bool, valid: impl Fn(usize) -> bool) -> usize { let li = layout.line_of(byte); let Some(line) = layout.lines.get(li) else { return byte }; let glyphs = layout.glyphs.get(line.glyph_start..line.glyph_end).unwrap_or_default(); @@ -500,6 +517,7 @@ pub fn caret_horizontal(layout: &TextLayout, byte: usize, right: bool) -> usize stops.dedup(); stops .into_iter() + .filter(|&b| valid(b)) .filter_map(|b| { // Both the distance and the place among stops at one x are counted in the step's direction. let (bx, bo) = stop(b); diff --git a/crates/text/src/tests_devanagari.rs b/crates/text/src/tests_devanagari.rs index de238ee05a..37c21ac5a1 100644 --- a/crates/text/src/tests_devanagari.rs +++ b/crates/text/src/tests_devanagari.rs @@ -97,21 +97,30 @@ fn pre_base_matra_is_drawn_before_its_consonant() { #[test] fn syllables_map_to_their_source_bytes_and_caret_stops() { let Some(face) = devanagari_test_face("syllables_map_to_their_source_bytes_and_caret_stops") else { return }; - // हि + न्दी: the second syllable's matra stays with the conjunct it follows. + // हि + न्दी: raw font clusters can subdivide a Unicode editing grapheme. let s = "हिन्दी"; let l = devanagari_layout(&face, s); let second = "हि".len(); - assert_eq!(source_clusters(&l), vec![(0, second), (second, s.len() - second)]); + let clusters = source_clusters(&l); + assert_eq!(clusters.first(), Some(&(0, second)), "{clusters:?}"); + let mut end = 0; + for &(byte, len) in &clusters { + assert_eq!(byte, end, "source clusters must cover input without gaps or overlaps: {clusters:?}"); + assert!(len > 0, "empty source cluster: {clusters:?}"); + end = byte.checked_add(len).expect("source cluster range overflow"); + assert!(s.get(byte..end).is_some(), "source cluster must span valid UTF-8: {clusters:?}"); + } + assert_eq!(end, s.len(), "source clusters must cover the whole input: {clusters:?}"); // The first syllable's i matra is drawn before its consonant. assert_eq!(l.glyphs[1].gid, face.glyph_for('ह'), "{:?}", l.glyphs); assert!(l.glyphs[0].origin.x < l.glyphs[1].origin.x, "{:?}", l.glyphs); - // Left and Right arrows pass over the same syllables the shaper made. + // Editing arrows follow Unicode graphemes, regardless of raw cluster subdivision. assert_eq!(edit::next_cluster(s, 0), second); assert_eq!(edit::next_cluster(s, second), s.len()); assert_eq!(edit::prev_cluster(s, s.len()), second); - assert_eq!(caret_horizontal(&l, 0, true), second); - assert_eq!(caret_horizontal(&l, second, true), s.len()); - assert_eq!(caret_horizontal(&l, s.len(), false), second); + assert_eq!(caret_horizontal_cluster(&l, s, 0, true), second); + assert_eq!(caret_horizontal_cluster(&l, s, second, true), s.len()); + assert_eq!(caret_horizontal_cluster(&l, s, s.len(), false), second); assert!((caret_position(&l, second).0.x - cluster_extent(&l, 0).1).abs() < 1e-9); } diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index 3a7069b4e2..5589c3d0cc 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -8,7 +8,7 @@ mod solid; mod visibility; -pub use solid::{Bevel, BevelShape, Extrude, Facet, Inflate, View, extrude, inflate, plane}; +pub use solid::{Bevel, BevelShape, Extrude, Facet, Inflate, View, extrude, inflate, inflate_together, plane}; pub use visibility::{VisibleFace, visible_faces}; mod shading; pub use shading::{LightGradient, RgbGradient, ShadeGradient}; diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index b4a11cdb8e..216513f2ec 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -433,8 +433,7 @@ struct Camera { origin: Point, /// The eye's distance in front of the centre; `None` without perspective. eye: Option, - /// Deeper than any part of the object: faces drawn first go this far behind it, and faces - /// drawn last go this far in front of it. + /// Deeper than any part of the object: faces drawn first go this far behind it. far: f64, light: V3, } @@ -487,7 +486,9 @@ enum Order { /// a piece of a twisted wall at the solid's outline covers the walls behind it. Twisted, /// The face is drawn after every other face when it is turned toward the viewer. A flat end of - /// the solid has the whole solid behind its plane, so it covers whatever it overlaps. + /// the solid has the whole solid behind its plane, so it covers whatever it overlaps. Its depth + /// is `f64::MAX`, so the faces drawn last by several solids sorted together keep the order they + /// were added in. Last, } @@ -526,8 +527,8 @@ impl Builder<'_> { } let depth = if behind && order != Order::Twisted { centre.2 - self.camera.far - } else if order == Order::Last { - centre.2 + self.camera.far + } else if order == Order::Last && facing > 0.0 { + f64::MAX } else { centre.2 }; @@ -840,12 +841,11 @@ pub fn extrude(path: &PathData, rule: FillRule, bounds: Rect, options: Extrude, } } if o.cap { - // A cap turned toward the viewer covers the twisted walls it overlaps, even those nearer - // than its center. - let ends = if o.twist != 0.0 { Order::Last } else { Order::Depth }; + // 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. for (s, n) in [(steps.first(), 1.0), (steps.last(), -1.0)] { let Some(s) = s else { continue }; - b.face(rings.iter().map(|r| ring_at(r, s)).collect(), camera.rotate(V3(0.0, 0.0, n)), ends)?; + b.face(rings.iter().map(|r| ring_at(r, s)).collect(), camera.rotate(V3(0.0, 0.0, n)), Order::Last)?; } } Ok(b.finish()) @@ -859,7 +859,11 @@ pub fn plane(path: &PathData, rule: FillRule, bounds: Rect, view: View) -> Resul let camera = Camera::new(view, bounds, 0.0); let mut b = Builder { camera: &camera, closed: false, facets: vec![] }; let contours: Vec> = rings.iter().map(|r| r.iter().map(|p| camera.place(*p, 0.0)).collect()).collect(); - b.face(contours, camera.rotate(V3(0.0, 0.0, 1.0)), Order::Depth)?; + // A plane is one flat face, seen from either side. Its normal is turned toward the viewer, so + // it is drawn last, as a cap is, and planes drawn in one order keep the order they are given in. + let up = camera.rotate(V3(0.0, 0.0, 1.0)); + let n = if camera.facing(V3::default(), up) < 0.0 { V3(-up.0, -up.1, -up.2) } else { up }; + b.face(contours, n, Order::Last)?; Ok(b.finish()) } @@ -1258,39 +1262,94 @@ fn cell_triangles(pieces: &[Vec]) -> Option> { Some(triangles) } -/// The part of `outline` inside `cell`, as rings (holes running the other way). -fn material(outline: &PathData, cell: Rect) -> Option>> { +/// The part of `outline` (its rings, each with its bounds) inside `cell`, as rings (holes running +/// the other way). Only the rings whose bounds meet the cell's go into the boolean. +fn material(outline: &[(Rect, vectorcraft_geom::SubPath)], cell: Rect) -> Option>> { let r = PathData::single(vectorcraft_geom::SubPath::polyline( &[Point::new(cell.x0, cell.y0), Point::new(cell.x1, cell.y0), Point::new(cell.x1, cell.y1), Point::new(cell.x0, cell.y1)], true, )); + let near = PathData::new( + outline.iter().filter(|(b, _)| b.x0 <= cell.x1 && cell.x0 <= b.x1 && b.y0 <= cell.y1 && cell.y0 <= b.y1).map(|(_, s)| s.clone()).collect(), + ); let rule = FillRule::NonZero; let part = - vectorcraft_pathops::try_boolean(&r, rule, outline, rule, vectorcraft_pathops::BoolOp::Intersect, vectorcraft_pathops::DEFAULT_PRECISION) + vectorcraft_pathops::try_boolean(&r, rule, &near, rule, vectorcraft_pathops::BoolOp::Intersect, vectorcraft_pathops::DEFAULT_PRECISION) .ok()?; rings(&part, rule, cell.width(), MAX_PLANE_POINTS).ok() } -/// Inflate: the shape puffed out like a cushion, its edge kept where the art's outline is. -pub fn inflate(path: &PathData, rule: FillRule, bounds: Rect, options: Inflate, view: View) -> Result, String> { - check_bounds(bounds)?; - let o = options.sanitized(); +/// A shape to inflate: its rings and the membrane under them on the grid of the bounds. +struct Puff { + rings: Vec>, + /// The index of the rings' edges. + edges: Edges, + cell: f64, + nx: usize, + ny: usize, + m: Membrane, + /// How high the front rises at its peak. + height: f64, +} + +/// The rings of `path` and its membrane on the grid of `bounds`; `None` for a shape with no area. +fn puff(path: &PathData, rule: FillRule, bounds: Rect, o: &Inflate) -> Result, String> { let rings = rings(path, rule, bounds.width().max(bounds.height()), MAX_SOLID_POINTS)?; if rings.is_empty() { - return Ok(vec![]); + return Ok(None); } let size = bounds.width().max(bounds.height()); if size <= 0.0 { - return Ok(vec![]); + return Ok(None); } const CELLS: usize = 48; let cell = size / CELLS as f64; let (nx, ny) = (((bounds.width() / cell).ceil() as usize).max(1), ((bounds.height() / cell).ceil() as usize).max(1)); let edges = Edges::new(&rings); let m = Membrane::solve(&rings, &edges, bounds.origin(), cell, nx + 1, ny + 1); - let outline = PathData::new(rings.iter().map(|r| vectorcraft_geom::SubPath::polyline(r, true)).collect()); // A circle of radius r puffs into a half sphere of radius r at 50 % (its membrane peaks at r²/4). let height = 2.0 * m.peak.sqrt() * o.volume / 50.0; + Ok(Some(Puff { rings, edges, cell, nx, ny, m, height })) +} + +/// Inflate: the shape puffed out like a cushion, its edge kept where the art's outline is. +pub fn inflate(path: &PathData, rule: FillRule, bounds: Rect, options: Inflate, view: View) -> Result, String> { + inflate_together(&[(path, rule)], bounds, options, view).pop().unwrap_or(Ok(vec![])) +} + +/// Inflate for several shapes of one object (a fill and the outlines of its strokes): each puffs +/// on its own over the grid of `bounds`, and one eye sees them all, as far away as the highest +/// puff needs with Perspective. One result for each shape, in order. +pub fn inflate_together(shapes: &[(&PathData, FillRule)], bounds: Rect, options: Inflate, view: View) -> Vec, String>> { + let o = options.sanitized(); + let puffs: Vec, String>> = + shapes.iter().map(|(path, rule)| check_bounds(bounds).and_then(|()| puff(path, *rule, bounds, &o))).collect(); + let reach = puffs.iter().flatten().flatten().map(|p| p.height).fold(0.0, f64::max); + puffs + .into_iter() + .map(|p| match p { + Ok(Some(p)) => inflated(p, bounds, o, view, reach), + Ok(None) => Ok(vec![]), + Err(e) => Err(e), + }) + .collect() +} + +/// The facets of one inflated shape, for a camera that allows for a puff `reach` high (or the +/// shape's own, if higher): `reach` is the highest puff of the shapes drawn together. +fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64) -> Result, String> { + let Puff { rings, edges, cell, nx, ny, m, height } = p; + let outline: Vec<(Rect, vectorcraft_geom::SubPath)> = rings + .iter() + .filter_map(|r| { + let b = r.iter().skip(1).fold(Rect::from_points(*r.first()?, *r.first()?), |b, p| b.union_pt(*p)); + Some((b, vectorcraft_geom::SubPath::polyline(r, true))) + }) + .collect(); + // When no shape puffs (no volume, or shapes too narrow for the grid), every front (and a back + // that puffs too) lies flat in one plane: its cells are drawn last, as caps are. If one shape + // puffs, a flat front can be behind its puff, so the cells keep their depths. + let flat = reach <= 0.0; let lift = |p: Point| { if m.peak <= 0.0 || edges.near(p, 1e-9) { return 0.0; @@ -1315,7 +1374,7 @@ pub fn inflate(path: &PathData, rule: FillRule, bounds: Rect, options: Inflate, if n.dot(n) > 0.5 { n } else { V3(0.0, 0.0, 1.0) } }; let smooth = view.shade && view.has_colored_lights(); - let camera = Camera::new(view, bounds, o.depth + 2.0 * height); + let camera = Camera::new(view, bounds, o.depth + 2.0 * height.max(reach)); // Without its back cap the object is a shell open behind, its inside showing. let mut b = Builder { camera: &camera, closed: o.cap, facets: vec![] }; let half = o.depth / 2.0; @@ -1464,7 +1523,8 @@ pub fn inflate(path: &PathData, rule: FillRule, bounds: Rect, options: Inflate, let front: Vec> = pieces.iter().zip(&lifts).map(|(p, h)| p.iter().zip(h).map(|(q, h)| camera.place(*q, half + h)).collect()).collect(); let n = newell(&front); - b.face(front, n, Order::Depth)?; + let order = if flat { Order::Last } else { Order::Depth }; + b.face(front, n, order)?; if o.both_sides && o.cap { // The back winds the same way round as the front, so its outward normal is // reversed. @@ -1474,7 +1534,7 @@ pub fn inflate(path: &PathData, rule: FillRule, bounds: Rect, options: Inflate, .map(|(p, h)| p.iter().zip(h).map(|(q, h)| camera.place(back_turn.apply(*q), -half - h * back_turn.scale)).collect()) .collect(); let n = newell(&back); - b.face(back, V3(-n.0, -n.1, -n.2), Order::Depth)?; + b.face(back, V3(-n.0, -n.1, -n.2), order)?; } } } @@ -1482,9 +1542,9 @@ pub fn inflate(path: &PathData, rule: FillRule, bounds: Rect, options: Inflate, } if !o.both_sides && o.cap { let back: Vec> = rings.iter().map(|r| r.iter().map(|p| camera.place(back_turn.apply(*p), -half)).collect()).collect(); - // The back turned toward the viewer covers the twisted walls it overlaps, even those - // nearer than its center. - b.face(back, camera.rotate(V3(0.0, 0.0, -1.0)), if o.twist != 0.0 { Order::Last } else { Order::Depth })?; + // The back 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. + b.face(back, camera.rotate(V3(0.0, 0.0, -1.0)), Order::Last)?; } if o.depth > 0.0 { // The sides, cut into slices that follow a twist or taper. diff --git a/crates/three-d/src/tests_solid.rs b/crates/three-d/src/tests_solid.rs index ba4ddde3f0..cdbfa7054c 100644 --- a/crates/three-d/src/tests_solid.rs +++ b/crates/three-d/src/tests_solid.rs @@ -176,6 +176,15 @@ fn a_plane_turns_about_the_given_centre() { assert!(close(extent(&wide).x0, 150.0 - 150.0 * 0.5, 1e-6)); // Its back shows when turned past 90°: a plane is two-sided. assert_eq!(plane(&p, FillRule::EvenOdd, b, View { rotation_y: 150.0, ..front() }).unwrap().len(), 1); + // From either side it is drawn last, so the planes of several parts sorted together keep the + // order they are given in, and it is lit as the side seen. + for (y, seen) in [(30.0, 1.0), (150.0, -1.0)] { + let v = View { rotation_x: -20.0, rotation_y: y, ..front() }; + let f = plane(&p, FillRule::EvenOdd, b, v).unwrap(); + let camera = Camera::new(v, b, 0.0); + let lit = camera.brightness(camera.rotate(V3(0.0, 0.0, seen))); + assert!(f.len() == 1 && f[0].depth == f64::MAX && close(f[0].brightness, lit, 1e-12), "{y}: {:?}", f[0]); + } } #[test] @@ -661,6 +670,21 @@ fn inflate_twists_tapers_and_opens_its_back() { assert_eq!(at(Inflate { taper: 0.0, ..o }), at(Inflate { taper: 0.01, ..o })); } +/// A flat front is drawn after every other face only when it is turned toward the viewer: an open +/// Inflate at 0 % volume seen from behind shows the inside of its front, the far side, and the +/// walls nearer the eye are drawn over it. +#[test] +fn an_open_flat_front_seen_from_behind_is_drawn_under_the_walls() { + let (p, b) = shape(&square(0.0, 0.0, 100.0)); + let o = Inflate { depth: 60.0, volume: 0.0, cap: false, ..Inflate::default() }; + let ahead = inflate(&p, FillRule::EvenOdd, b, o, View { rotation_x: -20.0, rotation_y: 30.0, ..front() }).unwrap(); + assert!(ahead.last().is_some_and(|f| f.depth == f64::MAX), "from in front, the front is drawn last"); + let behind = inflate(&p, FillRule::EvenOdd, b, o, View { rotation_x: -20.0, rotation_y: 150.0, ..front() }).unwrap(); + assert!(behind.iter().all(|f| f.depth < f64::MAX)); + let (gap, at) = worst_misorder(&behind, 120); + assert!(gap < 1.0, "{gap} pt behind at {at:?}"); +} + /// At 0 % volume an inflated shape is the extruded one: twisted and tapered, their outlines /// agree from every side (no wall goes missing in either). #[test] diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs index 01e460136b..86f6f90db3 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -628,16 +628,14 @@ fn lp_hover(cx: &ToolContext, cache: &mut RegionCache, p: Point, edge: bool) -> LpHover::None } -fn lp_overlays(h: &LpHover, cache: &RegionCache) -> Vec { +/// The highlight of `h`, `width` screen pixels wide in `color`. +fn lp_overlays(h: &LpHover, cache: &RegionCache, color: [u8; 3], width: f32) -> Vec { match h { LpHover::None => vec![], - LpHover::Part(bp) => vec![Overlay::Path { path: bp.clone(), color: HIGHLIGHT_RED, width: 4.0, dashed: false }], - LpHover::Region(i) => cache - .map - .regions - .get(*i) - .map(|(_, bp, _)| vec![Overlay::Path { path: bp.clone(), color: HIGHLIGHT_RED, width: 4.0, dashed: false }]) - .unwrap_or_default(), + LpHover::Part(bp) => vec![Overlay::Path { path: bp.clone(), color, width, dashed: false }], + LpHover::Region(i) => { + cache.map.regions.get(*i).map(|(_, bp, _)| vec![Overlay::Path { path: bp.clone(), color, width, dashed: false }]).unwrap_or_default() + } } } @@ -701,7 +699,7 @@ impl Tool for LivePaintBucketTool { } fn overlays(&self, _cx: &ToolContext) -> Vec { - lp_overlays(&self.hover, &self.cache) + lp_overlays(&self.hover, &self.cache, HIGHLIGHT_RED, 4.0) } fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { @@ -711,18 +709,54 @@ impl Tool for LivePaintBucketTool { // ---------- Live Paint Selection ---------- -/// Live Paint Selection: click selects a face (Shift adds); Alt-click selects an edge. +/// The Live Paint Selection tool's highlight width (screen pixels) by default. +pub const LP_SELECT_WIDTH: f64 = 4.0; +/// The least and greatest highlight width (screen pixels) the Live Paint Selection tool takes. +pub const LP_SELECT_WIDTH_RANGE: (f64, f64) = (1.0, 20.0); + +/// Live Paint Selection: click selects a face (Shift adds); Alt-click selects an edge. Its Tool +/// Options (double-click the tool) are `selectFills` and `selectStrokes` (both on), the highlight +/// `color` (`#rrggbb`, red by default) and its `width` ([`LP_SELECT_WIDTH`] pixels). With Select +/// Strokes off, Alt-click selects the face under the pointer as a click does; with Select Fills +/// off, a click selects the edge nearest the pointer as Alt-click does; with both off, a click +/// selects no face or edge. pub struct LivePaintSelectionTool { cache: RegionCache, hover: LpHover, + fills: bool, + strokes: bool, + color: [u8; 3], + width: f64, } impl Default for LivePaintSelectionTool { fn default() -> Self { - Self { cache: RegionCache::live_paint(), hover: LpHover::None } + Self { cache: RegionCache::live_paint(), hover: LpHover::None, fills: true, strokes: true, color: HIGHLIGHT_RED, width: LP_SELECT_WIDTH } } } +impl LivePaintSelectionTool { + /// What a click picks, Alt held or not: Some(true) an edge, Some(false) a face, None nothing. + fn picks_edge(&self, alt: bool) -> Option { + match (self.fills, self.strokes) { + (true, true) => Some(alt), + (true, false) => Some(false), + (false, true) => Some(true), + (false, false) => None, + } + } +} + +/// A highlight color option: `#rrggbb` or a layer color's name (any case). +fn lp_color(v: &Value) -> Option<[u8; 3]> { + let s = v.as_str()?.trim(); + if let Some((_, c)) = vectorcraft_doc::LAYER_COLORS.iter().find(|(name, _)| name.eq_ignore_ascii_case(s)) { + return Some(*c); + } + let [r, g, b, _] = vectorcraft_color::Color::from_hex(s)?.to_rgba8(1.0); + Some([r, g, b]) +} + impl Tool for LivePaintSelectionTool { fn id(&self) -> &'static str { "livePaintSelection" @@ -730,18 +764,21 @@ impl Tool for LivePaintSelectionTool { fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { let p = ev.pos; + let edge = self.picks_edge(ev.mods.alt); match ev.kind { PointerKind::Move => { - self.hover = match lp_hover(cx, &mut self.cache, p, ev.mods.alt) { - h @ LpHover::Part(_) => h, + self.hover = match edge.map(|e| lp_hover(cx, &mut self.cache, p, e)) { + Some(h @ LpHover::Part(_)) => h, _ => LpHover::None, }; vec![] } PointerKind::Down => { let mut hit = None; - if let Some(g) = live_paint_at(cx.doc, p).and_then(|id| cx.doc.node(id)) { - let part = if ev.mods.alt { edge_near(g, p, cx.tol(4.0)) } else { face_at(g, p) }; + if let Some(edge) = edge + && let Some(g) = live_paint_at(cx.doc, p).and_then(|id| cx.doc.node(id)) + { + let part = if edge { edge_near(g, p, cx.tol(4.0)) } else { face_at(g, p) }; hit = part.map(|n| n.id); } match (hit, ev.mods.shift) { @@ -756,12 +793,36 @@ impl Tool for LivePaintSelectionTool { } fn overlays(&self, _cx: &ToolContext) -> Vec { - lp_overlays(&self.hover, &self.cache) + lp_overlays(&self.hover, &self.cache, self.color, self.width as f32) } fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { Cursor::Arrow } + + fn options(&self) -> Value { + let [r, g, b] = self.color; + json!({ + "selectFills": self.fills, + "selectStrokes": self.strokes, + "color": format!("#{r:02x}{g:02x}{b:02x}"), + "width": self.width, + }) + } + + fn set_option(&mut self, key: &str, v: &Value) { + match key { + "selectFills" => self.fills = v.as_bool().unwrap_or(self.fills), + "selectStrokes" => self.strokes = v.as_bool().unwrap_or(self.strokes), + "color" => self.color = lp_color(v).unwrap_or(self.color), + "width" => { + let (min, max) = LP_SELECT_WIDTH_RANGE; + self.width = v.as_f64().filter(|w| w.is_finite()).map_or(self.width, |w| w.clamp(min, max)); + } + _ => return, + } + self.hover = LpHover::None; + } } /// Create a builder-family tool by id (None = not one of ours). @@ -1014,6 +1075,74 @@ mod tests { assert_eq!(acts, vec![Action::Exec("select.none".into(), json!({}))]); } + #[test] + fn live_paint_selection_options_choose_what_a_click_selects() { + let (d, _gid, f2, e) = live_group_doc(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let alt = Mods { alt: true, ..Default::default() }; + let set = |ids: &[NodeId]| vec![Action::Exec("select.set".into(), json!({ "ids": ids.iter().map(|i| i.0).collect::>() }))]; + let none = vec![Action::Exec("select.none".into(), json!({}))]; + let mut t = LivePaintSelectionTool::default(); + assert_eq!(t.options(), json!({"selectFills": true, "selectStrokes": true, "color": "#ff2a2a", "width": 4.0})); + // Select Fills off: a click inside a face selects nothing, and a click by an edge selects it. + t.set_option("selectFills", &json!(false)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, 75.0, 25.0)), none); + t.pointer(&cx, &ev(PointerKind::Move, 75.0, 25.0)); + assert!(t.overlays(&cx).is_empty()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, 51.0, 25.0)), set(&[e])); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, 51.0, 25.0).with_mods(alt)), set(&[e])); + // Select Strokes off: Alt-click by an edge selects the face under the pointer. + t.set_option("selectFills", &json!(true)); + t.set_option("selectStrokes", &json!(false)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, 51.0, 25.0).with_mods(alt)), set(&[f2])); + t.pointer(&cx, &ev(PointerKind::Move, 51.0, 25.0).with_mods(alt)); + let ov = t.overlays(&cx); + let [Overlay::Path { path, .. }] = ov.as_slice() else { panic!("{ov:?}") }; + assert_eq!(path.bounding_box(), Rect::new(50.0, 0.0, 100.0, 50.0), "the face, not the edge"); + // Both off: nothing is selected or highlighted. + t.set_option("selectFills", &json!(false)); + for m in [Mods::default(), alt] { + assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, 51.0, 25.0).with_mods(m)), none); + t.pointer(&cx, &ev(PointerKind::Move, 51.0, 25.0).with_mods(m)); + assert!(t.overlays(&cx).is_empty()); + } + let shift = Mods { shift: true, ..Default::default() }; + assert!(t.pointer(&cx, &ev(PointerKind::Down, 75.0, 25.0).with_mods(shift)).is_empty()); + } + + #[test] + fn live_paint_selection_options_set_the_highlight() { + let (d, ..) = live_group_doc(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = LivePaintSelectionTool::default(); + let highlight = |t: &mut LivePaintSelectionTool| { + t.pointer(&cx, &ev(PointerKind::Move, 75.0, 25.0)); + match t.overlays(&cx).as_slice() { + [Overlay::Path { color, width, .. }] => (*color, *width), + ov => panic!("{ov:?}"), + } + }; + assert_eq!(highlight(&mut t), (HIGHLIGHT_RED, 4.0)); + t.set_option("color", &json!("#00FF00")); + t.set_option("width", &json!(9)); + assert_eq!(highlight(&mut t), ([0, 0xff, 0], 9.0)); + // A layer color's name; a value that is not a color, or a width that is not a number, is ignored. + t.set_option("color", &json!("light blue")); + t.set_option("width", &json!("wide")); + assert_eq!(highlight(&mut t), ([0x4f, 0x80, 0xff], 9.0)); + t.set_option("color", &json!("nope")); + assert_eq!(t.options()["color"], "#4f80ff"); + // The width stays within its range. + t.set_option("width", &json!(100)); + assert_eq!(t.options()["width"], json!(LP_SELECT_WIDTH_RANGE.1)); + t.set_option("width", &json!(0)); + assert_eq!(t.options()["width"], json!(LP_SELECT_WIDTH_RANGE.0)); + } + #[test] fn create_builds_the_three_tools() { for id in ["shapeBuilder", "livePaintBucket", "livePaintSelection"] { diff --git a/crates/tools/src/catalog.rs b/crates/tools/src/catalog.rs index 7c1fe218f9..955325a0f6 100644 --- a/crates/tools/src/catalog.rs +++ b/crates/tools/src/catalog.rs @@ -101,7 +101,7 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ &[t("mesh", "Mesh Tool", Some("U"), "tool-mesh")], &[t("gradient", "Gradient Tool", Some("G"), "tool-gradient")], &[t("eyedropper", "Eyedropper Tool", Some("I"), "tool-eyedropper"), t("measure", "Measure Tool", None, "tool-measure")], - &[t("blend", "Blend Tool", Some("W"), "tool-blend")], + &[t("blend", "Blend Tool", Some("W"), "tool-blend"), t("objectsOnPath", "Objects on Path Tool", None, "tool-objects-on-path")], &[t("dimension", "Dimension Tool", None, "tool-dimension")], &[ t("symbolSprayer", "Symbol Sprayer Tool", Some("Shift+S"), "tool-symbol"), diff --git a/crates/tools/src/corners.rs b/crates/tools/src/corners.rs index c3be27432d..b710fc7c75 100644 --- a/crates/tools/src/corners.rs +++ b/crates/tools/src/corners.rs @@ -374,7 +374,10 @@ impl CornerDrag { if !self.began { return vec![]; } - let mut out = vec![Overlay::Measure { p: self.at, text: format!("Radius: {}", cx.len(self.radius)) }]; + let mut out = vec![]; + if cx.measurement_labels { + out.push(Overlay::Measure { p: self.at, text: format!("Radius: {}", cx.len(self.radius)) }); + } if self.at_limit { out.push(Overlay::Path { path: self.corners_at_limit(), color: crate::builder::HIGHLIGHT_RED, width: 2.0, dashed: false }); } @@ -465,6 +468,8 @@ mod tests { assert!((radius(&a[1]) - 15.0).abs() < 1e-9); assert!(matches!(&a[1], Action::Preview(_, v) if v["id"] == id.0)); assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == "Radius: 15.00 pt"))); + let quiet = ToolContext { measurement_labels: false, ..crate::testutil::cx(&d, &s, &p) }; + assert!(!t.overlays(&quiet).iter().any(|o| matches!(o, Overlay::Measure { .. }))); // Past the middle the corner is fully round; back outside it is square. assert_eq!(radius(&t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 100.0, 100.0))[0]), 50.0); assert_eq!(radius(&t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 260.0, 260.0))[0]), 0.0); diff --git a/crates/tools/src/cropimage.rs b/crates/tools/src/cropimage.rs index 967733ce4e..512f4140a3 100644 --- a/crates/tools/src/cropimage.rs +++ b/crates/tools/src/cropimage.rs @@ -81,6 +81,8 @@ pub struct CropImageTool { /// None until it's dragged or set. rect: Option<(Option, Rect)>, drag: Option, + /// Where the pointer last was on the canvas (measurement label during a drag). + last: Point, } impl CropImageTool { @@ -108,6 +110,7 @@ impl CropImageTool { fn reset(&mut self) { self.rect = None; self.drag = None; + self.last = Point::ZERO; } } @@ -145,12 +148,14 @@ impl Tool for CropImageTool { let Some((id, image, r)) = self.current(cx) else { return vec![] }; match ev.kind { PointerKind::Down => { + self.last = ev.pos; self.drag = match hit_handle(r, ev.pos, cx.tol(5.0)) { Some(h) => Some(Drag::Handle(h, r)), None => r.contains(ev.pos).then_some(Drag::Move(ev.pos, r)), }; } PointerKind::Drag => { + self.last = ev.pos; let next = match self.drag { Some(Drag::Handle(h, from)) => within(resized(from, h, ev.pos), image), Some(Drag::Move(start, from)) => { @@ -163,7 +168,7 @@ impl Tool for CropImageTool { } PointerKind::Up => self.drag = None, PointerKind::DoubleClick => return self.apply(cx), - PointerKind::Move => {} + PointerKind::Move => self.last = ev.pos, } vec![] } @@ -201,7 +206,14 @@ impl Tool for CropImageTool { let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]; out.extend(corners.iter().zip(corners.iter().cycle().skip(1)).map(|(a, b)| Overlay::Line { a: *a, b: *b, color: CYAN, dashed: false })); out.extend(Handle::ALL.iter().map(|h| Overlay::Handle { p: h.pos(r), color: CYAN })); - out.push(Overlay::Label { p: Point::new(r.x0, r.y1), text: cx.size_label(r.width(), r.height()), color: CYAN }); + if cx.measurement_labels { + let text = cx.size_label(r.width(), r.height()); + if self.drag.is_some() { + out.push(Overlay::Measure { p: self.last, text }); + } else { + out.push(Overlay::Label { p: Point::new(r.x0, r.y1), text, color: CYAN }); + } + } out } @@ -370,4 +382,36 @@ mod tests { fn the_tool_is_made_by_its_id() { assert_eq!(crate::create(ID).id(), ID); } + + /// Smart Guides › Measurement Labels: the crop size readout follows the preference and the + /// pointer while the box is dragged. + #[test] + fn measurement_labels_gate_the_crop_size_readout() { + let (d, s) = doc_with_image((50.0, 60.0)); + let p = paint(); + let mut t = CropImageTool::default(); + let count = |on: bool| { + let mut tool = CropImageTool::default(); + let c = ToolContext { measurement_labels: on, ..cx(&d, &s, &p) }; + tool.pointer(&c, &PointerEvent::new(PointerKind::Down, 50.0, 60.0)); + tool.pointer(&c, &PointerEvent::new(PointerKind::Drag, 80.0, 70.0)); + tool.overlays(&c).iter().filter(|o| matches!(o, Overlay::Measure { .. } | Overlay::Label { .. })).count() + }; + assert_eq!(count(true), 1); + assert_eq!(count(false), 0); + let c = cx(&d, &s, &p); + drag(&mut t, &c, (50.0, 60.0), (80.0, 70.0)); + assert!( + t.overlays(&c).iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == &c.size_label(170.0, 90.0))), + "idle: label at the box" + ); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 110.0)); + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 120.0, 100.0)); + assert!( + t.overlays(&c) + .iter() + .any(|o| matches!(o, Overlay::Measure { p, text, .. } if *p == Point::new(120.0, 100.0) && text == &c.size_label(170.0, 90.0))), + "drag: measure at the pointer" + ); + } } diff --git a/crates/tools/src/cursors.toml b/crates/tools/src/cursors.toml index e0d1550d36..b2ee35ecd9 100644 --- a/crates/tools/src/cursors.toml +++ b/crates/tools/src/cursors.toml @@ -490,6 +490,13 @@ shown_when = ["The Blend tool over an anchor point (the blend starts there)."] hotspot = "The crosshair's centre." look = "Crosshair with a target badge (a ring with a centre dot)." +[[cursor]] +id = "ObjectsOnPath" +group = "Width, blend, slice and shape builder" +shown_when = ["The Objects on Path tool over a path the selected objects can attach to: a click attaches them."] +hotspot = "The crosshair's center." +look = "Crosshair with a badge of small squares along a curve, as on the tool's icon." + [[cursor]] id = "Slice" group = "Width, blend, slice and shape builder" diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index aed41c8297..4f47604717 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -399,7 +399,9 @@ impl Tool for DimensionTool { for p in [a, b] { out.push(Overlay::Anchor { p, color, filled: true, size: 6.0 }); } - if let Ok(text) = self.style.label(a.distance(b), false) { + if cx.measurement_labels + && let Ok(text) = self.style.label(a.distance(b), false) + { out.push(Overlay::Measure { p: self.at + Vec2::new(12.0, 12.0), text }); } } diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index b95468e37a..19f3da4b2f 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -62,6 +62,8 @@ enum State { start: Point, grab: Option, began: bool, + /// Group Selection: Shift-click on a selected object toggles it off on release. + deselect: Option, }, /// Dragging a curved segment: it follows the pointer (`path.reshapeSegment`). Segment { @@ -452,14 +454,25 @@ impl Tool for DirectSelectionTool { } else { h.leaf }; - self.state = State::MoveObject { start: p, grab: None, began: false }; - if cx.selection.contains(target) { - vec![] - } else if ev.mods.shift || cx.selection.contains(h.leaf) { - vec![Action::Exec("select.add".into(), json!({"ids": [target.0]}))] - } else { - vec![Action::Exec("select.set".into(), json!({"ids": [target.0]}))] + let mut deselect = None; + let mut out = vec![]; + if ev.mods.shift { + // Shift on a selected member deselects what was hit (a compound path's part), + // not the next ancestor a plain click would add (#2441). + if cx.selection.contains(h.leaf) { + deselect = Some(h.leaf); + } else { + out.push(Action::Exec("select.toggle".into(), json!({"id": target.0}))); + } + } else if !cx.selection.contains(target) { + if cx.selection.contains(h.leaf) { + out.push(Action::Exec("select.add".into(), json!({"ids": [target.0]}))); + } else { + out.push(Action::Exec("select.set".into(), json!({"ids": [target.0]}))); + } } + self.state = State::MoveObject { start: p, grab: None, began: false, deselect }; + out } (PointerKind::DoubleClick, _) if self.group => release_guide_at(cx, p, ev.mods).into_iter().collect(), (PointerKind::DoubleClick, _) if !self.group => { @@ -503,7 +516,7 @@ impl Tool for DirectSelectionTool { self.snapped = false; if let Some(g) = self.mesh.hit(cx, &cx.selection.objects, p) { self.state = State::Mesh; - return self.mesh.press(g); + return self.mesh.press(cx, g); } self.mesh.unfocus(); if let Some((id, si, ai, out)) = hit_handle(cx, p, point) { @@ -522,7 +535,7 @@ impl Tool for DirectSelectionTool { } // Alt picks the whole path (and Alt-drag copies it), as on a segment. if ev.mods.alt { - self.state = State::MoveObject { start: p, grab: Some(grab), began: false }; + self.state = State::MoveObject { start: p, grab: Some(grab), began: false, deselect: None }; let whole = cx.selection.contains(id) && cx.selection.partial(id).is_none(); return if whole { vec![] } else { vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))] }; } @@ -533,7 +546,7 @@ impl Tool for DirectSelectionTool { // Paths all selected whole move as objects, held by this anchor, so Alt can turn // the copy on and off during the drag as with the Selection tool. self.state = if already && cx.selection.anchors.is_empty() { - State::MoveObject { start: p, grab: Some(grab), began: false } + State::MoveObject { start: p, grab: Some(grab), began: false, deselect: None } } else { State::MoveAnchors { start: p, grab, began: false } }; @@ -586,7 +599,7 @@ impl Tool for DirectSelectionTool { } } // Clicking the fill selects the whole leaf path (all anchors). - self.state = State::MoveObject { start: p, grab: None, began: false }; + self.state = State::MoveObject { start: p, grab: None, began: false, deselect: None }; if ev.mods.shift { return vec![Action::Exec("select.toggle".into(), json!({"id": h.leaf.0}))]; } @@ -638,14 +651,14 @@ impl Tool for DirectSelectionTool { )); out } - (PointerKind::Drag, State::MoveObject { start, grab, began }) => { + (PointerKind::Drag, State::MoveObject { start, grab, began, .. }) => { let mut out = vec![]; if !began { if p.distance(start) < cx.tol(3.0) { return out; } out.push(Action::Begin(if ev.mods.alt { "Copy".into() } else { "Move".into() })); - self.state = State::MoveObject { start, grab, began: true }; + self.state = State::MoveObject { start, grab, began: true, deselect: None }; if grab.is_some() { // Alt can go down or up at any time: gather both while nothing has moved. self.anchor_snap = Some(PointSnap::new(cx, || Targets::for_anchor_drag(cx.doc, cx.selection))); @@ -763,16 +776,23 @@ impl Tool for DirectSelectionTool { | State::SpineSegment { began, .. } | State::TypeArea { began, .. }, ) => { + let deselect = match self.state { + State::MoveObject { deselect, .. } => deselect, + _ => None, + }; self.state = State::Idle; self.guides.clear(); (self.anchor_snap, self.copy_snap, self.move_snap) = (None, None, None); - match (began, self.click.take(), self.click_segment.take()) { - (true, _, _) => vec![Action::Commit], - (false, Some((id, si, ai)), _) => { + match (began, deselect, self.click.take(), self.click_segment.take()) { + (true, ..) => vec![Action::Commit], + (false, Some(id), _, _) => vec![Action::Exec("select.toggle".into(), json!({"id": id.0}))], + (false, None, Some((id, si, ai)), _) => { vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": [[si, ai]], "mode": "set"}))] } - (false, None, Some((id, si, seg))) => vec![Action::Exec("select.segments".into(), json!({"id": id.0, "segments": [[si, seg]]}))], - (false, None, None) => vec![], + (false, None, None, Some((id, si, seg))) => { + vec![Action::Exec("select.segments".into(), json!({"id": id.0, "segments": [[si, seg]]}))] + } + (false, None, None, None) => vec![], } } (PointerKind::Up, State::Handle { .. } | State::SpineHandle { .. }) => { @@ -1377,6 +1397,35 @@ mod tests { assert_eq!(click(&s, 25.0, 100.0), vec![Action::Exec("select.add".into(), json!({"ids": [compound.0]}))]); } + /// Group Selection Shift-click on a selected compound-path member deselects it on release. + #[test] + fn group_selection_shift_click_deselects_a_compound_path_member() { + let mut d = vectorcraft_doc::Document::new(500.0, 500.0); + let l = d.layers[0].id; + let (outer, hole, compound) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let rect = |id, a: f64, b: f64| { + std::sync::Arc::new(vectorcraft_doc::Node::path(id, vectorcraft_geom::shapes::rectangle(Rect::new(a, a, b, b)), Default::default())) + }; + let mut c = vectorcraft_doc::Node::new( + compound, + vectorcraft_doc::NodeKind::Compound { + children: vec![rect(outer, 0.0, 200.0), rect(hole, 50.0, 150.0)], + rule: vectorcraft_geom::FillRule::EvenOdd, + }, + ); + c.appearance = vectorcraft_doc::Appearance::default_art().into(); + d.insert(Some(l), 0, c).unwrap(); + let p = paint(); + let mut s = Selection::default(); + s.set([outer]); + let shift = Mods { shift: true, ..Mods::default() }; + let cx = cx(&d, &s, &p); + let mut t = DirectSelectionTool::new(true); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 25.0, 100.0).with_mods(shift)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 25.0, 100.0).with_mods(shift)); + assert_eq!(a, vec![Action::Exec("select.toggle".into(), json!({"id": outer.0}))]); + } + /// A path inside an inner group, a sibling path outside it, and the groups' ids. /// The inside path is the rectangle at (100, 100); the outside one at (300, 300). fn nested_group_doc() -> (vectorcraft_doc::Document, NodeId, NodeId, NodeId, NodeId) { diff --git a/crates/tools/src/distort/perspective.rs b/crates/tools/src/distort/perspective.rs index b105a1562b..4f172760b6 100644 --- a/crates/tools/src/distort/perspective.rs +++ b/crates/tools/src/distort/perspective.rs @@ -1262,7 +1262,9 @@ impl Tool for PerspectiveSelectionTool { } } } - if let Some((p, t)) = &self.measure { + if cx.measurement_labels + && let Some((p, t)) = &self.measure + { out.push(Overlay::Measure { p: *p, text: t.clone() }); } out diff --git a/crates/tools/src/distort/width.rs b/crates/tools/src/distort/width.rs index e6c29e9e08..ebe7d7ab5d 100644 --- a/crates/tools/src/distort/width.rs +++ b/crates/tools/src/distort/width.rs @@ -435,7 +435,9 @@ impl Tool for WidthTool { let q = d.spot.p; out.push(Overlay::Line { a: q + d.spot.n * d.left, b: q - d.spot.n * d.right, color: BLUE, dashed: false }); out.push(Overlay::Path { path: diamond(q, r), color: BLUE, width: 2.0, dashed: false }); - out.push(Overlay::Measure { p: q + d.spot.n * (d.left + r * 3.0), text: format!("W: {}", cx.stroke_unit.readout(d.left + d.right)) }); + if cx.measurement_labels { + out.push(Overlay::Measure { p: q + d.spot.n * (d.left + r * 3.0), text: format!("W: {}", cx.stroke_unit.readout(d.left + d.right)) }); + } } else if let Some(h) = &self.hover { out.push(Overlay::Line { a: h.p + h.n * h.left, b: h.p - h.n * h.right, color: BLUE, dashed: true }); out.push(Overlay::Path { path: diamond(h.p, r), color: BLUE, width: 1.0, dashed: false }); diff --git a/crates/tools/src/draw2/anchor.rs b/crates/tools/src/draw2/anchor.rs index cf18d014d8..5ac491c612 100644 --- a/crates/tools/src/draw2/anchor.rs +++ b/crates/tools/src/draw2/anchor.rs @@ -6,7 +6,9 @@ //! 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, //! straight or curved (#1111; Shift: its handles at right angles to the line between its anchors, -//! at one length). Blend spine points and handles follow the same conversions (#2544). +//! 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). Blend spine points and handles follow the same +//! conversions (#2544). //! Scissors: click a path to split it there. use serde_json::json; @@ -37,6 +39,23 @@ enum State { start: Point, began: bool, }, + /// Shift-dragging an anchor (`from`, where it was): it moves, handles and all. + Move { + id: NodeId, + si: usize, + ai: usize, + from: Point, + start: Point, + began: bool, + }, + /// Shift-dragging a selected blend's spine point: it moves, handles and all. + SpineMove { + id: NodeId, + ai: usize, + from: Point, + start: Point, + began: bool, + }, /// Dragging a selected blend's spine point into a symmetric smooth point. SpineConvert { id: NodeId, @@ -124,6 +143,7 @@ impl AnchorTool { }; let rank = |state| match state { State::Idle => None, + State::Move { id, .. } | State::SpineMove { id, .. } => Some((cx.selection.contains(id), cx.doc.index_path(id))), State::Convert { id, .. } | State::Handle { id, .. } | State::SpineConvert { id, .. } @@ -170,6 +190,35 @@ impl AnchorTool { out } + /// The press on an anchor (or a selected blend's spine point) with Shift held moves it + /// instead of converting it. Any other press is kept. + fn moving(cx: &ToolContext, st: State) -> State { + match st { + State::Convert { id, si, ai, start, .. } => { + match cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p)) { + Some(from) => State::Move { id, si, ai, from, start, began: false }, + None => st, + } + } + State::SpineConvert { id, ai, start, .. } => { + match crate::direct::spines(cx) + .into_iter() + .find(|(blend, _)| *blend == id) + .and_then(|(_, path)| path.subpaths.first()?.anchors.get(ai).map(|a| a.p)) + { + Some(from) => State::SpineMove { id, ai, from, start, began: false }, + None => st, + } + } + _ => st, + } + } + + /// How far a Shift-dragged anchor has gone: Shift still held keeps it at 45° steps. + fn move_delta(cx: &ToolContext, start: Point, p: Point, shift: bool) -> vectorcraft_geom::Vec2 { + if shift { constrain_angle_from(p - start, 45.0, cx.constrain_angle) } else { p - start } + } + fn add(cx: &ToolContext, p: Point) -> Vec { hit_segment(cx, p, cx.pick_tol()).map(insert_anchor).into_iter().collect() } @@ -216,6 +265,9 @@ impl Tool for AnchorTool { } ("anchorPoint", PointerKind::Down) => { self.state = Self::press_target(cx, p); + if ev.mods.shift { + self.state = Self::moving(cx, self.state); + } if matches!(self.state, State::Handle { .. }) { self.snap = HandleSnap::default(); } @@ -226,6 +278,8 @@ impl Tool for AnchorTool { let (began, far) = match self.state { State::Idle => return out, State::Convert { began, start, .. } + | State::Move { began, start, .. } + | State::SpineMove { began, start, .. } | State::Handle { began, start, .. } | State::SpineConvert { began, start, .. } | State::SpineHandle { began, start, .. } @@ -236,10 +290,16 @@ impl Tool for AnchorTool { return out; } out.push(Action::Begin( - if matches!(self.state, State::Convert { .. } | State::SpineConvert { .. }) { "Convert Anchor Point" } else { "Reshape" } - .into(), + match self.state { + State::Convert { .. } | State::SpineConvert { .. } => "Convert Anchor Point", + State::Move { .. } | State::SpineMove { .. } => "Move", + _ => "Reshape", + } + .into(), )); if let State::Convert { began, .. } + | State::Move { began, .. } + | State::SpineMove { began, .. } | State::Handle { began, .. } | State::SpineConvert { began, .. } | State::SpineHandle { began, .. } @@ -254,6 +314,14 @@ impl Tool for AnchorTool { "path.convertAnchor".into(), json!({"id": id.0, "subpath": si, "anchor": ai, "to": "smooth", "x": p.x, "y": p.y}), ), + State::Move { id, si, ai, from, start, .. } => { + let q = from + Self::move_delta(cx, start, p, ev.mods.shift); + Action::Preview("path.moveAnchor".into(), json!({"id": id.0, "subpath": si, "anchor": ai, "x": q.x, "y": q.y})) + } + State::SpineMove { id, ai, from, start, .. } => { + let q = from + Self::move_delta(cx, start, p, ev.mods.shift); + Action::Preview("object.blend.spine.moveAnchor".into(), json!({"id": id.0, "anchor": ai, "x": q.x, "y": q.y})) + } State::SpineConvert { id, ai, .. } => Action::Preview( "object.blend.spine.convertAnchor".into(), json!({"id": id.0, "anchor": ai, "to": "smooth", "x": p.x, "y": p.y}), @@ -304,6 +372,8 @@ impl Tool for AnchorTool { let st = std::mem::replace(&mut self.state, State::Idle); match st { State::Convert { began: true, .. } + | State::Move { began: true, .. } + | State::SpineMove { began: true, .. } | State::Handle { began: true, .. } | State::SpineConvert { began: true, .. } | State::SpineHandle { began: true, .. } @@ -367,6 +437,8 @@ impl Tool for AnchorTool { let st = std::mem::replace(&mut self.state, State::Idle); match st { State::Convert { began: true, .. } + | State::Move { began: true, .. } + | State::SpineMove { began: true, .. } | State::Handle { began: true, .. } | State::SpineConvert { began: true, .. } | State::SpineHandle { began: true, .. } @@ -396,6 +468,9 @@ impl Tool for AnchorTool { } _ => match self.state { State::Reshape { .. } => Cursor::ReshapeSegment, + // A Shift-drag moving an anchor shows the filled arrow, as Direct Selection's does. + State::Move { began: true, .. } | State::SpineMove { began: true, .. } => Cursor::Arrow, + State::Move { .. } | State::SpineMove { .. } => Cursor::AnchorPoint, State::Idle => press_cursor(cx, p), State::Convert { .. } | State::Handle { .. } | State::SpineConvert { .. } | State::SpineHandle { .. } => Cursor::AnchorPoint, }, @@ -856,4 +931,43 @@ mod tests { assert!(!a.has_out()); assert_eq!(a.h_in, Point::new(160.0, 280.0)); } + + /// Shift held at the press on an anchor moves it, handles and all, instead of pulling out + /// handles; Shift still held keeps the move at 45° steps, released frees it. A Shift-click + /// that doesn't move leaves the anchor as it was. + #[test] + fn anchor_point_shift_drag_moves_the_anchor() { + 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); + sp.anchors[1] = vectorcraft_geom::Anchor::smooth(Point::new(200.0, 300.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 s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let shift = Mods { shift: true, ..Mods::default() }; + let moved = |x: f64, y: f64| Action::Preview("path.moveAnchor".into(), json!({"id": id.0, "subpath": 0, "anchor": 1, "x": x, "y": y})); + let mut t = AnchorTool::new("anchorPoint"); + // Pressed a pixel off the anchor: it keeps that offset to the pointer. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 201.0, 301.0).with_mods(shift)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 231.0, 341.0)); + assert_eq!(a, vec![Action::Begin("Move".into()), moved(230.0, 340.0)]); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 241.0, 306.0).with_mods(shift)); + assert!( + matches!(&a[..], [Action::Preview(c, v)] if c == "path.moveAnchor" && v["y"].as_f64().is_some_and(|y| (y - 300.0).abs() < 1e-9)), + "{a:?}" + ); + assert_eq!(t.cursor(&cx, Point::new(241.0, 306.0), shift), Cursor::Arrow); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 241.0, 306.0)), vec![Action::Commit]); + // Without Shift the same press still pulls out handles. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 200.0, 300.0)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 230.0, 340.0)); + assert!(matches!(&a[..], [Action::Begin(_), Action::Preview(c, _)] if c == "path.convertAnchor"), "{a:?}"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 230.0, 340.0)); + // A Shift-click that doesn't move does nothing (no conversion to a corner). + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 200.0, 300.0).with_mods(shift)); + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 200.0, 300.0).with_mods(shift)).is_empty()); + } } diff --git a/crates/tools/src/draw2/curvature.rs b/crates/tools/src/draw2/curvature.rs index 7394c467df..d2503be652 100644 --- a/crates/tools/src/draw2/curvature.rs +++ b/crates/tools/src/draw2/curvature.rs @@ -598,6 +598,9 @@ impl Tool for CurvatureTool { curvature_extend(&mut tail, false, h, self.how(&e), false); tail.to_bezpath_into(&mut bp); o.push(Overlay::Path { path: bp, color: FEEDBACK, width: 1.0, dashed: false }); + if cx.measurement_labels && e.p.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(e.p, h) }); + } } return o; } @@ -609,6 +612,12 @@ impl Tool for CurvatureTool { pts.push((h, false)); curvature_spline(&pts, false).to_bezpath_into(&mut bp); o.push(Overlay::Path { path: bp, color: FEEDBACK, width: 1.0, dashed: false }); + if let Some((from, _)) = self.pts.last() + && cx.measurement_labels + && from.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(*from, h) }); + } } for (i, (p, _)) in self.pts.iter().enumerate() { o.push(Overlay::CurvePoint { p: *p, color: FEEDBACK, filled: Some(i) == self.current, size: 6.0 }); @@ -1033,7 +1042,11 @@ mod tests { let s = selected(id, Some(5)); let cx = quiet(&d, &s, &p); t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 650.0, 60.0)); - assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Path { .. })), "the rubber band shows"); + let ovs = t.overlays(&cx); + assert!(ovs.iter().any(|o| matches!(o, Overlay::Path { .. })), "the rubber band shows"); + let from = pt(550.0, 120.0); + let to = pt(650.0, 60.0); + assert!(ovs.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == &cx.segment_measure_label(from, to)))); let a = press(&mut t, &cx, 650.0, 60.0, true); assert!(matches!(edit_op(&a[0]), Some(("extend", v)) if v["from"] == "smooth"), "{a:?}"); curvature_extend(&mut sp, false, pt(650.0, 60.0), EndCurve::Smooth, false); diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index c7cf84f9fe..c0630d997d 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -39,6 +39,11 @@ pub struct GestureTool { /// "Keep selected": select the path a Pencil, Paintbrush or Blob Brush stroke draws, continues /// or merges into (on for the Pencil and Paintbrush, off for the Blob Brush). pub keep_selected: bool, + /// "Alt key toggles to Smooth Tool": holding Alt with the Pencil tool smooths selected paths + /// instead of closing the path (Pencil only, on by default). + pub alt_smooth: bool, + /// Active drag is smoothing with the Pencil tool. + smoothing: bool, /// "Merge only with selection": a Blob Brush stroke merges only with selected paths. pub merge_only_selection: bool, /// "Edit selected paths within N pixels". @@ -74,6 +79,9 @@ impl GestureTool { size: 10.0, fill: false, keep_selected: id != "blobBrush", + // Off, as Pencil Tool Options ships it: Alt keeps drawing a closed path until it is on. + alt_smooth: false, + smoothing: false, merge_only_selection: false, edit_within: 12.0, close_within: 15.0, @@ -181,13 +189,19 @@ impl GestureTool { let pts = &self.points; let has_sel = !cx.selection.is_empty(); let tol = cx.tol(self.edit_within); + if self.smoothing { + if has_sel && pts.len() >= 2 { + return vec![Action::Exec("path.smoothRegion".into(), json!({"points": points_json(pts), "radius": tol, "fidelity": self.fidelity}))]; + } + return vec![]; + } match self.id { "pencil" | "paintbrush" => { if !self.began { return vec![]; } let near = pts.len() > 2 && pts[0].distance(pts[pts.len() - 1]) <= cx.tol(self.close_within); - let closed = m.alt || (self.extend.is_none() && near); + let closed = (m.alt && !self.alt_smooth) || (self.extend.is_none() && near); vec![Action::Preview("path.freehand".into(), self.freehand_params(closed)), Action::Commit] } "blobBrush" => vec![Action::Exec( @@ -228,10 +242,15 @@ impl Tool for GestureTool { PointerKind::Down => { self.active = true; self.began = false; - self.extend = if self.draws_path() { self.find_extend(cx, p) } else { None }; - self.redraw = if self.draws_path() && self.extend.is_none() { self.find_redraw(cx, p) } else { None }; + self.smoothing = self.id == "pencil" && self.alt_smooth && ev.mods.alt; + self.extend = if self.draws_path() && !self.smoothing { self.find_extend(cx, p) } else { None }; + self.redraw = if self.draws_path() && !self.smoothing && self.extend.is_none() { self.find_redraw(cx, p) } else { None }; // A path continued starts at its end, one redrawn on it; a new one where it snaps. - let start = if self.snaps() && self.extend.is_none() && self.redraw.is_none() { self.snap.press(cx, p, &[], None) } else { p }; + let start = if self.snaps() && !self.smoothing && self.extend.is_none() && self.redraw.is_none() { + self.snap.press(cx, p, &[], None) + } else { + p + }; self.clear(); self.push(start, ev.pressure); vec![] @@ -240,7 +259,10 @@ impl Tool for GestureTool { if !self.active { return vec![]; } - if self.snaps() { + if !self.began && self.id == "pencil" && self.alt_smooth && ev.mods.alt { + self.smoothing = true; + } + if self.snaps() && !self.smoothing { // Where the stroke would end: shown, taken on release. self.snap.drag(cx, p, None); } @@ -248,7 +270,7 @@ impl Tool for GestureTool { return vec![]; } self.push(p, ev.pressure); - if !self.draws_path() { + if !self.draws_path() || self.smoothing { return vec![]; } let mut out = vec![]; @@ -263,11 +285,12 @@ impl Tool for GestureTool { if !self.active { return vec![]; } - let end = if self.snaps() { self.snap.drag(cx, p, None) } else { p }; + let end = if self.snaps() && !self.smoothing { self.snap.drag(cx, p, None) } else { p }; self.snap.clear(); if self.points.last().is_some_and(|l| l.distance(p) >= cx.tol(1.0)) { self.push(end, ev.pressure); } else if self.snaps() + && !self.smoothing && self.points.len() > 1 && let Some(last) = self.points.last_mut() { @@ -277,6 +300,7 @@ impl Tool for GestureTool { let out = self.finish(cx, ev.mods); self.active = false; self.began = false; + self.smoothing = false; self.clear(); self.extend = None; self.redraw = None; @@ -296,6 +320,7 @@ impl Tool for GestureTool { self.snap.clear(); self.active = false; self.began = false; + self.smoothing = false; self.clear(); if began { vec![Action::Cancel] } else { vec![] } } @@ -331,7 +356,10 @@ impl Tool for GestureTool { o.push(Overlay::Path { path: polyline(&self.points), color, width, dashed: self.id == "knife" }); o } - fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { + fn cursor(&self, _cx: &ToolContext, _p: Point, m: Mods) -> Cursor { + if self.id == "pencil" && self.alt_smooth && m.alt { + return Cursor::Smooth; + } match self.id { "paintbrush" => Cursor::Paintbrush, "blobBrush" => Cursor::BlobBrush, @@ -345,7 +373,17 @@ impl Tool for GestureTool { } fn options(&self) -> Value { match self.id { - "pencil" | "paintbrush" => { + "pencil" => { + json!({ + "fidelity": self.fidelity, + "fill": self.fill, + "altSmooth": self.alt_smooth, + "keepSelected": self.keep_selected, + "editWithin": self.edit_within, + "closeWithin": self.close_within + }) + } + "paintbrush" => { json!({ "fidelity": self.fidelity, "fill": self.fill, @@ -365,6 +403,7 @@ impl Tool for GestureTool { "fidelity" => self.fidelity = v.as_f64().unwrap_or(self.fidelity).clamp(0.05, 100.0), "size" => self.size = v.as_f64().unwrap_or(self.size).clamp(0.1, 1000.0), "fill" => self.fill = v.as_bool().unwrap_or(self.fill), + "altSmooth" => self.alt_smooth = v.as_bool().unwrap_or(self.alt_smooth), "keepSelected" => self.keep_selected = v.as_bool().unwrap_or(self.keep_selected), "mergeOnlySelection" => self.merge_only_selection = v.as_bool().unwrap_or(self.merge_only_selection), "editWithin" => self.edit_within = v.as_f64().unwrap_or(self.edit_within).clamp(0.0, 100.0), @@ -390,6 +429,16 @@ mod tests { v } + fn drag_held(t: &mut GestureTool, cx: &ToolContext, pts: &[(f64, f64)], m: Mods) -> Vec> { + let mut v = vec![t.pointer(cx, &PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1).with_mods(m))]; + for &(x, y) in &pts[1..] { + v.push(t.pointer(cx, &PointerEvent::new(PointerKind::Drag, x, y).with_mods(m))); + } + let l = pts[pts.len() - 1]; + v.push(t.pointer(cx, &PointerEvent::new(PointerKind::Up, l.0, l.1).with_mods(m))); + v + } + /// The Pencil's new path starts and ends on Smart Guides (#506), the points between where /// the hand went. #[test] @@ -540,4 +589,46 @@ mod tests { b.key(&cx, ToolKey::BracketRight, Mods::default()); assert_eq!(b.options()["size"], 11.0); } + + #[test] + fn pencil_alt_toggles_to_smooth_when_enabled_and_closes_when_disabled() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let cx = cx(&d, &s, &p); + + // Off by default, as Pencil Tool Options ships it; on, Alt lends the Smooth tool. + let mut t = GestureTool::new("pencil"); + assert_eq!(t.options()["altSmooth"], json!(false)); + t.set_option("altSmooth", &json!(true)); + + // When alt is pressed, cursor shows smooth tool. + let alt_mod = Mods { alt: true, ..Default::default() }; + assert_eq!(t.cursor(&cx, Point::new(50.0, 50.0), alt_mod), Cursor::Smooth); + assert_eq!(t.cursor(&cx, Point::new(50.0, 50.0), Mods::default()), Cursor::Pencil); + + // Alt-drag over selected path smooths it. + let acts = drag_held(&mut t, &cx, &[(50.0, 150.0), (150.0, 150.0), (250.0, 150.0)], alt_mod); + assert!(acts[1].is_empty(), "drag does not preview freehand path while smoothing"); + let last = acts.last().unwrap(); + assert!( + matches!(&last[0], Action::Exec(c, v) if c == "path.smoothRegion" && v["points"].as_array().unwrap().len() == 3), + "expected path.smoothRegion, got: {last:?}" + ); + + // When altSmooth is disabled: + t.set_option("altSmooth", &json!(false)); + assert_eq!(t.options()["altSmooth"], json!(false)); + assert_eq!(t.cursor(&cx, Point::new(50.0, 50.0), alt_mod), Cursor::Pencil); + + // Alt-drag draws a closed pencil path. + let empty_sel = Selection::default(); + let cx_empty = crate::testutil::cx(&d, &empty_sel, &p); + let acts = drag(&mut t, &cx_empty, &[(0.0, 0.0), (10.0, 5.0), (20.0, 0.0)], alt_mod); + assert_eq!(acts[1][0], Action::Begin("Pencil".into())); + let last = acts.last().unwrap(); + assert!(matches!(&last[0], Action::Preview(_, v) if v["closed"] == true && v["style"] == "pencil")); + assert_eq!(last[1], Action::Commit); + } } diff --git a/crates/tools/src/extra.rs b/crates/tools/src/extra.rs index 2c87204647..86d4ae4a32 100644 --- a/crates/tools/src/extra.rs +++ b/crates/tools/src/extra.rs @@ -402,24 +402,30 @@ impl Tool for ShaperTool { pub struct GraphTool { id: &'static str, start: Option, + last: Point, + mods: Mods, began: bool, } impl GraphTool { fn new(id: &str) -> Self { let id = crate::catalog::tool_info(id).map(|t| t.id).unwrap_or("columnGraph"); - Self { id, start: None, began: false } + Self { id, start: None, last: Point::ZERO, mods: Mods::default(), began: false } } fn kind(&self) -> &'static str { vectorcraft_doc::GraphKind::parse(self.id).unwrap_or_default().id() } - fn params(&self, s: Point, p: Point, m: Mods) -> Value { + /// The plot rectangle a drag from `s` to `p` draws (Shift = square, Alt = from the centre). + fn plot_rect(s: Point, p: Point, m: Mods) -> vectorcraft_geom::Rect { let mut d = p - s; if m.shift { let k = d.x.abs().max(d.y.abs()); d = Vec2::new(k * d.x.signum(), k * d.y.signum()); } - let r = if m.alt { vectorcraft_geom::Rect::from_points(s - d, s + d) } else { vectorcraft_geom::Rect::from_points(s, s + d) }; + if m.alt { vectorcraft_geom::Rect::from_points(s - d, s + d) } else { vectorcraft_geom::Rect::from_points(s, s + d) } + } + fn params(&self, s: Point, p: Point, m: Mods) -> Value { + let r = Self::plot_rect(s, p, m); json!({ "type": self.kind(), "x": r.x0, "y": r.y0, "width": r.width().max(1.0), "height": r.height().max(1.0) }) } } @@ -435,11 +441,14 @@ impl Tool for GraphTool { match ev.kind { PointerKind::Down => { self.start = Some(ev.pos); + self.last = ev.pos; self.began = false; vec![] } PointerKind::Drag => { let Some(s) = self.start else { return vec![] }; + self.last = ev.pos; + self.mods = ev.mods; let mut out = vec![]; if !self.began { if ev.pos.distance(s) < cx.tol(3.0) { @@ -472,6 +481,14 @@ impl Tool for GraphTool { } vec![] } + fn overlays(&self, cx: &ToolContext) -> Vec { + if let Some(s) = self.start.filter(|_| self.began && cx.measurement_labels) { + let r = Self::plot_rect(s, self.last, self.mods); + vec![Overlay::Measure { p: self.last, text: cx.size_label(r.width(), r.height()) }] + } else { + vec![] + } + } fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { Cursor::Crosshair } @@ -503,6 +520,38 @@ mod tests { assert_eq!(t.params(Point::ZERO, 1.0, None)["rays"].as_u64(), Some(0)); } + #[test] + fn graph_plot_measure_labels() { + use crate::testutil::*; + use vectorcraft_doc::Selection; + + let (d, _) = doc_with_rect(); + let s = Selection::default(); + let p = paint(); + let measure_count = |t: &GraphTool, c: &ToolContext| t.overlays(c).iter().filter(|o| matches!(o, Overlay::Measure { .. })).count(); + let measure_text = |t: &GraphTool, c: &ToolContext| { + t.overlays(c).iter().find_map(|o| match o { + Overlay::Measure { text, .. } => Some(text.clone()), + _ => None, + }) + }; + let mut t = GraphTool::new("columnGraph"); + let drag = |t: &mut GraphTool, c: &ToolContext| { + t.pointer(c, &PointerEvent::new(PointerKind::Down, 10.0, 10.0)); + t.pointer(c, &PointerEvent::new(PointerKind::Drag, 110.0, 60.0)); + }; + let on = ToolContext { measurement_labels: true, ..cx(&d, &s, &p) }; + drag(&mut t, &on); + assert_eq!(measure_count(&t, &on), 1); + let text = measure_text(&t, &on).unwrap_or_default(); + assert!(text.starts_with("W: "), "{text}"); + assert!(text.contains("\nH: "), "{text}"); + let off = ToolContext { measurement_labels: false, ..cx(&d, &s, &p) }; + let mut quiet = GraphTool::new("columnGraph"); + drag(&mut quiet, &off); + assert_eq!(measure_count(&quiet, &off), 0); + } + #[test] fn create_covers_both() { assert_eq!(create("flare").unwrap().id(), "flare"); diff --git a/crates/tools/src/guides.rs b/crates/tools/src/guides.rs index f24ce03e7f..7465545857 100644 --- a/crates/tools/src/guides.rs +++ b/crates/tools/src/guides.rs @@ -14,7 +14,8 @@ use std::sync::Arc; use vectorcraft_doc::hit::{HitOptions, hit_test}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind, OrientedBox, Selection}; use vectorcraft_geom::kurbo::ParamCurveNearest; -use vectorcraft_geom::{Affine, Line, ParamCurve, PathSeg, Point, Rect, SubPath, Vec2, constrain_angle_from}; +use vectorcraft_geom::{Affine, Line, ParamCurve, PathSeg, Point, Rect, Shape, SubPath, Vec2, constrain_angle_from}; +use vectorcraft_text::{FontDb, layout as layout_text}; use crate::bbox::Handle; use crate::{Overlay, ScreenFrame, ToolContext}; @@ -53,6 +54,7 @@ enum Kind { Artboard, Bleed, Guide, + Glyph, } impl Kind { @@ -64,6 +66,7 @@ impl Kind { Kind::Artboard => "artboard", Kind::Bleed => "bleed", Kind::Guide => "guide", + Kind::Glyph => "glyph", } } } @@ -158,6 +161,19 @@ fn span(r: &Rect, x: bool) -> (f64, f64) { if x { (r.x0, r.x1) } else { (r.y0, r.y1) } } +/// Along axis `x`, does dragging `handle` move the box's minimum edge (true) or maximum (false)? +fn resize_moves_min_edge(handle: Handle, x: bool) -> Option { + let (ax, ay) = handle.axes(); + if x && !ax || !x && !ay { + return None; + } + if x { + Some(matches!(handle, Handle::Left | Handle::TopLeft | Handle::BottomLeft)) + } else { + Some(matches!(handle, Handle::Top | Handle::TopLeft | Handle::TopRight)) + } +} + /// The objects a moved selection (`moving`) spaces itself evenly with, by their bounds: each /// visible object on a layer as a whole (a group too), and inside a group holding some of the /// moving objects its other objects, but a Shaper Group's original shapes. At most [`BUDGET`]. @@ -197,12 +213,21 @@ impl Targets { t } + /// Targets for scaling the selection: the other art, styled as `cx` asks, and with Smart Guides › + /// Spacing Guides the neighbours whose gaps the moving edge should match ([`Self::snap_scale`]). + pub fn for_scale(cx: &ToolContext) -> Self { + Self::for_move(cx, &cx.selection.objects) + } + /// Targets for a drawn point: the art in `visible` (all of it for None) but `exclude`, its /// anchors, centres, edges and path segments, its anchors in line too. The anchors and /// segments of `exclude` (the path being drawn, whose bounds grow with it) stay targets. - pub fn for_drawing(doc: &Document, exclude: &[NodeId], visible: Option) -> Self { + pub fn for_drawing(doc: &Document, exclude: &[NodeId], visible: Option, glyphs: bool) -> Self { let mut t = Self::collect_inner(doc, exclude, None, visible, Gather::Drawing); t.push_paths(doc, exclude, true); + if glyphs { + t.push_glyphs(doc, exclude, visible); + } t.index() } @@ -246,6 +271,51 @@ impl Targets { self.ys.push((a.y, a, Kind::Anchor)); } + /// Live-text baselines and glyph bounds (View › Snap to Glyph). + fn push_glyphs(&mut self, doc: &Document, exclude: &[NodeId], visible: Option) { + let skip: HashSet = exclude.iter().copied().collect(); + let db = FontDb::global(); + let kind = Kind::Glyph; + let mut budget = BUDGET / 4; + walk_but(&doc.layers, &skip, &mut |n| { + if budget == 0 || !n.visible { + return; + } + let NodeKind::Text(t) = &n.kind else { return }; + let lay = layout_text(db, t); + let ink = t.xf.transform_rect_bbox(lay.bounds); + if !ink.is_finite() || ink.width() <= 0.0 || ink.height() <= 0.0 { + return; + } + if let Some(v) = visible + && ink.intersect(v).area() <= 0.0 + && !v.contains(ink.center()) + { + return; + } + let to_doc = |p: Point| t.xf * p; + for line in &lay.lines { + let at = to_doc(Point::new(line.x0, line.baseline)); + self.ys.push((at.y, at, kind)); + } + for g in &lay.glyphs { + if budget == 0 { + break; + } + let bb = g.outline.bounding_box(); + if !(bb.width() > 0.0 && bb.height() > 0.0) { + continue; + } + let r = t.xf.transform_rect_bbox(bb); + for p in [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)] { + self.xs.push((p.x, p, kind)); + self.ys.push((p.y, p, kind)); + } + budget -= 1; + } + }); + } + /// The same targets drawing their guides as the Smart Guides preferences in `cx` ask /// ([`GuideStyle::of`]). pub fn styled(mut self, cx: &ToolContext) -> Self { @@ -986,13 +1056,13 @@ impl Targets { (nx, ny, snap) = (c.0 + s * e.0, c.1 + s * e.1, found); } } - let out = Affine::translate(origin.to_vec2()) * Affine::scale_non_uniform(nx, ny) * Affine::translate(-origin.to_vec2()); + let mut out = Affine::translate(origin.to_vec2()) * Affine::scale_non_uniform(nx, ny) * Affine::translate(-origin.to_vec2()); let (hit_x, hit_y, on) = snap; if let Some((q, k)) = on { return (out, self.label(q, k.label()).into_iter().collect()); } // The lines run from the target's own point across the resized box, on the page. - let nr = (to_doc * out).transform_rect_bbox(r); + let mut nr = (to_doc * out).transform_rect_bbox(r); let mut ov = vec![]; if let Some((x, from)) = hit_x { ov.extend(self.line(Point::new(x, from.y.min(nr.y0)), Point::new(x, from.y.max(nr.y1)))); @@ -1003,6 +1073,38 @@ impl Targets { if hit_x.is_some() || hit_y.is_some() { ov.extend(self.label(to_doc * (out * handle.pos(r)), "align")); } + if !self.boxes.is_empty() && !from_center { + let aligned = [hit_x.is_some(), hit_y.is_some()]; + for (is_x, lined_up) in [(true, aligned[0]), (false, aligned[1])] { + if lined_up { + continue; + } + let Some(moves_min) = resize_moves_min_edge(handle, is_x) else { continue }; + if let Some((shift, gaps)) = self.even_spacing(nr, is_x, tol) { + let (lo, hi) = span(&nr, is_x); + let len = hi - lo; + let new_len = if moves_min { hi - (lo + shift) } else { hi + shift - lo }; + if len > 1e-9 && new_len > 1e-9 { + let f = new_len / len; + let (ax, ay) = handle.axes(); + if is_x { + nx *= f; + if proportional && ay { + ny *= f; + } + } else { + ny *= f; + if proportional && ax { + nx *= f; + } + } + out = Affine::translate(origin.to_vec2()) * Affine::scale_non_uniform(nx, ny) * Affine::translate(-origin.to_vec2()); + nr = (to_doc * out).transform_rect_bbox(r); + ov.extend(gaps.into_iter().flat_map(|g| self.gap_marks(g, is_x, tol))); + } + } + } + } (out, ov) } } @@ -1222,6 +1324,7 @@ struct SnapKey { exclude: Vec, screen: Option, view: [bool; 5], + snap_to_glyph: bool, style: GuideStyle, tolerances: [f64; 2], } @@ -1233,6 +1336,7 @@ impl SnapKey { exclude: exclude.to_vec(), screen: cx.screen, view: [cx.smart_guides, cx.snap_to_point, cx.snap_to_pixel, cx.snap_to_grid, cx.guides], + snap_to_glyph: cx.snap_to_glyph && cx.alignment_guides, style: GuideStyle::of(cx), tolerances: [cx.snapping_tolerance, cx.snap_tolerance], } @@ -1290,7 +1394,7 @@ impl DrawSnap { } fn gather(&mut self, cx: &ToolContext, key: SnapKey) { - let snap = PointSnap::new(cx, || Targets::for_drawing(cx.doc, &key.exclude, visible(cx))); + let snap = PointSnap::new(cx, || Targets::for_drawing(cx.doc, &key.exclude, visible(cx), key.snap_to_glyph)); self.targets = Some((Some(key), snap)); } @@ -1334,7 +1438,7 @@ pub fn snap_pick(cx: &ToolContext, p: Point) -> (Point, Vec) { } let tol = if cx.smart_guides { cx.snap_tol() } else { cx.tol(cx.snap_tolerance) }; let mut roots = cx.selection.objects.clone(); - roots.extend(hit_test(cx.doc, p, HitOptions { tol, ..cx.hit_options() }).map(|h| h.leaf)); + roots.extend(hit_test(cx.doc, p, HitOptions { tol, skip_guides: false, ..cx.hit_options() }).map(|h| h.leaf)); let near = Rect::new(p.x - tol, p.y - tol, p.x + tol, p.y + tol); Targets::points_near(cx.doc, &roots, near).styled(cx).snap_point(p, tol) } @@ -1494,6 +1598,36 @@ mod tests { assert_eq!((dv, lines(&ov)), (Vec2::ZERO, 0)); } + /// Smart Guides › Spacing Guides (#394): resizing by a side handle snaps the moving edge to the + /// same gap as the neighbours in its row, with the gaps marked. + #[test] + fn spacing_guides_resize_snaps_the_moving_edge_to_equal_gaps() { + use crate::bbox::scale_for_drag; + use vectorcraft_doc::{Appearance, Node}; + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + for r in [Rect::new(20.0, 300.0, 60.0, 340.0), Rect::new(80.0, 300.0, 120.0, 340.0)] { + let id = d.alloc_id(); + d.insert(Some(l), 0, Node::path(id, vectorcraft_geom::shapes::rectangle(r), Appearance::default_art())).unwrap(); + } + let r = Rect::new(141.0, 305.0, 181.0, 345.0); + let id = d.alloc_id(); + d.insert(Some(l), 0, Node::path(id, vectorcraft_geom::shapes::rectangle(r), Appearance::default_art())).unwrap(); + let s = Selection { objects: vec![id], ..Default::default() }; + let t = Targets::for_scale(&cx(&d, &s, &paint())); + let (a, ov) = t.snap_scale( + &OrientedBox::aligned(r), + Handle::Left, + scale_for_drag(r, Handle::Left, Point::new(139.0, 325.0), false, false), + false, + false, + 4.0, + ); + assert_eq!(a.transform_rect_bbox(r).x0, 140.0, "20 pt from the second square"); + let magenta = |o: &Overlay| matches!(o, Overlay::Line { color, .. } if *color == MAGENTA); + assert!(ov.iter().any(magenta), "{ov:?}"); + } + /// Preferences › Smart Guides › Display Options (#394): the colour, and Alignment Guides and /// Anchor/Path Labels off, change what shows and never where a point lands. #[test] @@ -1569,7 +1703,7 @@ mod tests { || t.segments.iter().any(|(_, s)| s.start() == corner || s.end() == corner) }; assert!(!gives_corner(&Targets::collect(&d, &[], None))); - assert!(!gives_corner(&Targets::for_drawing(&d, &[], None))); + assert!(!gives_corner(&Targets::for_drawing(&d, &[], None, false))); assert!(!gives_corner(&Targets::for_anchor_drag(&d, &Selection::default()))); assert!(!gives_corner(&Targets::for_handle(&d, face))); assert!(!object_boxes(&d, &[face]).contains(&Rect::new(0.0, 300.0, 150.0, 400.0)), "the source shapes' bounds"); @@ -1661,7 +1795,7 @@ mod tests { let (d, _) = doc_with_rect(); let (s, p) = (Selection::default(), paint()); let c = cx(&d, &s, &p); - let t = Targets::for_drawing(&d, &[], None).styled(&c); + let t = Targets::for_drawing(&d, &[], None, false).styled(&c); // The rect is 100..200: its corner, a point on its side, and in line with an anchor. let (q, ov) = t.snap_from(Point::new(202.0, 198.0), None, 4.0); assert_eq!((q, labels(&ov)), (Point::new(200.0, 200.0), vec!["anchor"])); @@ -1715,7 +1849,7 @@ mod tests { d.guides.push(vectorcraft_doc::Guide::new(false, 150.0)); let (s, p) = (Selection::default(), paint()); let c = ToolContext { guides: true, ..cx(&d, &s, &p) }; - let t = Targets::for_drawing(&d, &[], None).styled(&c).with_rulers(&c); + let t = Targets::for_drawing(&d, &[], None, false).styled(&c).with_rulers(&c); let (q, ov) = t.snap_from(Point::new(152.0, 101.5), None, 4.0); assert!((q - Point::new(150.0, 100.0)).hypot() < 1e-9, "{q:?}"); assert_eq!(labels(&ov), ["intersect"]); @@ -1762,7 +1896,7 @@ mod tests { let mut s = Selection::default(); s.set([id]); s.anchors.insert(id, [(0, 1)].into_iter().collect()); - for t in [Targets::collect(&d, &[], None), Targets::for_drawing(&d, &[id], None), Targets::for_anchor_drag(&d, &s)] { + for t in [Targets::collect(&d, &[], None), Targets::for_drawing(&d, &[id], None, false), Targets::for_anchor_drag(&d, &s)] { for q in (0..40).flat_map(|i| (0..40).map(move |j| Point::new(i as f64 * 12.7, j as f64 * 11.3))) { let scan = t.points.iter().copied().filter(|(a, _)| a.distance(q) <= 6.0).min_by(|a, b| a.0.distance(q).total_cmp(&b.0.distance(q))); assert_eq!(t.nearest_point(q, 6.0).map(|h| h.0.distance(q)), scan.map(|h| h.0.distance(q)), "{q:?}"); diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 450bf75f7c..81e6f6a541 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -23,6 +23,7 @@ pub mod intertwine; pub mod meshblend; pub mod meshedit; pub mod mirror; +pub mod objects_on_path; pub mod params; pub mod pathtype; pub mod pen; @@ -251,6 +252,8 @@ pub struct ToolContext<'a> { /// points (a transform's reference point) land on anchors and ruler guides within /// [`Self::snap_tolerance`]. pub snap_to_point: bool, + /// View → Snap to Glyph: drawn points snap to live-text baselines and glyph bounds (with Smart Guides). + pub snap_to_glyph: bool, /// View → Show Corner Widget: paths show draggable Live Corners widgets in their corners. pub corner_widgets: bool, /// Which paint proxy is in front (true = Fill): the one the Gradient tool edits. @@ -262,6 +265,8 @@ pub struct ToolContext<'a> { pub appearance_item: Option, /// General → Constrain Angle (degrees): Shift constrains drags to 45° steps from it. pub constrain_angle: f64, + /// General → Keyboard Increment: arrow-key nudges in document units (Shift multiplies by 10). + pub keyboard_increment: f64, /// The selected freeform gradient point (`paint.freeform.selectPoint`), marked on the /// freeform annotator. pub freeform_point: Option, @@ -379,6 +384,11 @@ impl ToolContext<'_> { pub fn offset_label(&self, dx: f64, dy: f64) -> String { format!("dX: {}\ndY: {}", self.len(dx), self.len(dy)) } + /// A segment label while drawing: distance, angle and offsets between two points. + pub fn segment_measure_label(&self, a: Point, b: Point) -> String { + let (dist, ang, dx, dy) = xform::measure(a, b); + format!("D: {}\nAngle: {ang:.1}°\n{}", self.len(dist), self.offset_label(dx, dy)) + } /// What Snap to Grid snaps to: the grid's subdivisions (or its lines without any). pub fn grid_step(&self) -> f64 { self.doc.grid.spacing / self.doc.grid.subdivisions.max(1) as f64 @@ -402,6 +412,7 @@ impl ToolContext<'_> { path_only: self.path_only, type_path_only: self.type_path_only, scope: self.isolation, + skip_guides: !self.guides, } } } @@ -516,6 +527,9 @@ pub enum Cursor { BlendObject, /// The Blend tool over an anchor point (the blend starts there): a crosshair with a target. BlendAnchor, + /// The Objects on Path tool over a path the selected objects can attach to (a click attaches + /// them). + ObjectsOnPath, /// Over a bracket of selected type on a path (a drag moves it): the arrow with a bracket. PathBracket, /// Over the type widget of selected type (a double-click converts point type to area type and @@ -691,6 +705,7 @@ impl Cursor { | Cursor::Shaper | Cursor::LivePaintBucket | Cursor::Measure + | Cursor::ObjectsOnPath | Cursor::PrintTiling | Cursor::SymbolSprayer | Cursor::SymbolShifter @@ -809,6 +824,7 @@ pub fn create(id: &str) -> Box { .or_else(|| cropimage::create(other)) .or_else(|| cut::create(other)) .or_else(|| intertwine::create(other)) + .or_else(|| objects_on_path::create(other)) .or_else(|| touchtype::create(other)) .unwrap_or_else(|| Box::new(NoopTool(tool_info(other).map(|t| t.id).unwrap_or("selection")))), } @@ -920,11 +936,13 @@ pub(crate) mod testutil { show_bbox: true, snap_to_pixel: false, snap_to_point: true, + snap_to_glyph: false, corner_widgets: true, fill_active: true, gradient_stop: None, appearance_item: None, constrain_angle: 0.0, + keyboard_increment: 1.0, freeform_point: None, raster_sample: 1, preview_bounds: false, diff --git a/crates/tools/src/meshblend.rs b/crates/tools/src/meshblend.rs index 4253ed530f..2b3127529f 100644 --- a/crates/tools/src/meshblend.rs +++ b/crates/tools/src/meshblend.rs @@ -190,7 +190,7 @@ impl Tool for MeshTool { if cx.selection.objects != [g.id] && cx.doc.node(g.id).is_some_and(|n| matches!(n.kind, NodeKind::Mesh(_))) { out.push(Action::Exec("select.set".into(), json!({"ids": [g.id.0]}))); } - out.extend(self.edit.press(g)); + out.extend(self.edit.press(cx, g)); return out; } self.edit.unfocus(); diff --git a/crates/tools/src/meshedit.rs b/crates/tools/src/meshedit.rs index adb3adcd3a..d9fbd5cc87 100644 --- a/crates/tools/src/meshedit.rs +++ b/crates/tools/src/meshedit.rs @@ -8,7 +8,7 @@ use std::borrow::Cow; use serde_json::{Value, json}; use vectorcraft_doc::live::{GradientMesh, envelope_grid}; use vectorcraft_doc::{EnvelopeKind, Node, NodeId, NodeKind}; -use vectorcraft_geom::Point; +use vectorcraft_geom::{Point, Vec2}; use crate::{Action, Overlay, ToolContext}; @@ -35,12 +35,21 @@ pub struct MeshGrab { pub handle: Option, } +/// An in-progress mesh point or handle drag. +struct ActiveDrag { + grab: MeshGrab, + /// Where the grabbed point or handle was when the drag began. + origin: Point, + /// The current drag position (preview target); set on the first `drag_to`. + at: Option, +} + /// Point and handle drags on meshes. #[derive(Default)] pub struct MeshEdit { /// The point last clicked: its handles show and can be dragged. focus: Option<(NodeId, usize)>, - drag: Option, + drag: Option, } impl MeshEdit { @@ -63,15 +72,23 @@ impl MeshEdit { } /// Start dragging `grab` (its point takes the focus). - pub fn press(&mut self, grab: MeshGrab) -> Vec { + pub fn press(&mut self, cx: &ToolContext, grab: MeshGrab) -> Vec { self.focus = Some((grab.id, grab.index)); - self.drag = Some(grab); + let mut origin = Point::ZERO; + if let Some(grid) = cx.doc.node(grab.id).and_then(grid_of) + && let Some(q) = grid.points.get(grab.index) + { + origin = if let Some(h) = grab.handle { q.p + q.handles[h] } else { q.p }; + } + self.drag = Some(ActiveDrag { grab, origin, at: None }); vec![Action::Begin("Move Mesh Point".into())] } /// The preview of a drag to `p` (`None` when nothing is being dragged). - pub fn drag_to(&self, p: Point) -> Option> { - let g = self.drag?; + pub fn drag_to(&mut self, p: Point) -> Option> { + let d = self.drag.as_mut()?; + d.at = Some(p); + let g = d.grab; let mut params = json!({"id": g.id.0, "index": g.index, "x": p.x, "y": p.y}); if let Some(h) = g.handle { params["handle"] = json!(h); @@ -109,6 +126,13 @@ impl MeshEdit { out.push(Overlay::Line { a: q.p, b: q.p + *h, color: FEEDBACK, dashed: false }); out.push(Overlay::Handle { p: q.p + *h, color: FEEDBACK }); } + if cx.measurement_labels + && let Some(d) = &self.drag + && let Some(at) = d.at + { + let delta = at - d.origin; + out.push(Overlay::Measure { p: at + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: cx.offset_label(delta.x, delta.y) }); + } out } } @@ -188,4 +212,20 @@ mod tests { ); assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 90.0, 210.0)), vec![Action::Commit]); } + + #[test] + fn mesh_drag_honors_measurement_labels() { + let (d, _e) = doc_with_envelope(); + let (s, p) = (Selection::default(), paint()); + let base = cx(&d, &s, &p); + let on = ToolContext { measurement_labels: true, ..base }; + let off = ToolContext { measurement_labels: false, ..base }; + let mut t = crate::meshblend::create("mesh").unwrap(); + t.pointer(&on, &PointerEvent::new(PointerKind::Down, 200.0, 100.0)); + assert!(!t.overlays(&on).iter().any(|o| matches!(o, Overlay::Measure { .. }))); + t.pointer(&on, &PointerEvent::new(PointerKind::Drag, 210.0, 90.0)); + let want = on.offset_label(10.0, -10.0); + 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 { .. }))); + } } diff --git a/crates/tools/src/objects_on_path.rs b/crates/tools/src/objects_on_path.rs new file mode 100644 index 0000000000..e7db500df0 --- /dev/null +++ b/crates/tools/src/objects_on_path.rs @@ -0,0 +1,159 @@ +//! The Objects on Path tool (#2545): a click on a path attaches the selected objects to it +//! (`object.objectsOnPath.attach`). A path they can attach to is highlighted under the pointer, +//! and the pointer shows [`Cursor::ObjectsOnPath`] over it. +//! +//! Behavior: . + +use serde_json::json; +use vectorcraft_doc::NodeId; +use vectorcraft_doc::objects_on_path::{attachable_path, is_objects_on_path}; +use vectorcraft_geom::{BezPath, Point}; + +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; + +/// The highlight of the path under the pointer. +const HIGHLIGHT: [u8; 3] = [0x4f, 0x9d, 0xff]; + +/// The path a click at `p` attaches the selected objects to: the path object hit there, when it can +/// take objects, is in no Objects on Path group, and something else is selected. +pub fn target(cx: &ToolContext, p: Point) -> Option<(NodeId, BezPath)> { + let h = vectorcraft_doc::hit::hit_test(cx.doc, p, cx.hit_options())?; + let n = cx.doc.node(h.leaf)?; + let path = attachable_path(n)?; + if h.ancestry.iter().filter(|a| **a != h.leaf).any(|a| cx.doc.node(*a).is_some_and(is_objects_on_path)) { + return None; + } + cx.selection.objects.iter().any(|id| *id != h.leaf).then(|| (h.leaf, path.to_bezpath())) +} + +#[derive(Default)] +pub struct ObjectsOnPathTool { + /// The path under the pointer the selection can attach to, and its outline. + hover: Option<(NodeId, BezPath)>, + /// Where the press was, while the button is down. + press: Option, +} + +impl Tool for ObjectsOnPathTool { + fn id(&self) -> &'static str { + "objectsOnPath" + } + + fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + let p = ev.pos; + match ev.kind { + PointerKind::Move => { + self.hover = target(cx, p); + vec![] + } + PointerKind::Down => { + self.press = Some(p); + vec![] + } + PointerKind::Up => { + // A press that moved away is not a click. + let Some(start) = self.press.take().filter(|q| q.distance(p) < cx.tol(3.0)) else { return vec![] }; + let Some((path, _)) = target(cx, start) else { return vec![] }; + self.hover = None; + vec![Action::Exec("object.objectsOnPath.attach".into(), json!({ "path": path.0 }))] + } + _ => vec![], + } + } + + fn overlays(&self, _cx: &ToolContext) -> Vec { + self.hover.iter().map(|(_, path)| Overlay::Path { path: path.clone(), color: HIGHLIGHT, width: 2.0, dashed: false }).collect() + } + + fn cursor(&self, cx: &ToolContext, p: Point, _mods: Mods) -> Cursor { + if target(cx, p).is_some() { Cursor::ObjectsOnPath } else { Cursor::Arrow } + } + + /// Escape while the button is down cancels the click: the release attaches nothing. + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + if key == ToolKey::Escape { + self.press = None; + self.hover = None; + } + vec![] + } + + fn busy(&self) -> bool { + self.press.is_some() + } +} + +pub fn create(id: &str) -> Option> { + (id == "objectsOnPath").then(|| Box::new(ObjectsOnPathTool::default()) as Box) +} + +#[cfg(test)] +mod tests { + use vectorcraft_doc::{Appearance, Document, Node, NodeKind, Selection}; + use vectorcraft_geom::{Rect, shapes}; + + use super::*; + use crate::testutil::{cx, paint}; + + fn doc() -> (Document, NodeId, NodeId) { + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let line = d.alloc_id(); + let square = d.alloc_id(); + d.insert(Some(l), 0, Node::path(line, shapes::line(Point::new(0.0, 300.0), Point::new(400.0, 300.0)), Appearance::default_art())).unwrap(); + d.insert(Some(l), 1, Node::path(square, shapes::rectangle(Rect::new(50.0, 50.0, 70.0, 70.0)), Appearance::default_art())).unwrap(); + (d, line, square) + } + + fn ev(kind: PointerKind, x: f64, y: f64) -> PointerEvent { + PointerEvent::new(kind, x, y) + } + + #[test] + fn a_click_on_a_path_attaches_the_selection_to_it() { + let (d, line, square) = doc(); + let mut sel = Selection::default(); + sel.set([square]); + let paint = paint(); + let cx = cx(&d, &sel, &paint); + let mut t = ObjectsOnPathTool::default(); + let on = Point::new(200.0, 300.0); + assert_eq!(t.cursor(&cx, on, Mods::default()), Cursor::ObjectsOnPath); + assert_eq!(t.cursor(&cx, Point::new(200.0, 500.0), Mods::default()), Cursor::Arrow, "away from paths"); + t.pointer(&cx, &ev(PointerKind::Move, on.x, on.y)); + assert_eq!(t.overlays(&cx).len(), 1, "the path is highlighted"); + t.pointer(&cx, &ev(PointerKind::Down, on.x, on.y)); + let acts = t.pointer(&cx, &ev(PointerKind::Up, on.x, on.y)); + assert!(matches!(acts.as_slice(), [Action::Exec(id, p)] if id == "object.objectsOnPath.attach" && p["path"] == line.0), "{acts:?}"); + } + + #[test] + fn escape_during_the_press_cancels_the_click() { + let (d, _, square) = doc(); + let mut sel = Selection::default(); + sel.set([square]); + let paint = paint(); + let cx = cx(&d, &sel, &paint); + let mut t = ObjectsOnPathTool::default(); + t.pointer(&cx, &ev(PointerKind::Move, 200.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 300.0)); + assert!(t.busy()); + t.key(&cx, ToolKey::Escape, Mods::default()); + assert!(!t.busy() && t.overlays(&cx).is_empty()); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 200.0, 300.0)).is_empty(), "the release attaches nothing"); + } + + #[test] + fn nothing_attaches_without_other_objects_selected() { + let (d, line, _) = doc(); + let mut sel = Selection::default(); + sel.set([line]); + let paint = paint(); + let cx = cx(&d, &sel, &paint); + let mut t = ObjectsOnPathTool::default(); + assert_eq!(t.cursor(&cx, Point::new(200.0, 300.0), Mods::default()), Cursor::Arrow); + t.pointer(&cx, &ev(PointerKind::Down, 200.0, 300.0)); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 200.0, 300.0)).is_empty()); + assert!(matches!(d.node(line).map(|n| &n.kind), Some(NodeKind::Path { .. }))); + } +} diff --git a/crates/tools/src/pathtype.rs b/crates/tools/src/pathtype.rs index 2b251f7acd..21fdaefc93 100644 --- a/crates/tools/src/pathtype.rs +++ b/crates/tools/src/pathtype.rs @@ -226,6 +226,11 @@ impl BracketDrag { Value::Object(m) } + /// The drag has left the click: the bracket is moving along the path. + pub fn adjusting(&self) -> bool { + self.began + } + pub fn finish(self) -> Vec { if self.began { vec![Action::Commit] } else { vec![] } } diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs index f578d8e318..e1a8eccf58 100644 --- a/crates/tools/src/pen.rs +++ b/crates/tools/src/pen.rs @@ -27,7 +27,7 @@ use serde_json::json; use vectorcraft_doc::{NodeId, NodeKind}; -use vectorcraft_geom::{BezPath, Point}; +use vectorcraft_geom::{BezPath, Point, Vec2}; use crate::direct::hit_handle; use crate::draw2::{AnchorTool, editable_paths}; @@ -396,6 +396,9 @@ impl Tool for PenTool { bp.line_to(h); } 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) }); + } } o.extend_from_slice(self.snap.guides()); o @@ -1206,6 +1209,9 @@ mod tests { assert!(o.iter().any( |o| matches!(o, Overlay::Path { path, .. } if path.elements().last().and_then(|e| e.end_point()) == Some(Point::new(150.0, 318.0))) )); + let from = Point::new(60.0, 300.0); + let to = Point::new(150.0, 318.0); + assert!(o.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == &cx.segment_measure_label(from, to)))); let a = click(&mut t, &cx, 152.0, 318.0, Mods::default()); assert_eq!(a[1], Action::Preview("path.appendAnchor".into(), json!({"id": id.0, "x": 150.0, "y": 318.0}))); let shift = Mods { shift: true, ..Mods::default() }; diff --git a/crates/tools/src/pie.rs b/crates/tools/src/pie.rs index 957c8d3714..e173d0a556 100644 --- a/crates/tools/src/pie.rs +++ b/crates/tools/src/pie.rs @@ -187,8 +187,8 @@ impl PieDrag { } /// The angle readout next to the pointer. - pub fn overlays(&self) -> Vec { - if !self.began { + pub fn overlays(&self, cx: &ToolContext) -> Vec { + if !self.began || !cx.measurement_labels { return vec![]; } vec![Overlay::Measure { p: self.at, text: format!("{:.1}°", self.angle) }] @@ -275,6 +275,8 @@ mod tests { assert!(v.get("pieStart").is_none(), "{v}"); assert!(t.transforming()); assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == "90.0°"))); + let quiet = ToolContext { measurement_labels: false, ..cx(&d, &s, &p) }; + assert!(!t.overlays(&quiet).iter().any(|o| matches!(o, Overlay::Measure { .. }))); // Below the center and to the left: 225°, on the ellipse's own angles (not the page's). let a = t.pointer(&c, &ev(PointerKind::Drag, Point::new(100.0, 200.0))); assert!(matches!(&a[0], Action::Preview(_, v) if (v["pieEnd"].as_f64().unwrap() - 225.0).abs() < 1e-9), "{a:?}"); diff --git a/crates/tools/src/printtiling.rs b/crates/tools/src/printtiling.rs index 7a443ba6ce..b4e0e06d0c 100644 --- a/crates/tools/src/printtiling.rs +++ b/crates/tools/src/printtiling.rs @@ -79,7 +79,7 @@ impl Tool for PrintTilingTool { fn overlays(&self, cx: &ToolContext) -> Vec { match self.drag { // How far the corner is from the artboard's. - Some((_, Some(r))) if self.began => { + Some((_, Some(r))) if self.began && cx.measurement_labels => { vec![Overlay::Measure { p: self.last, text: cx.offset_label(self.last.x - r.x0, self.last.y - r.y0) }] } _ => vec![], @@ -122,6 +122,8 @@ mod tests { let a = t.pointer(&c, &ev(PointerKind::Drag, 2.0, 497.0)); assert_eq!(a, vec![Action::Preview("print.tiling.set".into(), json!({"origin": [0.0, 500.0], "artboard": 0}))]); assert!(matches!(t.overlays(&c).as_slice(), [Overlay::Measure { .. }])); + let quiet = ToolContext { measurement_labels: false, ..cx(&d, &s, &pd) }; + assert!(t.overlays(&quiet).is_empty()); assert_eq!(t.pointer(&c, &ev(PointerKind::Up, 2.0, 497.0)), vec![Action::Commit]); assert!(!t.busy()); // A click alone changes nothing; a double click resets. diff --git a/crates/tools/src/rulerguide.rs b/crates/tools/src/rulerguide.rs index 1f9bc8e479..faa6ab9c98 100644 --- a/crates/tools/src/rulerguide.rs +++ b/crates/tools/src/rulerguide.rs @@ -1,7 +1,9 @@ //! Ruler guides on the canvas. Dragged out of a ruler with any tool ([`NewGuide`]), a guide is //! made where it is released over the canvas: with the Artboard tool, an artboard guide of the //! active artboard. For the selection tools ([`GuideEdit`]), a press on a guide selects it (Shift -//! adds it to the selected guides or, released without a drag, takes it out); dragging moves the +//! adds it to the selected guides or, released without a drag, takes it out; a click on a guide +//! selected with objects makes it the key object Align lines them up on, `select.key`, and a +//! click on the key guide again cancels it); dragging moves the //! selected guides (Alt copies them), and a marquee selects the guides it crosses along with the //! art ([`marquee_select`]). A dragged guide snaps ([`GuideSnap`]): with Shift to the //! ruler's ticks, else to whole pixels, the grid, with Smart Guides the art's and the artboards' @@ -92,6 +94,9 @@ struct Drag { began: bool, /// Shift-pressed on a selected guide: released without a drag, it leaves the selection. deselect: bool, + /// Pressed (no Shift) on a guide selected with objects: released without a drag, it becomes + /// the key object Align lines them up on, or stops being it when it was. + key: bool, } /// Snapping for a dragged ruler guide, its targets gathered when the drag begins. @@ -246,6 +251,7 @@ impl GuideEdit { pointer: ev.pos, began: false, deselect: shift && selected, + key: !shift && selected && !cx.selection.is_empty(), }); self.snap = GuideSnap::default(); Some(match (selected, shift) { @@ -278,6 +284,11 @@ impl GuideEdit { vec![Action::Commit] } else if d.deselect { vec![Action::Exec("guide.select".into(), json!({ "indexes": [d.index], "toggle": true }))] + } else if d.key && cx.selection.key_guide == Some(d.index) { + // A click on the key guide again: no key. + vec![Action::Exec("select.key".into(), json!({}))] + } else if d.key { + vec![Action::Exec("select.key".into(), json!({ "guide": d.index }))] } else { vec![] } @@ -620,6 +631,43 @@ mod tests { assert_eq!(a[1], Action::Preview("guide.move".into(), json!({"dx": 0.0, "dy": 20.0, "copy": true}))); } + /// #2143: a click on a guide selected with objects makes it the key; on the key guide again, + /// no key. Alone (no objects), with Shift, or dragged, it doesn't. + #[test] + fn a_click_on_a_guide_selected_with_objects_makes_it_the_key() { + // The same document as doc_with_rect's, with the guides. + let (d, rect) = (guides_doc(), doc_with_rect().1); + let p = paint(); + let click = |s: &Selection, m: Mods| { + let c = cx(&d, s, &p); + let mut g = GuideEdit::default(); + let mut out = g.press(&c, &ev(PointerKind::Down, 302.0, 50.0, m)).unwrap(); + out.extend(g.pointer(&c, &ev(PointerKind::Up, 302.0, 50.0, m)).unwrap()); + out + }; + let mut s = Selection::default(); + s.set([rect]); + s.toggle_guide(0); + let make = Action::Exec("select.key".into(), json!({"guide": 0})); + assert_eq!(click(&s, Mods::default()), vec![make]); + s.key_guide = Some(0); + assert_eq!(click(&s, Mods::default()), vec![Action::Exec("select.key".into(), json!({}))], "the key guide again"); + let shift = Mods { shift: true, ..Default::default() }; + assert_eq!(click(&s, shift), vec![Action::Exec("guide.select".into(), json!({"indexes": [0], "toggle": true}))]); + s.set_guides([0]); + assert_eq!(click(&s, Mods::default()), vec![], "a guide alone has nothing to align"); + // Not selected yet: the first click selects it. + s.set([rect]); + assert_eq!(click(&s, Mods::default()), vec![Action::Exec("guide.select".into(), json!({"indexes": [0]}))]); + // A drag moves it. + s.toggle_guide(0); + let c = cx(&d, &s, &p); + let mut g = GuideEdit::default(); + g.press(&c, &ev(PointerKind::Down, 302.0, 50.0, Mods::default())); + g.pointer(&c, &ev(PointerKind::Drag, 340.0, 50.0, Mods::default())); + assert_eq!(g.pointer(&c, &ev(PointerKind::Up, 340.0, 50.0, Mods::default())), Some(vec![Action::Commit])); + } + #[test] fn dropped_on_its_ruler_the_guide_is_deleted() { let d = guides_doc(); @@ -663,8 +711,10 @@ mod tests { 2.0, Point::new(inch(0.01), inch(0.03)), Point::new(inch(3.07), inch(3.27)), - Point::new(inch(3.06), inch(3.28)), - inch(0.05), + // An inch ruler's ticks are binary fractions, so at zoom 2 they are 1/16 in + // apart, not the 0.05 in a decimal ladder gave (#2827). + Point::new(inch(3.0725), inch(3.28)), + inch(0.0625), ), ] } diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 7e969b0e68..be3f08da1c 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -48,9 +48,9 @@ enum State { /// Shift-pressed on this selected object: released without a drag, it leaves the /// selection. deselect: Option, - /// Pressed (no modifier) on this object of a selection of several: released without a - /// drag, it becomes the key object that Align aligns to if `can_be_key` allows it (the key - /// again: no key). + /// Pressed (no modifier) on this object of a selection of several, or of one with ruler + /// guides: released without a drag, it becomes the key object that Align aligns to if + /// `can_be_key` allows it (the key again: no key). key: Option, }, Scaling { @@ -424,6 +424,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::Bracket(b) => b.adjusting(), State::Mirror(d) => d.adjusting(), _ => false, } @@ -542,7 +543,7 @@ impl Tool for SelectionTool { // What the handle moves snaps as a dragged point does: to pixels or the // grid, else with Smart Guides to the other objects, else with Snap to // Point to their anchors; the ruler guides with Snap to Point. - self.targets = Some(PointSnap::new(cx, || Targets::collect(cx.doc, &cx.selection.objects, None))); + self.targets = Some(PointSnap::new(cx, || Targets::for_scale(cx))); self.state = State::Scaling { handle, bx, areas }; return vec![Action::Begin(label.into())]; } @@ -581,7 +582,7 @@ impl Tool for SelectionTool { } } else if !cx.selection.contains(top) { out.push(Action::Exec("select.set".into(), json!({ "ids": [top.0] }))); - } else if cx.selection.objects.len() > 1 && !m.cmd && !m.alt { + } else if (cx.selection.objects.len() > 1 || !cx.selection.guides.is_empty()) && !m.cmd && !m.alt { key = Some(top); } self.state = State::Moving { start: grab, began: false, deselect, key }; @@ -713,7 +714,7 @@ impl Tool for SelectionTool { match &self.state { State::Marquee { start, cur, .. } => o.push(Overlay::Marquee(Rect::from_points(*start, *cur))), State::Corner(c) => o.extend(c.overlays(cx)), - State::Pie(d) => o.extend(d.overlays()), + State::Pie(d) => o.extend(d.overlays(cx)), State::Loaded { press: Some((start, cur)), .. } => o.push(Overlay::Marquee(Rect::from_points(*start, *cur))), _ => {} } @@ -927,6 +928,22 @@ mod tests { assert!(t.transforming()); } + /// A type-on-path bracket drag is a transform, so the sharp selection box hides while the span moves. + #[test] + fn a_bracket_drag_counts_as_transforming_once_it_moves() { + let (d, id) = crate::testutil::doc_with_path_type(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = SelectionTool::default(); + assert!(!t.transforming()); + t.pointer(&cx, &ev(PointerKind::Down, 280.0, 290.0)); + assert!(!t.transforming(), "a press is still a click"); + t.pointer(&cx, &ev(PointerKind::Drag, 320.0, 290.0)); + assert!(t.transforming()); + } + /// #812: with Smart Guides on, hovering near an object's centre or an anchor labels it, and a /// press there grabs the object by that point. #[test] @@ -1425,7 +1442,8 @@ mod tests { } /// #541: a click on one object of a selection of several makes it the key object; a click on - /// the key again lets it go. A drag moves them all, a lone object has no key. + /// the key again lets it go. A drag moves them all, a lone object has no key unless ruler + /// guides are selected with it. #[test] fn a_click_on_a_selected_object_makes_it_the_key() { let (d, id) = doc_with_area_type(); @@ -1449,10 +1467,13 @@ mod tests { t.pointer(&c, &ev(PointerKind::Down, 150.0, 150.0)); t.pointer(&c, &ev(PointerKind::Drag, 170.0, 150.0)); assert_eq!(t.pointer(&c, &ev(PointerKind::Up, 170.0, 150.0)), vec![Action::Commit]); - // One object selected: a click on it does nothing. + // One object selected: a click on it does nothing, unless ruler guides are selected + // with it for it to be the key of (#2143). let mut one = Selection::default(); one.add(rect); assert!(click(&one, 150.0, 150.0).is_empty()); + one.guides = vec![0]; + assert_eq!(click(&one, 150.0, 150.0), vec![Action::Exec("select.key".into(), json!({"id": rect.0}))]); } /// In isolation mode a click makes only a selected top-level object the key, as `select.key` @@ -1679,6 +1700,38 @@ mod tests { assert_eq!(a, vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))]); } + /// #3036: with Lock Guides on, a guide object neither takes the press nor stops a marquee + /// from starting over it; with guides unlocked, the press still picks it. + #[test] + fn marquee_passes_through_locked_guide_objects() { + let (mut d, id) = doc_with_rect(); + let l = d.layers[0].id; + let g = d.alloc_id(); + let pts = [Point::new(20.0, 20.0), Point::new(400.0, 20.0), Point::new(400.0, 400.0), Point::new(20.0, 400.0)]; + let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&pts, true)); + let mut guide = vectorcraft_doc::Node::path(g, path, vectorcraft_doc::Appearance::default_art()); + let vectorcraft_doc::NodeKind::Path { guide: flag, .. } = &mut guide.kind else { panic!("a path") }; + *flag = true; + d.insert(Some(l), 1, guide).unwrap(); + let s = Selection::default(); + let p = paint(); + let locked = ToolContext { guides: false, ..cx(&d, &s, &p) }; + for (x, y) in [(20.0, 60.0), (50.0, 50.0)] { + let mut t = SelectionTool::default(); + assert!(t.pointer(&locked, &ev(PointerKind::Down, x, y)).is_empty(), "press at ({x}, {y})"); + t.pointer(&locked, &ev(PointerKind::Drag, 250.0, 250.0)); + assert!(matches!(t.state, State::Marquee { .. }), "press at ({x}, {y})"); + // The rectangle is rubber-band selected (the engine leaves locked guides out). + let a = t.pointer(&locked, &ev(PointerKind::Up, 250.0, 250.0)); + let Some(Action::Exec(c, v)) = a.first() else { panic!("press at ({x}, {y}): {a:?}") }; + assert_eq!(c, "select.set", "press at ({x}, {y})"); + assert!(v["ids"].as_array().unwrap().contains(&json!(id.0)), "press at ({x}, {y}): {a:?}"); + } + let unlocked = ToolContext { guides: true, ..cx(&d, &s, &p) }; + let mut t = SelectionTool::default(); + assert_eq!(t.pointer(&unlocked, &ev(PointerKind::Down, 20.0, 60.0)), vec![Action::Exec("select.set".into(), json!({"ids": [g.0]}))]); + } + #[test] fn handle_drag_scales() { let (d, id) = doc_with_rect(); diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index a035329471..e46bd15dcb 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -31,9 +31,13 @@ const ROWS: &[Row] = &[ (&["rectangularGrid"], None, &["rows", "columns", "rowSkew", "columnSkew", "frame", "fill"]), (&["polarGrid"], None, &["concentric", "radial", "concentricSkew", "radialSkew", "compound", "fill"]), (&["pencil", "paintbrush"], None, &["fidelity", "fill", "keepSelected", "editWithin", "closeWithin"]), + // Pencil Tool Options' Alt key toggles to Smooth Tool (the Paintbrush has no such option). + (&["pencil"], None, &["altSmooth"]), (&["smooth"], None, &["fidelity"]), (&["blobBrush", "eraser"], None, &["size"]), (&["blobBrush"], None, &["keepSelected", "mergeOnlySelection"]), + // Live Paint Selection Tool Options (`builder::LivePaintSelectionTool`). + (&["livePaintSelection"], None, &["selectFills", "selectStrokes", "color", "width"]), (&["polygon"], None, &["sides"]), (&["star"], None, &["points"]), (&["freeTransform"], None, &["constrain"]), diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index cb81263ec9..07593a72b5 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -8,7 +8,7 @@ //! the dragged corner snap to Smart Guides ([`DrawSnap`]), hovering before the press too. use serde_json::{Value, json}; -use vectorcraft_geom::{Point, Rect}; +use vectorcraft_geom::{Point, Rect, Vec2}; use crate::guides::{DrawSnap, Leave, square}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -251,15 +251,21 @@ impl Tool for ShapeTool { fn overlays(&self, cx: &ToolContext) -> Vec { let mut o = self.snap.guides().to_vec(); if let Some(s) = self.start.filter(|_| self.began && cx.measurement_labels) { - // A box's size as drawn (from its centre with Alt, square with Shift). - let (w, h) = match self.id { - "polygon" | "star" | "lineSegment" => ((self.last - s).x.abs(), (self.last - s).y.abs()), - _ => { - let r = drag_rect(s, self.last, self.mods); - (r.width(), r.height()) - } + let p = self.last + Vec2::new(cx.tol(12.0), cx.tol(12.0)); + let text = if self.id == "lineSegment" { + cx.segment_measure_label(s, self.last) + } else { + // A box's size as drawn (from its centre with Alt, square with Shift). + let (w, h) = match self.id { + "polygon" | "star" => ((self.last - s).x.abs(), (self.last - s).y.abs()), + _ => { + let r = drag_rect(s, self.last, self.mods); + (r.width(), r.height()) + } + }; + cx.size_label(w, h) }; - o.push(Overlay::Measure { p: self.last, text: cx.size_label(w, h) }); + o.push(Overlay::Measure { p, text }); } o } @@ -422,5 +428,8 @@ mod tests { let shift = Mods { shift: true, ..Mods::default() }; let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 203.0, 302.0).with_mods(shift)); assert!(matches!(&a[..], [_, Action::Preview(_, v)] if v["x2"] == 200.0 && (v["y2"].as_f64().unwrap() - 300.0).abs() < 1e-9), "{a:?}"); + let from = Point::new(300.0, 300.0); + let to = Point::new(200.0, 300.0); + assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == &cx.segment_measure_label(from, to)))); } } diff --git a/crates/tools/src/text.rs b/crates/tools/src/text.rs index 7918193cdd..db0e6e3f3a 100644 --- a/crates/tools/src/text.rs +++ b/crates/tools/src/text.rs @@ -633,7 +633,7 @@ impl Tool for TypeTool { edit::prev_word(&text, self.caret) } else { if lay.glyphs.iter().any(|g| g.rtl) { - vectorcraft_text::caret_horizontal(&lay, self.caret, false) + vectorcraft_text::caret_horizontal_cluster(&lay, &text, self.caret, false) } else { edit::prev_cluster(&text, self.caret) } @@ -653,7 +653,7 @@ impl Tool for TypeTool { edit::next_word(&text, self.caret) } else { if lay.glyphs.iter().any(|g| g.rtl) { - vectorcraft_text::caret_horizontal(&lay, self.caret, true) + vectorcraft_text::caret_horizontal_cluster(&lay, &text, self.caret, true) } else { edit::next_cluster(&text, self.caret) } diff --git a/crates/tools/src/text_tests.rs b/crates/tools/src/text_tests.rs index 6c94a07a53..2ca9196546 100644 --- a/crates/tools/src/text_tests.rs +++ b/crates/tools/src/text_tests.rs @@ -3,7 +3,8 @@ use super::*; use crate::testutil::{cx, paint}; -use vectorcraft_doc::{CharStyle, Document, Node, Selection}; +use vectorcraft_doc::{CharStyle, Document, Node, NodeKind, Selection, TextObject}; +use vectorcraft_text::FontDb; fn doc_with_text(text: &str) -> (Document, NodeId) { let mut d = Document::new(500.0, 500.0); @@ -44,6 +45,175 @@ fn apply(d: &mut Document, snapshot: &Document, acts: &[Action]) { } } +#[test] +fn type_arrows_keep_devanagari_clusters_with_an_rtl_suffix() { + // Use the text tests' installed-family order, requiring coverage of the unchanged Hindi input. + // The Hebrew suffix selects the Type tool's existing visual-arrow route. + let hindi = "हिन्दी"; + let second = "हि".len(); + assert_eq!((second, hindi.len()), (6, 18)); + let db = FontDb::global(); + let face = ["Kohinoor Devanagari", "ITF Devanagari", "Devanagari Sangam MN", "Noto Sans Devanagari", "Nirmala UI", "Mangal"] + .into_iter() + .filter_map(|name| db.face(name, "Regular").filter(|face| face.family == name)) + .find(|face| hindi.chars().all(|ch| face.covers(ch))); + let Some(face) = face else { + eprintln!("SKIPPED: type_arrows_keep_devanagari_clusters_with_an_rtl_suffix; no installed candidate font covers the Hindi input"); + return; + }; + assert!(hindi.chars().all(|ch| face.covers(ch)), "the selected face covers the unchanged Hindi prefix"); + let style = CharStyle { font_family: face.family.clone(), font_style: face.style.clone(), size: 20.0, ..Default::default() }; + + // The plain-LTR control runs first. Each case uses a fresh document and tool. + for (case, text, visual_route) in [("plain_ltr", "हिन्दी", false), ("mixed_rtl", "हिन्दी שלום", true)] { + let (mut d, id, mut tool) = editing(text); + let NodeKind::Text(t) = &mut d.node_mut(id).unwrap().kind else { panic!("text fixture") }; + for run in &mut t.runs { + run.style = style.clone(); + } + assert_eq!(t.plain_text(), text); + assert_eq!(&text[..hindi.len()], hindi); + let lay = vectorcraft_text::layout(db, t); + assert_eq!(lay.lines.len(), 1, "{case}: one ordinary horizontal line"); + assert!(!lay.vertical, "{case}: horizontal Type"); + let mut hindi_spans: Vec<_> = lay.glyphs.iter().filter(|g| g.byte < hindi.len()).map(|g| (g.byte, g.len)).collect(); + hindi_spans.sort_unstable(); + hindi_spans.dedup(); + // Raw shaping spans are diagnostic; editing boundaries do not depend on their count. + assert!(!hindi_spans.is_empty(), "{case}: Hindi glyph source spans are present"); + for glyph in lay.glyphs.iter().filter(|g| g.byte < hindi.len()) { + let used = db.face_by_id(glyph.font_id).expect("the Hindi glyph's loaded face"); + assert!(used.file_data() == face.file_data(), "{case}: Hindi uses the selected face bytes"); + assert_eq!(used.face_index(), face.face_index(), "{case}: Hindi uses the selected face index"); + assert_ne!(glyph.gid, 0, "{case}: Hindi glyph is present"); + assert!(!glyph.rtl, "{case}: Hindi prefix remains LTR"); + } + assert_eq!(lay.glyphs.iter().any(|g| g.rtl), visual_route, "{case}: actual Type arrow-route predicate"); + if visual_route { + assert!(lay.glyphs.iter().any(|g| g.rtl && g.byte > hindi.len()), "{case}: the ordinary suffix supplies RTL glyphs"); + } + assert_eq!(edit::next_cluster(text, second), hindi.len(), "{case}: logical cluster end"); + assert_eq!(edit::prev_cluster(text, hindi.len()), second, "{case}: logical cluster start"); + tool.caret = second; + tool.anchor = second; + assert_eq!(tool.editing, Some(id)); + assert_eq!(tool.sel(), (second, second), "{case}: collapsed caret before Right"); + assert!(tool.typing.is_none(), "{case}: no pending typing session"); + key(&mut tool, &d, ToolKey::Right, Mods::default()); + assert_eq!((tool.caret, tool.anchor), (hindi.len(), hindi.len()), "{case}: Right must move 6 -> 18 across the Hindi cluster"); + key(&mut tool, &d, ToolKey::Left, Mods::default()); + assert_eq!((tool.caret, tool.anchor), (second, second), "{case}: Left must move 18 -> 6 across the Hindi cluster"); + } +} + +#[test] +fn type_arrows_keep_devanagari_clusters_across_wrapped_lines() { + use vectorcraft_doc::{Composer, Justify}; + use vectorcraft_geom::{Affine, PathData}; + + // Use the installed-family order and unchanged Hindi input from the single-line test. + // Shaping and wrapping capabilities vary by face; an eligibility skip is not arrow coverage. + let hindi = "हिन्दी"; + let text = "हिन्दी שלום"; + let second = "हि".len(); + let split = "हिन्".len(); + assert_eq!((second, split, hindi.len()), (6, 12, 18)); + let db = FontDb::global(); + let face = ["Kohinoor Devanagari", "ITF Devanagari", "Devanagari Sangam MN", "Noto Sans Devanagari", "Nirmala UI", "Mangal"] + .into_iter() + .filter_map(|name| db.face(name, "Regular").filter(|face| face.family == name)) + .find(|face| hindi.chars().all(|ch| face.covers(ch))); + let Some(face) = face else { + eprintln!("SKIPPED: type_arrows_keep_devanagari_clusters_across_wrapped_lines; no installed candidate font covers the Hindi input"); + return; + }; + let style = CharStyle { font_family: face.family.clone(), font_style: face.style.clone(), size: 20.0, ..Default::default() }; + let (mut d, id, mut tool) = editing(text); + let NodeKind::Text(t) = &mut d.node_mut(id).unwrap().kind else { panic!("text fixture") }; + for run in &mut t.runs { + run.style = style.clone(); + } + t.para.justify = Justify::Left; + t.para.composer = Composer::SingleLine; + t.para.hyphenate = false; + assert_eq!(t.plain_text(), text); + assert_eq!(&text[..hindi.len()], hindi); + + // Measure once on the selected face. No width sweep or invented line endpoints. + let natural = vectorcraft_text::layout(db, t); + assert_eq!(natural.lines.len(), 1, "setup: natural point text is a single line"); + assert!(!natural.vertical, "setup: horizontal text"); + let hindi_glyphs: Vec<_> = natural.glyphs.iter().filter(|g| g.byte < hindi.len()).collect(); + assert!(!hindi_glyphs.is_empty(), "setup: actual Hindi glyphs exist"); + for glyph in &hindi_glyphs { + let used = db.face_by_id(glyph.font_id).expect("the Hindi glyph's loaded face"); + assert!(used.file_data() == face.file_data(), "setup: Hindi uses the selected face bytes"); + assert_eq!(used.face_index(), face.face_index(), "setup: Hindi uses the selected face index"); + assert_ne!(glyph.gid, 0, "setup: Hindi glyph is present"); + assert!(!glyph.rtl, "setup: Hindi prefix is LTR"); + assert!(glyph.len > 0 && glyph.byte + glyph.len <= hindi.len(), "setup: Hindi glyph source range"); + assert!( + text.is_char_boundary(glyph.byte) && text.is_char_boundary(glyph.byte + glyph.len), + "setup: glyph source ranges are UTF-8 boundaries" + ); + } + let prefix_width: f64 = hindi_glyphs.iter().filter(|g| g.byte < split).map(|g| g.advance).sum(); + let split_width: f64 = hindi_glyphs.iter().filter(|g| g.byte == split).map(|g| g.advance).sum(); + assert!(prefix_width.is_finite() && prefix_width > 0.0, "setup: prefix has positive finite advance"); + assert!(split_width.is_finite(), "setup: the internal raw-group advance is finite"); + if split_width <= 0.0 { + eprintln!( + "SKIPPED: type_arrows_keep_devanagari_clusters_across_wrapped_lines; layout capability: the selected face has no positive-advance raw group at internal byte {split}" + ); + return; + } + let width = prefix_width + split_width * 0.5; + assert!(width.is_finite() && width > prefix_width && width < prefix_width + split_width, "setup: one measured width separates the raw groups"); + + t.kind = TextKind::Area { frame: PathData::from_bezpath(&Rect::new(0.0, 0.0, width, 500.0).to_path(0.1)) }; + t.xf = Affine::IDENTITY; + assert_eq!((t.area.rows, t.area.columns, t.area.inset), (1, 1, 0.0)); + assert_eq!((t.para.left_indent, t.para.first_line_indent, t.para.right_indent), (0.0, 0.0, 0.0)); + let lay = vectorcraft_text::layout(db, t); + assert!(!lay.overflow, "setup: the full RTL suffix fits the tall frame"); + assert!(!lay.vertical, "setup: horizontal area text"); + assert!(lay.glyphs.iter().any(|g| g.rtl && g.byte > hindi.len()), "setup: actual RTL suffix selects Type's visual-arrow route"); + for glyph in lay.glyphs.iter().filter(|g| g.byte < hindi.len()) { + let used = db.face_by_id(glyph.font_id).expect("the wrapped Hindi glyph's loaded face"); + assert!(used.file_data() == face.file_data(), "setup: wrapped Hindi uses the selected face bytes"); + assert_eq!(used.face_index(), face.face_index(), "setup: wrapped Hindi uses the selected face index"); + assert_ne!(glyph.gid, 0, "setup: wrapped Hindi glyph is present"); + assert!(!glyph.rtl, "setup: wrapped Hindi prefix stays LTR"); + } + assert_eq!(edit::next_cluster(text, second), hindi.len(), "setup: logical cluster end is 18"); + assert_eq!(edit::prev_cluster(text, hindi.len()), second, "setup: logical cluster start is 6"); + assert_eq!(edit::prev_cluster(text, split), second, "setup: raw line endpoint 12 is inside the grapheme"); + assert_eq!(edit::next_cluster(text, split), hindi.len(), "setup: raw line endpoint 12 is not its end"); + if lay.lines.len() < 2 || (lay.lines[0].start, lay.lines[0].end, lay.lines[1].start) != (0, split, split) { + eprintln!( + "SKIPPED: type_arrows_keep_devanagari_clusters_across_wrapped_lines; layout capability: the measured frame does not expose adjacent wrapped endpoints at internal byte {split}" + ); + return; + } + assert!(lay.lines.len() >= 2, "setup: actual wrapping occurred"); + assert_eq!( + (lay.lines[0].start, lay.lines[0].end, lay.lines[1].start), + (0, split, split), + "setup: actual adjacent line endpoints reach internal byte 12" + ); + assert_eq!(lay.line_of(second), 0, "setup: caret 6 is on the preceding line"); + assert!(!lay.lines[0].rtl, "setup: the preceding paragraph line is LTR"); + tool.caret = second; + tool.anchor = second; + assert_eq!(tool.editing, Some(id)); + assert_eq!(tool.sel(), (second, second), "setup: collapsed caret before Right"); + assert!(tool.typing.is_none(), "setup: no pending typing session"); + key(&mut tool, &d, ToolKey::Right, Mods::default()); + assert_eq!((tool.caret, tool.anchor), (hindi.len(), hindi.len()), "wrapped Right must move 6 -> 18 across the Hindi grapheme"); + key(&mut tool, &d, ToolKey::Left, Mods::default()); + assert_eq!((tool.caret, tool.anchor), (second, second), "wrapped Left must move 18 -> 6 across the Hindi grapheme"); +} + #[test] fn typing_is_one_coalesced_preview() { let (mut d, id, mut tool) = editing("Hello"); @@ -339,6 +509,35 @@ fn hebrew_typing_and_visual_arrows_keep_logical_text() { assert_eq!(t.plain_text(), "שלום"); } +/// View › Snap to Glyph: new point type placed near live text snaps to its baseline. +#[test] +fn snap_to_glyph_lines_up_new_point_type_with_a_baseline() { + let (d, _) = doc_with_text("Baseline"); + let (sel, p) = (Selection::default(), paint()); + let mut c = cx(&d, &sel, &p); + c.snap_to_glyph = true; + let existing = match &d.layers[0].children().unwrap()[0].kind { + NodeKind::Text(t) => t, + _ => panic!("text"), + }; + let lay = vectorcraft_text::layout(FontDb::global(), existing); + let baseline_y = (existing.xf * Point::new(0.0, lay.lines[0].baseline)).y; + let mut tool = TypeTool::new("type"); + tool.pointer(&c, &PointerEvent::new(PointerKind::Down, 250.0, baseline_y + 2.0)); + let acts = tool.pointer(&c, &PointerEvent::new(PointerKind::Up, 250.0, baseline_y + 2.0)); + assert!( + acts.iter().any(|a| matches!(a, Action::Exec(cmd, v) if cmd == "text.create" && (v["y"].as_f64().unwrap() - baseline_y).abs() < 0.5)), + "{acts:?}" + ); + c.snap_to_glyph = false; + tool.pointer(&c, &PointerEvent::new(PointerKind::Down, 250.0, baseline_y + 2.0)); + let acts = tool.pointer(&c, &PointerEvent::new(PointerKind::Up, 250.0, baseline_y + 2.0)); + assert!( + acts.iter().any(|a| matches!(a, Action::Exec(cmd, v) if cmd == "text.create" && (v["y"].as_f64().unwrap() - (baseline_y + 2.0)).abs() < 0.5)), + "{acts:?}" + ); +} + /// Where new type goes snaps to Smart Guides (#506): a click beside a rect lines up with its /// centre, and hovering shows it first; an area's corners land on its anchors. #[test] diff --git a/crates/tools/src/touchtype.rs b/crates/tools/src/touchtype.rs index 2cf8c96e19..c60ba2bfc8 100644 --- a/crates/tools/src/touchtype.rs +++ b/crates/tools/src/touchtype.rs @@ -231,30 +231,65 @@ impl TouchTypeTool { in_quad(&b.quad, xf.inverse() * p).then_some(Part::Move) } + /// Document-space move for a character box (`b` of `t`): kerning along the line and baseline + /// shift along the character's up axis. + fn move_params(id: NodeId, t: &TextObject, b: &CharBox, moved: Vec2) -> Value { + let doc_len = |v: Vec2| linear(t.xf, v).hypot(); + let det = b.along.cross(b.ey); + let (along, rise) = if !b.kerned { + (0.0, moved.dot(b.ey)) + } else if det.abs() > 0.1 { + (moved.cross(b.ey) / det, b.along.cross(moved) / det) + } else { + (moved.dot(b.along), 0.0) + }; + let mut out = json!({"id": id.0, "start": b.start}); + let dx = along * doc_len(b.along); + let dy = rise * doc_len(b.ey); + if dx != 0.0 { + out["dx"] = json!(dx); + } + if dy != 0.0 { + out["dy"] = json!(dy); + } + out + } + + /// Arrow-key nudge in document space. + fn nudge_params(id: NodeId, t: &TextObject, b: &CharBox, doc_dx: f64, doc_dy: f64) -> Value { + Self::move_params(id, t, b, linear(t.xf.inverse(), Vec2::new(doc_dx, doc_dy))) + } + + fn arrow_nudge(key: ToolKey, vertical: bool, step: f64) -> Option { + let key = if vertical { + match key { + ToolKey::Up => ToolKey::Left, + ToolKey::Down => ToolKey::Right, + ToolKey::Right => ToolKey::Up, + ToolKey::Left => ToolKey::Down, + other => other, + } + } else { + key + }; + match key { + ToolKey::Left => Some(Vec2::new(-step, 0.0)), + ToolKey::Right => Some(Vec2::new(step, 0.0)), + ToolKey::Up => Some(Vec2::new(0.0, -step)), + ToolKey::Down => Some(Vec2::new(0.0, step)), + _ => None, + } + } + /// The `text.touchType` params for the drag `d` with the pointer at `p` (document space). fn params(id: NodeId, t: &TextObject, d: &Drag, p: Point) -> Value { let b = &d.from; let inv = t.xf.inverse(); let moved = linear(inv, p - d.press); - let doc_len = |v: Vec2| linear(t.xf, v).hypot(); let st = &b.style; let mut out = json!({"id": id.0, "start": b.start}); match d.part { - Part::Move => { - // Kerning moves the character along its line, and baseline shift moves it along its - // own up axis, which turns with its rotation. The drag is split between the two. - // Turned nearly onto the line, the character moves only along the line. - let det = b.along.cross(b.ey); - let (along, rise) = if !b.kerned { - (0.0, moved.dot(b.ey)) - } else if det.abs() > 0.1 { - (moved.cross(b.ey) / det, b.along.cross(moved) / det) - } else { - (moved.dot(b.along), 0.0) - }; - out["dx"] = json!(along * doc_len(b.along)); - out["dy"] = json!(rise * doc_len(b.ey)); - } + Part::Move => out = Self::move_params(id, t, b, moved), Part::HScale => { let w = (b.quad[1] - b.quad[0]).hypot(); out["hScale"] = json!(st.h_scale * factor(w + moved.dot(b.ex), w)); @@ -336,23 +371,40 @@ impl Tool for TouchTypeTool { } } - /// Escape cancels a drag, and otherwise lets go of the selected character. - fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { - if key != ToolKey::Escape { + /// Escape cancels a drag or clears the selection; arrow keys nudge the selected character. + fn key(&mut self, cx: &ToolContext, key: ToolKey, mods: Mods) -> Vec { + if key == ToolKey::Escape { + return match self.drag.take() { + Some(d) if d.began => vec![Action::Cancel], + Some(_) => vec![], + None => { + self.target = None; + vec![] + } + }; + } + if self.drag.is_some() { return vec![]; } - match self.drag.take() { - Some(d) if d.began => vec![Action::Cancel], - Some(_) => vec![], - None => { - self.target = None; - vec![] - } + let Some((id, t, b)) = self.current(cx) else { return vec![] }; + let lay = self.layout(t); + let step = cx.keyboard_increment * if mods.shift { 10.0 } else { 1.0 }; + let Some(d) = Self::arrow_nudge(key, lay.vertical, step) else { return vec![] }; + let params = Self::nudge_params(id, t, &b, d.x, d.y); + if params.get("dx").is_none() && params.get("dy").is_none() { + return vec![]; } + vec![Action::Exec("text.touchType".into(), params)] } fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool { - key == ToolKey::Escape && (self.drag.is_some() || self.current(cx).is_some()) + if key == ToolKey::Escape { + return self.drag.is_some() || self.current(cx).is_some(); + } + if self.drag.is_some() { + return false; + } + self.current(cx).is_some() && matches!(key, ToolKey::Left | ToolKey::Right | ToolKey::Up | ToolKey::Down) } fn overlays(&self, cx: &ToolContext) -> Vec { @@ -509,7 +561,44 @@ mod tests { let acts = drag(&mut t, &cx, first, first + Vec2::new(10.0, -4.0)); let p3 = preview(&acts[1]); assert_eq!(p3["start"], json!(0)); - assert!(close(p3["dx"].as_f64().unwrap(), 0.0) && close(p3["dy"].as_f64().unwrap(), 4.0), "{p3}"); + assert!(close(p3.get("dx").and_then(|v| v.as_f64()).unwrap_or(0.0), 0.0) && close(p3["dy"].as_f64().unwrap(), 4.0), "{p3}"); + } + + #[test] + fn arrow_keys_nudge_the_selected_character() { + let (d, id, s) = doc_with_type(); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = TouchTypeTool::default(); + let lay = vectorcraft_text::layout(FontDb::global(), text_of(&cx, id).unwrap()); + let y = lay.glyphs.iter().find(|g| g.byte == 1).unwrap(); + let at = Point::new(100.0, 200.0) + (y.origin.to_vec2() + Vec2::new(y.advance / 2.0, -10.0)); + drag(&mut t, &cx, at, at); + assert!(t.claims_key(&cx, ToolKey::Right)); + let acts = t.key(&cx, ToolKey::Right, Mods::default()); + let p1 = match &acts[0] { + Action::Exec(c, v) if c == "text.touchType" => v, + other => panic!("{other:?}"), + }; + assert!(close(p1["dx"].as_f64().unwrap(), 1.0) && p1.get("dy").is_none(), "{p1}"); + // The first character can't kern: a horizontal nudge does nothing. + let first = Point::new(100.0, 200.0) + Vec2::new(lay.glyphs[0].advance / 2.0, -10.0); + drag(&mut t, &cx, first, first); + assert!(t.key(&cx, ToolKey::Left, Mods::default()).is_empty()); + let acts = t.key(&cx, ToolKey::Up, Mods::default()); + let p2 = match &acts[0] { + Action::Exec(_, v) => v, + other => panic!("{other:?}"), + }; + assert!(close(p2["dy"].as_f64().unwrap(), 1.0), "{p2}"); + // Shift multiplies the increment (on a character that can kern). + drag(&mut t, &cx, at, at); + let acts = t.key(&cx, ToolKey::Right, Mods { shift: true, ..Mods::default() }); + let p3 = match &acts[0] { + Action::Exec(_, v) => v, + other => panic!("{other:?}"), + }; + assert!(close(p3["dx"].as_f64().unwrap(), 10.0), "{p3}"); } #[test] diff --git a/crates/tools/src/xform.rs b/crates/tools/src/xform.rs index 32203a3b1e..bc4066cc41 100644 --- a/crates/tools/src/xform.rs +++ b/crates/tools/src/xform.rs @@ -22,7 +22,7 @@ pub use artboard::ArtboardTool; pub use eyedropper::EyedropperTool; pub use free::{DistortMode, FreeTransformTool}; pub use gradient::GradientTool; -pub use measure::MeasureTool; +pub use measure::{MeasureTool, measure}; pub use transform::{TransformKind, TransformTool}; pub use wand::{LassoTool, MagicWandTool}; diff --git a/crates/tools/src/xform/free.rs b/crates/tools/src/xform/free.rs index 1386e6243d..550a9baf0b 100644 --- a/crates/tools/src/xform/free.rs +++ b/crates/tools/src/xform/free.rs @@ -189,7 +189,7 @@ impl FreeTransformTool { Op::Corners(h, mode) => { let q = distort_quad(d.rect, h, delta, mode); self.quad = Some(q); - self.measure = None; + self.measure = cx.measurement_labels.then(|| (p, cx.offset_label(delta.x, delta.y))); let corners: Vec = q.iter().map(|c| json!([c.x, c.y])).collect(); return Action::Preview("object.distort".into(), json!({ "corners": corners, "from": [d.rect.x0, d.rect.y0, d.rect.x1, d.rect.y1] })); } @@ -235,7 +235,7 @@ impl Tool for FreeTransformTool { self.drag = None; let Some(r) = selection_bounds(cx) else { return vec![] }; if let Some(op) = self.classify(cx, r, p, ev.mods) { - self.targets = op.handle().is_some().then(|| PointSnap::new(cx, || Targets::collect(cx.doc, &cx.selection.objects, None))); + self.targets = op.handle().is_some().then(|| PointSnap::new(cx, || Targets::for_scale(cx))); self.drag = Some(Drag { op, rect: r, start: p, began: false }); } vec![] @@ -520,4 +520,23 @@ mod tests { assert_eq!(q[1], Point::new(8.0, 0.0)); assert_eq!(q[2], Point::new(10.0, 10.0)); } + + #[test] + fn distort_drag_shows_move_measurement_labels() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let cx = |on: bool| ToolContext { measurement_labels: on, ..cx(&d, &s, &p) }; + let mut t = FreeTransformTool::default(); + t.set_option("mode", &json!("distort")); + t.pointer(&cx(true), &ev(PointerKind::Down, 200.0, 200.0)); + t.pointer(&cx(true), &ev(PointerKind::Drag, 220.0, 230.0)); + let want = cx(true).offset_label(20.0, 30.0); + assert!(t.overlays(&cx(true)).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == &want))); + t.pointer(&cx(true), &ev(PointerKind::Up, 220.0, 230.0)); + t.pointer(&cx(false), &ev(PointerKind::Down, 200.0, 200.0)); + t.pointer(&cx(false), &ev(PointerKind::Drag, 220.0, 230.0)); + assert!(t.overlays(&cx(false)).iter().all(|o| !matches!(o, Overlay::Measure { .. }))); + } } diff --git a/crates/tools/src/xform/measure.rs b/crates/tools/src/xform/measure.rs index b9f3ddcf23..55835c48c3 100644 --- a/crates/tools/src/xform/measure.rs +++ b/crates/tools/src/xform/measure.rs @@ -57,14 +57,16 @@ impl Tool for MeasureTool { if a == b { return vec![]; } - let (dist, ang, dx, dy) = measure(a, b); - vec![ - Overlay::Line { a, b, color: CYAN, dashed: false }, - Overlay::Measure { + let mut out = vec![Overlay::Line { a, b, color: CYAN, dashed: false }]; + // Measurement Labels decides the readout; the line the tool draws stays. + if cx.measurement_labels { + let (dist, ang, dx, dy) = measure(a, b); + out.push(Overlay::Measure { p: b + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("D: {}\nAngle: {ang:.1}°\n{}", cx.len(dist), cx.offset_label(dx, dy)), - }, - ] + }); + } + out } fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { @@ -104,5 +106,9 @@ mod tests { assert!((o["angle"].as_f64().unwrap() - 53.130102).abs() < 1e-4); let ov = t.overlays(&cx); assert!(matches!(&ov[1], Overlay::Measure { text, .. } if text.starts_with("D: 50.00 pt"))); + let quiet = ToolContext { measurement_labels: false, ..cx }; + let ov = t.overlays(&quiet); + assert!(!ov.iter().any(|o| matches!(o, Overlay::Measure { .. })), "Measurement Labels off hides the readout"); + assert!(ov.iter().any(|o| matches!(o, Overlay::Line { .. })), "the measured line stays"); } } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 84b46b637f..f8f127071d 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -107,6 +107,25 @@ fn drag_id() -> egui::Id { fn drag_pos_id() -> egui::Id { egui::Id::new("canvas-drag-pos") } +/// The document point last sent to the tool as a drag during [`Drag::Tool`]. +fn tool_drag_doc_id() -> egui::Id { + egui::Id::new("canvas-tool-drag-doc") +} +/// Whether the tool should get another drag event: the pointer moved this frame, or its document +/// position changed without a delta (some Wayland compositors coalesce motion until release, #834). +fn tool_drag_moved(ui: &Ui, xf: &Xf, p: Pos2, pointer: &egui::PointerState) -> bool { + if pointer.delta() != egui::Vec2::ZERO { + return true; + } + let at = xf.to_doc(p); + let id = tool_drag_doc_id(); + let prev = ui.data(|d| d.get_temp::(id)); + if prev == Some(at) { + return false; + } + ui.data_mut(|d| d.insert_temp(id, at)); + true +} /// The pen pressure (0..1) of the press in progress: the force of this frame's pen or touch /// input, else the last one seen since the press (`pressed`: a new press, whose mouse has none @@ -190,6 +209,7 @@ pub fn fit(app: &mut VectorcraftApp, how: &str) { v.zoom = zoom; } +/// Paint the document canvas, complete or cached artwork, navigation and tool overlays. pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let full = ui.available_rect_before_wrap(); @@ -284,7 +304,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // Artwork raster. let ppp = ui.ctx().pixels_per_point(); - let (w, h) = ((rect.width() * ppp).round().max(1.0) as u32, (rect.height() * ppp).round().max(1.0) as u32); + // Match Renderer::render_as before recording the cache extent or building its view. + let (w, h) = ( + ((rect.width() * ppp).round().max(1.0) as u32).min(u32::from(u16::MAX)), + ((rect.height() * ppp).round().max(1.0) as u32).min(u32::from(u16::MAX)), + ); // View › Pixel Preview: the art as it rasterizes, one pixel per point, while a document pixel // is bigger than a screen pixel (below that the screen render already shows it). let pixel = (app.ui.view.pixel_preview && v.zoom * ppp as f64 > 1.0).then(|| pixel_region(&xf)).flatten(); @@ -339,6 +363,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { app.perf.render_ms = done.ms; app.canvas.last_ms = done.ms; app.canvas.moved = done.moved > 0; + app.canvas.from_worker = true; } if app.canvas.key.as_ref() != Some(&key) || app.canvas.texture.is_none() { let (w, h, view) = match pixel { @@ -389,10 +414,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // Light documents render synchronously (no lag vs overlays); heavy ones go to the worker. // A document switch renders synchronously so another document's frame is never shown. // The first frame after an interaction, when the frame shown drew moved rasters, also goes - // to the worker. + // to the worker. An interaction's frames stay on the worker once it drew the frame shown: + // its renderer keeps the rasters of the art's effects that make those frames fast, and this + // thread's renderer has none, so a frame fast on the worker would be slow here. let same_doc = app.canvas.key.as_ref().is_some_and(|k| k.doc == key.doc); let settling = app.canvas.moved && !key.interacting; - let heavy = (app.canvas.last_ms > 8.0 || settling) && app.canvas.texture.is_some() && same_doc; + let staying = key.interacting && app.canvas.from_worker; + let heavy = (app.canvas.last_ms > 8.0 || settling || staying) && app.canvas.texture.is_some() && same_doc; match (&mut app.canvas.worker, heavy) { (Some(worker), true) => worker.submit(crate::render_worker::Job { key: key.clone(), doc: doc.clone(), w, h, view, opts }), _ => { @@ -403,12 +431,21 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { app.perf.render_ms = now_ms() - t0; app.canvas.last_ms = app.perf.render_ms; app.canvas.moved = app.canvas.renderer.stats.moved > 0; + app.canvas.from_worker = false; } } } if let (Some(tex), Some(k)) = (&app.canvas.texture, &app.canvas.key) && k.doc == key.doc { + // The frame being shown covers the canvas rect it was rendered for. While a panel is + // dragged that rect is a different size, so reprojecting the frame through the *current* + // rect stretches the art to the new size until the worker's frame arrives, then it snaps + // back. Rebuild the rect it was rendered for from the key's own pixel size instead. + let old_rect = { + let ppp = if k.ppp > 0.0 { k.ppp } else { 1.0 }; + egui::Rect::from_center_size(rect.center(), vec2(k.w as f32 / ppp, k.h as f32 / ppp)) + }; match k.pixel { // Document pixels: placed over the document rect they cover, turning with the view. Some([x0, y0, x1, y1]) => { @@ -416,17 +453,18 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } None if (k.rot - v.rotation).abs() < 1e-9 => { // Reproject the last frame if it was rendered for a different view. - let old = Xf { rect, zoom: k.zoom, center: Point::new(k.cx, k.cy), rot: xf.rot }; - let a = xf.to_screen(old.to_doc(rect.min)); - let b = xf.to_screen(old.to_doc(rect.max)); + let old = Xf { rect: old_rect, zoom: k.zoom, center: Point::new(k.cx, k.cy), rot: xf.rot }; + let a = xf.to_screen(old.to_doc(old_rect.min)); + let b = xf.to_screen(old.to_doc(old_rect.max)); painter.image(tex.id(), egui::Rect::from_min_max(a, b), egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } // The view turned after the last frame was rendered, and the worker renders the frame at // the new angle. Until it arrives, the last frame is drawn turned into this view: each // corner goes where this view puts the document point that the corner showed. None => { - let old = Xf { rect, zoom: k.zoom, center: Point::new(k.cx, k.cy), rot: k.rot.to_radians() }; - let q = [rect.left_top(), rect.right_top(), rect.right_bottom(), rect.left_bottom()].map(|c| xf.to_screen(old.to_doc(c))); + let old = Xf { rect: old_rect, zoom: k.zoom, center: Point::new(k.cx, k.cy), rot: k.rot.to_radians() }; + let q = + [old_rect.left_top(), old_rect.right_top(), old_rect.right_bottom(), old_rect.left_bottom()].map(|c| xf.to_screen(old.to_doc(c))); textured_quad(&painter, tex.id(), &q, (1.0, 1.0)); } } @@ -464,6 +502,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // Selected guides in the selection colour. let picked = LineLook { color: t.selection, ..look }; let selected: &[usize] = app.session.active().map_or(&[], |st| &st.selection.guides); + let key = app.session.active().and_then(|st| st.selection.key_guide); let view = view_bounds(&xf); // Guides on a hidden layer hide with it. for (i, g) in doc.guides.iter().enumerate().filter(|(_, g)| doc.guide_shown(g)) { @@ -479,6 +518,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } }; if selected.contains(&i) { picked } else { look }.guide(&painter, a, b); + // The key guide (Align to Key Object, #2143): thicker, as a key object's outline is. + if key == Some(i) { + painter.line_segment([a, b], Stroke::new(KEY_OUTLINE, picked.color)); + } } } @@ -533,7 +576,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } rulers(ui, full, &xf, app.hover_doc, app.session.general_unit(), origin_preview.unwrap_or_else(|| app.ruler_origin()), &t); } - if app.ui.task_bar && !revolve_edit && !app.session.tool_busy() && app.ui.screen_mode < 3 { + // The task bar is not drawn while the Simplify slider shows. + if app.ui.task_bar && !revolve_edit && !app.session.tool_busy() && app.ui.screen_mode < 3 && !crate::dialogs::simplify_slider::showing(app) { task_bar(app, ui, &xf); } if app.ui.screen_mode < 3 { @@ -680,6 +724,7 @@ fn cursor_icon(c: Cursor) -> egui::CursorIcon { | Cursor::SymbolStainer | Cursor::SymbolScreener | Cursor::SymbolStyler + | Cursor::ObjectsOnPath | Cursor::Scissors | Cursor::ScissorsNotAllowed | Cursor::MeshAdd @@ -867,7 +912,7 @@ fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: ui.data_mut(|dd| dd.insert_temp(drag_id(), Drag::Art)); } Drag::Tool => { - if pointer.delta() != egui::Vec2::ZERO { + if tool_drag_moved(ui, &xf, p, &pointer) { // Every position the pen or mouse passed this frame, not just the last: a // fast stroke keeps its curve (a pen reports far more often than frames come). for (at, force) in frame_moves(ui) { @@ -890,6 +935,7 @@ fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: ui.data_mut(|dd| { dd.remove::(drag_id()); dd.remove::(drag_pos_id()); + dd.remove::(tool_drag_doc_id()); }); match d { Drag::ZoomBox { start } => { @@ -1535,11 +1581,26 @@ fn grid(p: &egui::Painter, xf: &Xf, spacing: f64, subdiv: u32, look: LineLook) { } /// A ruler label for `v` (in the ruler's unit) on a ruler whose labels are `step` apart: whole -/// numbers, or as many decimals as the step has. +/// numbers, or the fewest decimals that write `step` exactly, so a binary step keeps its value +/// (an inch ruler's 1/16 reads `0.0625`, not the `0.06` that rounding the step's magnitude gave). +/// How far down the left ruler a label of `chars` characters reaches, counting from its top: it +/// is spelled one character per line, [`RULER_CHAR`] apart, and the last one is a line tall. +pub(crate) fn vertical_label_height(chars: usize) -> f32 { + chars.saturating_sub(1) as f32 * RULER_CHAR + RULER_LINE +} + +/// A ruler label's line spacing and line height on the left ruler. +const RULER_CHAR: f32 = 8.5; +const RULER_LINE: f32 = 9.5; + pub(crate) fn ruler_label(v: f64, step: f64) -> String { - let decimals = if step >= 1.0 { 0 } else { (-step.log10()).ceil() as usize }; + let exact = |d: u32| (step * 10f64.powi(d as i32)).fract().abs() < 1e-9; + let decimals = (0..=7).find(|d| exact(*d)).unwrap_or(7) as usize; let s = format!("{v:.decimals$}"); - if s.trim_start_matches('-').chars().all(|c| c == '0' || c == '.') { "0".into() } else { s } + // Trailing zeros go, as `Unit::number` drops them: a sixteenth-inch ruler labels the inch `1`, + // not `1.0000`, which the vertical ruler would spell down six lines. + let s = if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.') } else { &s }; + if s.trim_start_matches('-').chars().all(|c| c == '0' || c == '.') { "0".into() } else { s.into() } } /// The rulers, numbered in `unit` (the General unit). @@ -1649,7 +1710,7 @@ fn rulers(ui: &Ui, full: egui::Rect, xf: &Xf, hover: Option, unit: Unit, // (`per` points each). let per = unit.points(); let step = unit.ruler_step(xf.zoom); - let minor = step / 10.0; + let minor = unit.ruler_minor(step); let font = egui::FontId::proportional(9.5); let near = |v: f64, every: f64| ((v / every).round() * every - v).abs() < minor * 0.01; // A tick's length: the labelled ones longest, the halves between them shorter. @@ -1685,14 +1746,24 @@ fn rulers(ui: &Ui, full: egui::Rect, xf: &Xf, hover: Option, unit: Unit, } }); let clip_left = p.with_clip_rect(left); + // A label spelled down the ruler is tall, and a long one can reach the next label's place: + // "-0.0625" is seven characters, 60 pt of ruler, where a sixteenth-inch step leaves 54 pt at + // zoom 12. The ticks all stay; a label that would run into the one above it is left out. + let mut filled_to = f32::NEG_INFINITY; ticks(left.left_top(), left.left_bottom(), vectorcraft_geom::Vec2::new(sn, cs), &mut |d, y| { let sy = left.top() + d; clip_left.line_segment([pos2(left.right() - tick(y), sy), pos2(left.right(), sy)], Stroke::new(1.0, t.ruler_tick)); if near(y, step) { // Vertical labels read top-to-bottom, one digit per line like Illustrator. - for (k, ch) in ruler_label(y, step).chars().enumerate() { + let text = ruler_label(y, step); + let top = sy + 2.0; + if top < filled_to { + return; + } + filled_to = top + vertical_label_height(text.chars().count()); + for (k, ch) in text.chars().enumerate() { clip_left.text( - pos2(left.left() + 4.0, sy + 2.0 + k as f32 * 8.5), + pos2(left.left() + 4.0, top + k as f32 * RULER_CHAR), egui::Align2::LEFT_TOP, ch.to_string(), font.clone(), @@ -1880,6 +1951,7 @@ fn hit_with( path_only: prefs.object_selection_by_path_only, type_path_only: prefs.type_selection_by_path_only, scope: app.session.active().and_then(|st| st.isolation), + ..Default::default() }; test(&app.session.active()?.doc, p, opt) } @@ -1973,6 +2045,8 @@ fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, xf: &Xf) // Art dragged back onto the canvas: its move was already dropped. (A symbol was placed // above.) widgets::PanelDrag::Art(_) | widgets::PanelDrag::Symbol(_) | widgets::PanelDrag::LibraryGraphic { .. } => return, + // A Libraries panel style or group only moves within that panel. + widgets::PanelDrag::LibraryItem { .. } | widgets::PanelDrag::LibraryGroup { .. } => return, }; if let Err(e) = app.run(cmd, params) { app.status(e); @@ -1981,8 +2055,8 @@ fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, xf: &Xf) fn hover_highlight(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) { let Some(h) = app.hover_doc else { return }; - // Smart Guides › Object Highlighting: a Smart Guides display option, so it needs them on. - if !app.ui.view.smart_guides || !app.session.prefs.object_highlighting { + // Smart Guides › Object Highlighting: a Smart Guides display option, so it needs them on and Snap to Grid and Pixel Preview off. + if !app.ui.view.smart_guides || !app.session.prefs.object_highlighting || app.ui.view.snap_to_grid || app.ui.view.pixel_preview { return; } if app.session.tool_busy() || !matches!(app.session.tool_id(), "selection" | "directSelection" | "groupSelection") { @@ -2784,9 +2858,27 @@ fn draw_overlays(p: &egui::Painter, xf: &Xf, overlays: &[Overlay], t: &Tokens, l fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) { let t = Tokens::get(ui.ctx()); ui.painter().rect_filled(rect, 0.0, t.panel_darker); - let inner = rect.shrink2(vec2((rect.width() - 820.0).max(40.0) / 2.0, 60.0)); - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(inner).layout(egui::Layout::top_down(egui::Align::Min))); - let ui = &mut child; + // Taller than the window (a small window, many recent files): it scrolls. Widgets scrolled out + // of view are clipped, so they take no pointer. + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(egui::Layout::top_down(egui::Align::Min))); + egui::ScrollArea::vertical().id_salt("home-scroll").auto_shrink([false, false]).show(&mut child, |ui| { + let side = (ui.available_width() - 820.0).max(40.0) / 2.0; + let width = (ui.available_width() - 2.0 * side).max(0.0); + ui.add_space(60.0); + ui.horizontal_top(|ui| { + ui.add_space(side); + ui.allocate_ui_with_layout(vec2(width, 0.0), egui::Layout::top_down(egui::Align::Min), |ui| { + ui.set_width(width); + home_content(app, ui); + }); + }); + ui.add_space(60.0); + }); +} + +/// The Home screen's column: welcome, New / Open, Recent Files, presets and community links. +fn home_content(app: &mut VectorcraftApp, ui: &mut Ui) { + let t = Tokens::get(ui.ctx()); ui.label(egui::RichText::new(tl!("Welcome to VectorCraft")).font(theme::semibold(26.0)).color(t.text)); ui.add_space(4.0); ui.label(egui::RichText::new(tl!("Vector illustration — fast, open, scriptable.")).size(14.0).color(t.text_dim)); @@ -2834,21 +2926,54 @@ fn recent(app: &mut VectorcraftApp, ui: &mut Ui) { ui.label(egui::RichText::new(tl!("Recent Files")).font(theme::semibold(14.0)).color(t.text)); ui.add_space(8.0); for path in files { - let p = std::path::Path::new(&path); - let name = p.file_name().map_or_else(|| path.clone(), |n| n.to_string_lossy().into_owned()); - let folder = p.parent().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default(); - ui.horizontal(|ui| { - crate::icons::icon(ui, "history", 16.0, t.icon); - let r = ui.add(egui::Button::new(egui::RichText::new(&name).color(t.accent).size(13.0)).frame(false)).on_hover_text(&path); - ui.add(egui::Label::new(egui::RichText::new(&folder).size(12.0).color(t.text_dim)).truncate()); - if r.clicked() { - // A failure is reported to the user there. - let _ = crate::io::open_reporting(app, &path); - } - }); + if recent_row(ui, &path).clicked() { + // A failure is reported to the user there. + let _ = crate::io::open_reporting(app, &path); + } } } +/// One Recent Files row across the Home screen: history icon, name (accent) and folder (dim, +/// truncated). The whole row is one button that lights up under the pointer; its tooltip is the +/// full path. +fn recent_row(ui: &mut Ui, path: &str) -> egui::Response { + const PAD: f32 = 6.0; + const ICON: f32 = 16.0; + let t = Tokens::get(ui.ctx()); + let p = std::path::Path::new(path); + let name = p.file_name().map_or_else(|| path.to_string(), |n| n.to_string_lossy().into_owned()); + let folder = p.parent().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default(); + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 26.0), egui::Sense::click()); + if ui.is_rect_visible(rect) { + if resp.hovered() { + ui.painter().rect_filled(rect, CornerRadius::same(4), t.hover); + } + let icon = egui::Rect::from_center_size(egui::pos2(rect.left() + PAD + ICON / 2.0, rect.center().y), vec2(ICON, ICON)); + crate::icons::paint(ui, "history", icon, t.icon); + let x = icon.right() + 8.0; + let name_galley = egui::WidgetText::from(egui::RichText::new(&name).size(13.0).color(t.accent)).into_galley( + ui, + Some(egui::TextWrapMode::Truncate), + (rect.right() - PAD - x).max(0.0), + egui::TextStyle::Body, + ); + let folder_x = x + name_galley.size().x + 10.0; + ui.painter().galley(egui::pos2(x, rect.center().y - name_galley.size().y / 2.0), name_galley, t.accent); + let room = rect.right() - PAD - folder_x; + if room > 0.0 && !folder.is_empty() { + let folder_galley = egui::WidgetText::from(egui::RichText::new(&folder).size(12.0).color(t.text_dim)).into_galley( + ui, + Some(egui::TextWrapMode::Truncate), + room, + egui::TextStyle::Body, + ); + ui.painter().galley(egui::pos2(folder_x, rect.center().y - folder_galley.size().y / 2.0), folder_galley, t.text_dim); + } + } + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &name)); + resp.on_hover_text(path).on_hover_cursor(egui::CursorIcon::PointingHand) +} + fn kurbo_flatten(p: &BezPath, tol: f64, f: &mut impl FnMut(PathEl)) { vectorcraft_geom::kurbo::flatten(p.elements().iter().copied(), tol, f); } @@ -4725,6 +4850,107 @@ mod tests { assert_eq!(app.canvas.renderer.stats.previewed, 0); } + /// Dragging a small square over an A4 page filled by a rectangle blurred by 500 pt, at 200%: + /// the blur reaches far past the raster budget, so the still frame keeps the backdrop's raster + /// cropped to the view, and each frame of a Selection tool drag draws it from there instead of + /// previewing it at the drag's lower resolution: on this thread, and on the worker, where the + /// frames of a heavy document render. + #[test] + fn a_drag_over_a_wide_blur_draws_the_blur_from_the_still_frame() { + for on_worker in [false, true] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 595, "height": 842})).unwrap(); + app.canvas.worker_started = true; // no worker unless `on_worker` + let back = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 595, "height": 842})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [back], "color": "#1a4ce6"})).unwrap(); + app.run("effect.apply", json!({"effect": "blur.gaussian", "params": {"radius": 500}, "ids": [back]})).unwrap(); + let square = app.run("shape.rectangle", json!({"x": 260, "y": 380, "width": 60, "height": 60})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [square]})).unwrap(); + app.select_tool("selection"); + let ctx = egui::Context::default(); + // One headless frame with `events`, then, on the worker, frames until the frame it renders + // for them is shown. + let run = |app: &mut VectorcraftApp, events: Vec| { + let frame = |app: &mut VectorcraftApp, events| { + let raw = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 870.0))), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + }; + frame(app, events); + let until = std::time::Instant::now() + std::time::Duration::from_secs(60); + while app.canvas.worker.as_ref().is_some_and(|w| w.pending.is_some()) && std::time::Instant::now() < until { + std::thread::sleep(std::time::Duration::from_millis(5)); + frame(app, vec![]); + } + }; + let moved = |app: &VectorcraftApp| if on_worker { app.canvas.moved } else { app.canvas.renderer.stats.moved > 0 }; + run(&mut app, vec![]); + if let Some(vm) = app.view_mut() { + (vm.zoom, vm.center) = (2.0, Point::new(290.0, 410.0)); + } + if on_worker { + app.canvas.worker = crate::render_worker::Worker::spawn(ctx.clone()); + app.canvas.last_ms = 50.0; + } + run(&mut app, vec![]); + assert_eq!(app.canvas.from_worker, on_worker); + assert!(!moved(&app), "a still frame, on the worker: {on_worker}"); + let at = app.canvas_rect.unwrap().center(); + let button = + |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(&mut app, vec![egui::Event::PointerMoved(at)]); + run(&mut app, vec![button(at, true)]); + for step in [1.0, 2.0, 3.0] { + run(&mut app, vec![egui::Event::PointerMoved(at + vec2(13.0, 7.0) * step)]); + assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting && k.dragging), "step {step}, on the worker: {on_worker}"); + assert_eq!(app.canvas.from_worker, on_worker, "step {step}"); + assert!( + !moved(&app), + "the blur drawn from the still frame's raster, step {step}, on the worker: {on_worker} ({} ms)", + app.perf.render_ms + ); + } + run(&mut app, vec![button(at + vec2(39.0, 21.0), false)]); + let info = app.run("document.inspect", json!({})).unwrap(); + let children = info["layers"][0]["children"].as_array().unwrap().clone(); + let x0 = |id: &serde_json::Value| children.iter().find(|c| c["id"] == *id).unwrap()["bounds"]["x"].as_f64().unwrap(); + assert!(x0(&square) > 270.0 && x0(&back) == 0.0, "the square moved, the backdrop did not"); + app.canvas.worker = None; + } + } + + /// An interaction's frames stay on the worker once it drew the frame shown, however fast that + /// frame was: the worker's renderer keeps the effect rasters that made it fast, and this + /// thread's renderer, without them, would draw the next frame slowly. Without a frame from the + /// worker, a fast frame renders on this thread as before. + #[test] + fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap(); + app.canvas.worker_started = true; // the first frame renders on this thread + let ctx = egui::Context::default(); + shapes(&mut app, &ctx); + for from_worker in [true, false] { + app.canvas.worker = crate::render_worker::Worker::spawn(ctx.clone()); + (app.canvas.from_worker, app.canvas.last_ms) = (from_worker, 1.0); + app.session.begin_interaction("Preview").unwrap(); + shapes(&mut app, &ctx); + let pending = app.canvas.worker.as_ref().and_then(|w| w.pending.as_ref()).is_some_and(|k| k.interacting); + assert_eq!(pending, from_worker, "sent to the worker: {from_worker}"); + if !from_worker { + assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting), "rendered on this thread"); + } + app.session.cancel_interaction().unwrap(); + app.canvas.worker = None; + shapes(&mut app, &ctx); + } + } + /// The frame after an interaction renders without `interacting` also when the interaction /// leaves the document as it was (#1257): here a drag back to where it started. #[test] @@ -4753,6 +4979,134 @@ mod tests { assert!(!app.canvas.moved); } + /// Cache metadata, worker requests and view transforms use the renderer's bounded raster size. + /// Keep the worker controlled so huge virtual viewports never allocate huge test images. + #[test] + fn canvas_render_jobs_use_renderer_limited_dimensions() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.canvas.worker_started = true; + app.ui.view.rulers = false; + let frame = |app: &mut VectorcraftApp, size, ppp| { + let mut input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(pos2(0.0, 0.0), size)), ..Default::default() }; + input.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().native_pixels_per_point = Some(ppp); + let mut output = ctx.run_ui(input, |ui| show(app, ui)); + output.textures_delta.clear(); + }; + frame(&mut app, vec2(400.0, 300.0), 1.0); + let (worker, jobs, _completed) = crate::render_worker::Worker::test_channel(); + app.canvas.worker = Some(worker); + app.canvas.last_ms = 50.0; + for (size, ppp, wide) in [(vec2(70000.25, 32.0), 1.0, true), (vec2(32.0, 70000.25), 1.0, false), (vec2(40000.25, 32.0), 2.0, true)] { + frame(&mut app, size, ppp); + let job = jobs.try_recv().expect("oversized viewport queued on controlled worker"); + assert_eq!((job.key.w, job.key.h), (job.w, job.h)); + assert_eq!(if wide { job.w } else { job.h }, u32::from(u16::MAX)); + assert!((1..=u32::from(u16::MAX)).contains(&job.w)); + assert!((1..=u32::from(u16::MAX)).contains(&job.h)); + let center = job.view * Point::new(job.key.cx, job.key.cy); + assert!((center.x - f64::from(job.w) / 2.0).abs() < 0.001); + assert!((center.y - f64::from(job.h) / 2.0).abs() < 0.001); + } + } + + /// A cached texture keeps the renderer's document mapping when the viewport changes. The + /// controlled worker cannot finish early, even if egui repeats a layout pass. + #[test] + fn cached_frames_keep_their_scale_during_resize_rotation_and_dpi_changes() { + for (old_rot, new_rot, old_ppp, new_ppp, pixel, resize_only) in [ + // Isolate the original panel/window resize: zoom, pan, rotation and DPI stay fixed. + (0.0, 0.0, 1.0, 1.0, false, true), + (30.0, 30.0, 1.25, 1.25, false, true), + (0.0, 0.0, 1.0, 1.0, false, false), + (30.0, 30.0, 1.25, 1.25, false, false), + (30.0, 75.0, 1.25, 1.25, false, false), + (30.0, 75.0, 1.25, 2.0, false, false), + (30.0, 30.0, 2.0, 1.25, false, false), + (30.0, 75.0, 1.25, 2.0, true, false), + ] { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.canvas.worker_started = true; + app.ui.view.pixel_preview = pixel; + let frame = |app: &mut VectorcraftApp, size: egui::Vec2, ppp: f32| { + let mut input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(pos2(31.25, 19.5), size)), ..Default::default() }; + // Monitor DPI is viewport input, not egui's UI zoom (which rescales the last + // screen rect and would override the simultaneous resize under test). + input.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().native_pixels_per_point = Some(ppp); + let mut out = ctx.run_ui(input, |ui| show(app, ui)); + assert!((out.pixels_per_point - ppp).abs() < 0.001); + out.textures_delta.clear(); + let tex = app.canvas.texture.as_ref().expect("rendered canvas texture").id(); + out.shapes + .into_iter() + .find_map(|s| match s.shape { + Shape::Mesh(m) if m.texture_id == tex => Some(m), + _ => None, + }) + .expect("the canvas texture is drawn") + }; + frame(&mut app, vec2(800.25, 600.35), old_ppp); + { + let v = app.view_mut().unwrap(); + v.rotation = old_rot; + v.zoom = 2.5; + v.center = Point::new(210.0, 160.0); + } + frame(&mut app, vec2(800.25, 600.35), old_ppp); + let old = app.canvas.key.clone().unwrap(); + let (worker, jobs, completed) = crate::render_worker::Worker::test_channel(); + app.canvas.worker = Some(worker); + app.canvas.last_ms = 50.0; + { + let v = app.view_mut().unwrap(); + v.rotation = new_rot; + if !resize_only { + v.zoom = 3.25; + v.center = Point::new(225.0, 170.0); + } + } + let size = vec2(602.5, 720.1); + let mesh = frame(&mut app, size, new_ppp); + assert_eq!(app.canvas.key.as_ref(), Some(&old), "the cached frame is still displayed"); + let job = jobs.try_recv().expect("the replacement frame was submitted"); + assert_eq!(job.key.ppp, new_ppp); + assert_eq!(job.key.rot, new_rot); + if resize_only { + assert_eq!((job.key.zoom, job.key.cx, job.key.cy, job.key.rot, job.key.ppp), (old.zoom, old.cx, old.cy, old.rot, old.ppp)); + } + assert_ne!((job.key.w, job.key.h), (old.w, old.h)); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let render_view = Affine::translate((old.w as f64 / 2.0, old.h as f64 / 2.0)) + * Affine::rotate(old.rot.to_radians()) + * Affine::scale(old.zoom * old.ppp as f64) + * Affine::translate((-old.cx, -old.cy)); + assert_eq!(mesh.vertices.len(), 4); + for vertex in &mesh.vertices { + assert!([pos2(0.0, 0.0), pos2(1.0, 0.0), pos2(1.0, 1.0), pos2(0.0, 1.0)].contains(&vertex.uv)); + let doc = if let Some([x0, y0, x1, y1]) = old.pixel { + Point::new(x0 as f64 + vertex.uv.x as f64 * (x1 - x0) as f64, y0 as f64 + vertex.uv.y as f64 * (y1 - y0) as f64) + } else { + render_view.inverse() * Point::new(vertex.uv.x as f64 * old.w as f64, vertex.uv.y as f64 * old.h as f64) + }; + assert!( + (vertex.pos - xf.to_screen(doc)).length() < 0.002, + "{old_rot}° -> {new_rot}°, DPI {old_ppp} -> {new_ppp}, pixel={pixel}: {vertex:?}" + ); + } + // Deliver the actual replacement and verify that it replaces the cached key. + let img = app.canvas.renderer.render(&job.doc, job.w, job.h, job.view, &job.opts); + let expected = job.key.clone(); + completed.send(crate::render_worker::Done { key: job.key, img, ms: 1.0, moved: 0 }).unwrap(); + frame(&mut app, size, new_ppp); + assert_eq!(app.canvas.key.as_ref(), Some(&expected), "the worker's frame arrived"); + } + } + /// When the view turns while the worker renders the frame at the new angle (Reset Rotate View on /// a heavy document), the canvas draws the last frame turned until that frame arrives: each /// corner goes where the new view puts the document point that the corner showed. The new frame @@ -5274,6 +5628,37 @@ mod tests { assert_eq!(dots(&mut app).len(), 2, "one anchor still shows them"); } + /// Smart Guides › Object Highlighting (#394): the outline of the object under the pointer does not + /// show with View › Snap to Grid or View › Pixel Preview on, even with Smart Guides and the option on. + #[test] + fn snap_to_grid_and_pixel_preview_hide_the_hover_outline() { + 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": 100, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("select.none", &json!({})).unwrap(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let rect = app.canvas_rect.unwrap(); + let over = Xf::new(rect, app.view().unwrap()).to_screen(Point::new(150.0, 150.0)); + let layer = egui::epaint::ColorMode::Solid(c32(app.session.active().unwrap().doc.layer_color(vectorcraft_doc::NodeId(id)))); + let outlines = |app: &mut VectorcraftApp| { + frame(app, &ctx, vec![egui::Event::PointerMoved(over)]); + shapes(app, &ctx).iter().filter(|s| matches!(s, Shape::Path(ps) if ps.stroke.width == 1.5 && ps.stroke.color == layer)).count() + }; + assert!(app.ui.view.smart_guides && app.session.prefs.object_highlighting); + assert!(outlines(&mut app) > 0, "highlighted with Snap to Grid and Pixel Preview off"); + app.run("view.snapToGrid", json!({})).unwrap(); + assert!(app.ui.view.snap_to_grid); + assert_eq!(outlines(&mut app), 0, "Snap to Grid on"); + app.run("view.snapToGrid", json!({})).unwrap(); + assert!(outlines(&mut app) > 0, "Snap to Grid off again"); + app.run("view.pixelPreview", json!({})).unwrap(); + assert!(app.ui.view.pixel_preview); + assert_eq!(outlines(&mut app), 0, "Pixel Preview on"); + app.run("view.pixelPreview", json!({})).unwrap(); + assert!(outlines(&mut app) > 0, "Pixel Preview off again"); + } + /// Smart Guides › Object Highlighting (#394): the outline of the object under the pointer /// shows with Smart Guides on and the option on, and not otherwise. #[test] @@ -6580,7 +6965,7 @@ mod tests { let fill = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.fill_paint(); let red = Paint::solid(Color::from_hex("#ed1c24").unwrap()); let rows = SwatchRows { grabbed: "Red".into(), names: vec!["Red".into()], groups: false }; - let swatch = PanelDrag::Paint { paint: red.clone(), params: json!({"swatch": "Red"}), rows: Some(rows) }; + let swatch = PanelDrag::Paint { paint: red.clone(), params: json!({"swatch": "Red"}), rows: Some(rows), library: None }; // Off the art nothing happens. drop(&mut app, swatch.clone(), Point::new(300.0, 250.0)); assert_eq!(fill(&app), Paint::solid(Color::WHITE)); @@ -6869,6 +7254,34 @@ mod tests { assert_eq!(plain(&app, id), "雅がくらくか"); } + #[test] + fn tool_drag_moved_without_pointer_delta() { + let ctx = egui::Context::default(); + let rect = egui::Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let v = View::default(); + let xf = Xf::new(rect, &v); + let a = pos2(100.0, 100.0); + let b = pos2(150.0, 120.0); + let mut first = false; + let mut second = false; + let mut out = + ctx.run_ui(egui::RawInput { screen_rect: Some(rect), events: vec![egui::Event::PointerMoved(a)], ..Default::default() }, |ui| { + let pointer = ui.input(|i| i.pointer.clone()); + first = tool_drag_moved(ui, &xf, a, &pointer); + second = tool_drag_moved(ui, &xf, a, &pointer); + }); + out.textures_delta.clear(); + assert!(first, "the first drag sample at a position runs"); + assert!(!second, "the same position without a delta is not sent again"); + let mut moved = false; + out = ctx.run_ui(egui::RawInput { screen_rect: Some(rect), events: vec![egui::Event::PointerMoved(b)], ..Default::default() }, |ui| { + let pointer = ui.input(|i| i.pointer.clone()); + moved = tool_drag_moved(ui, &xf, b, &pointer); + }); + out.textures_delta.clear(); + assert!(moved, "a new document position runs even when egui reports no delta"); + } + #[test] fn frame_moves_keeps_touch_samples_and_pressure_but_leaves_mouse_unchanged() { let ctx = egui::Context::default(); diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 4f3226bf2f..efd99a0453 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -1,6 +1,7 @@ //! Window chrome: application bar (menus), Control bar, document tabs, status bar. use std::borrow::Cow; +use std::sync::Arc; use egui::{CornerRadius, Sense, Stroke, Ui, vec2}; use serde_json::json; @@ -508,7 +509,12 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { crate::panels::artboards::select(app, selected); } } - // Isolation mode breadcrumb bar. +} + +/// The isolation mode breadcrumb bar. It is drawn over the top of `area` (the canvas), after the +/// canvas, so entering isolation mode does not change the canvas's size (#3126). +pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { + let t = Tokens::get(ui.ctx()); if let Some(st) = app.session.active() && let Some(iso) = st.isolation { @@ -519,7 +525,8 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) { if let Some(pn) = &pattern_edit { crumbs.push(pn.clone()); } - let (bar, _) = ui.allocate_exact_size(vec2(ui.available_width(), 24.0), Sense::hover()); + let bar = egui::Rect::from_min_size(area.min, vec2(area.width(), 24.0)); + ui.interact(bar, ui.id().with("iso-bar"), Sense::click_and_drag()); ui.painter().rect_filled(bar, 0.0, t.panel); let back = egui::Rect::from_min_size(bar.min + vec2(6.0, 3.0), vec2(18.0, 18.0)); let bresp = ui.interact(back, ui.id().with("iso-back"), Sense::click()); @@ -645,6 +652,7 @@ fn artboard_list(app: &VectorcraftApp, ui: &mut Ui, cur: usize) -> Option .inner } +/// Draw the status message, bounded readouts and artboard navigation controls. pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); egui::Panel::bottom("status_bar") @@ -720,50 +728,148 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) { }) .unwrap_or(""); ui.label(egui::RichText::new(tool).size(11.5).color(t.text_dim)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.label( - egui::RichText::new(format!( - "{} {:.1} ms · {} {:.1} ms · {:.0} fps", - crate::i18n::tr_ctx(crate::i18n::current(), "diagnostics", "render"), - app.perf.render_ms, - crate::i18n::tr_ctx(crate::i18n::current(), "diagnostics", "ui"), - app.perf.frame_ms, - app.perf.fps - )) - .size(10.5) - .color(t.text_disabled), - ); - if let Some(p) = app.hover_doc { - let u = app.session.general_unit(); - ui.label( - egui::RichText::new(format!("X: {} Y: {}", u.readout(p.x), u.readout(p.y))).font(theme::mono(10.5)).color(t.text_dim), - ); - } - // Background saves, exports and opens in progress, else the last message. - let busy: Vec<&str> = app - .background - .jobs - .iter() - .filter(|j| !j.label.is_empty() && !j.cancelled()) - .map(|j| j.label.as_str()) - .chain(app.opening.pending.iter().map(|p| p.label.as_str())) - .collect(); - if let Some(job) = busy.first() { - let more = busy.len() - 1; - let label = crate::i18n::msg(job); - let text = if more > 0 { format!("{label}… (+{more})") } else { format!("{label}…") }; - ui.add(egui::Spinner::new().size(12.0).color(t.accent)); - ui.add(egui::Label::new(egui::RichText::new(text).size(11.0).color(t.text)).truncate()); - } else if !app.ui.status.is_empty() { - // The message stays English in `ui.status` (agents and tests read it). - let message = crate::i18n::msg(&app.ui.status); - ui.add(egui::Label::new(egui::RichText::new(message).size(11.0).color(t.text)).truncate()); - } - }); + status_readouts(app, ui, &t); }); }); } +/// The most recently measured status widths, scoped to this UI and display settings. +struct StatusReadoutWidths { + key: (crate::i18n::Lang, vectorcraft_doc::Unit, f32), + values: [f32; 4], +} + +/// Reuse sample-string measurements until language, document units or display scale changes. +/// Keep a single entry per UI so repeated DPI/zoom changes cannot grow the cache indefinitely. +fn status_readout_widths(ui: &Ui, lang: crate::i18n::Lang, unit: vectorcraft_doc::Unit, t: &Tokens) -> Arc { + let id = ui.id().with("status-readout-widths"); + let key = (lang, unit, ui.ctx().pixels_per_point()); + if let Some(cached) = ui.data(|data| data.get_temp::>(id)) + && cached.key == key + { + return cached; + } + // Text layout also accesses egui state, so measure outside the ui.data lock. + let mono = theme::mono(10.5); + let proportional = egui::FontId::proportional(10.5); + let render = crate::i18n::tr_ctx(lang, "diagnostics", "render"); + let ui_name = crate::i18n::tr_ctx(lang, "diagnostics", "ui"); + let measure = |text, font: &egui::FontId| ui.painter().layout_no_wrap(text, font.clone(), t.text).size().x.ceil() + 4.0; + // Reserve a readable numeric range using every digit in the active font. These samples + // depend on the language/units, never the live values: timings cannot move field boundaries. + let timing_width = |label| (0..=9).map(|d| measure(format!("{label} {d}{d}{d}{d}.{d} ms"), &proportional)).fold(0.0_f32, f32::max); + let render_width = timing_width(render); + let ui_width = timing_width(ui_name); + let fps_width = (0..=9).map(|d| measure(format!("{d}{d}{d}{d} fps"), &proportional)).fold(0.0_f32, f32::max); + // Each axis shows at least -9999.99..9999.99 in the selected unit without elision. + let axis_width = (0..=9).map(|d| measure(format!("X: -{d}{d}{d}{d}.{d}{d} {}", unit.suffix()), &mono)).fold(100.0_f32, f32::max); + let widths = Arc::new(StatusReadoutWidths { key, values: [render_width, ui_width, fps_width, axis_width] }); + ui.data_mut(|data| data.insert_temp(id, Arc::clone(&widths))); + widths +} + +/// Allocate the remaining row once, then paint each field inside its own bounded rectangle. +/// Child UIs requested with a desired width can shrink to their contents; these rectangles cannot. +fn status_readouts(app: &VectorcraftApp, ui: &mut Ui, t: &Tokens) { + const MESSAGE_MIN: f32 = 180.0; + let mono = theme::mono(10.5); + let proportional = egui::FontId::proportional(10.5); + let unit = app.session.general_unit(); + let lang = crate::i18n::current(); + let render = crate::i18n::tr_ctx(lang, "diagnostics", "render"); + let ui_name = crate::i18n::tr_ctx(lang, "diagnostics", "ui"); + let widths = status_readout_widths(ui, lang, unit, t); + let [render_width, ui_width, fps_width, axis_width] = widths.values; + let coord_width = 2.0 * axis_width; + let perf_width = render_width + ui_width + fps_width + 12.0; + let point_id = ui.id().with(("status-hover-point", app.session.active().map(|st| st.uid))); + if let Some(p) = app.hover_doc { + ui.data_mut(|data| data.insert_temp(point_id, p)); + } + let gap = ui.spacing().item_spacing.x; + let size = vec2(ui.available_width().max(0.0), ui.available_height().max(0.0)); + let (area, _) = ui.allocate_exact_size(size, Sense::hover()); + let coordinates = area.width() >= MESSAGE_MIN + coord_width + gap; + let diagnostics = area.width() >= MESSAGE_MIN + coord_width + perf_width + 2.0 * gap; + let mut right = area.right(); + if diagnostics { + let perf = egui::Rect::from_min_max(egui::pos2(right - perf_width, area.top()), area.right_bottom()); + let mut x = perf.left(); + for (id, width, text) in [ + ("render", render_width, format!("{render} {:.1} ms", app.perf.render_ms)), + ("ui", ui_width, format!("{ui_name} {:.1} ms", app.perf.frame_ms)), + ("fps", fps_width, format!("{:.0} fps", app.perf.fps)), + ] { + let rect = egui::Rect::from_min_size(egui::pos2(x, area.top()), vec2(width, area.height())); + status_field(ui, id, rect, text, proportional.clone(), t.text_disabled); + x += width + 6.0; + } + right = perf.left() - gap; + } + if coordinates { + let left = right - coord_width; + // Keep the coordinate slot even without a hover point, so entering/leaving the canvas + // cannot move or re-truncate the message. X and Y have separate, stable origins. + let coord_rect = egui::Rect::from_min_max(egui::pos2(left, area.top()), egui::pos2(right, area.bottom())); + // The canvas clears hover_doc when the pointer leaves. While inspecting a readout, + // retain its last value so its tooltip can show the complete coordinate. + let inspecting = ui.input(|i| i.pointer.hover_pos()).is_some_and(|p| coord_rect.contains(p)) && ui.rect_contains_pointer(coord_rect); + let point = app.hover_doc.or_else(|| inspecting.then(|| ui.data(|data| data.get_temp::(point_id))).flatten()); + if let Some(p) = point { + for (id, x, value) in [("X", left, p.x), ("Y", left + axis_width, p.y)] { + let rect = egui::Rect::from_min_size(egui::pos2(x, area.top()), vec2(axis_width, area.height())); + status_field(ui, id, rect, format!("{id}: {}", unit.readout(value)), mono.clone(), t.text_dim); + } + } + right = left - gap; + } + let busy: Vec<&str> = app + .background + .jobs + .iter() + .filter(|j| !j.label.is_empty() && !j.cancelled()) + .map(|j| j.label.as_str()) + .chain(app.opening.pending.iter().map(|p| p.label.as_str())) + .collect(); + // Reserve the spinner's space while idle too: starting a background job changes the text, + // not its origin. Messages take priority over optional readouts in a narrow window. + let message = if let Some(job) = busy.first() { + let spinner = egui::Rect::from_center_size(egui::pos2(area.left() + 6.0, area.center().y), vec2(12.0, 12.0)); + ui.put(spinner, egui::Spinner::new().size(12.0).color(t.accent)); + let label = crate::i18n::msg(job); + let more = busy.len() - 1; + if more > 0 { format!("{label}… (+{more})") } else { format!("{label}…") } + } else { + crate::i18n::msg(&app.ui.status) + }; + 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())); + status_field(ui, "message", rect, message, egui::FontId::proportional(11.0), t.text); + } +} + +/// A field never grows with its text. Clipping also bounds over-wide glyphs; hover and access +/// information retain the complete value when its on-screen label is truncated. +fn status_field(ui: &mut Ui, id: &str, rect: egui::Rect, text: String, font: egui::FontId, color: egui::Color32) { + if rect.width() <= 0.0 || rect.height() <= 0.0 { + return; + } + let galley = egui::WidgetText::from(egui::RichText::new(&text).font(font)).into_galley( + ui, + Some(egui::TextWrapMode::Truncate), + rect.width(), + egui::TextStyle::Body, + ); + let at = egui::pos2(rect.left(), rect.center().y - galley.size().y / 2.0); + let elided = galley.elided; + ui.painter().with_clip_rect(ui.clip_rect().intersect(rect)).galley(at, galley, color); + let response = ui.interact(rect, ui.id().with(("status-field", id)), Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Label, true, &text)); + if elided { + response.on_hover_text(text); + } +} + /// Contextual hint for the active tool: segments of (text, bold). Keys in bold segments are /// written as shortcuts are ("Alt+Click"); [`hint_segments`] names them for the platform. /// The hint of the Zoom tool with Performance › Animated Zoom on. @@ -1026,6 +1132,10 @@ mod tests { assert_eq!(super::first_tab_shown(&widths, None, 350.0), 0); assert_eq!(super::first_tab_shown(&widths, Some(4), 50.0), 4, "a tab wider than the room still shows"); } + use std::sync::Arc; + + use super::{StatusReadoutWidths, status_readouts}; + use crate::theme::Tokens; use serde_json::json; use vectorcraft_engine::Session; @@ -1050,6 +1160,326 @@ mod tests { } } + #[derive(Debug)] + struct StatusText { + text: String, + at: egui::Pos2, + clip: egui::Rect, + bounds: egui::Rect, + elided: bool, + } + + /// Collect status-bar text layout from a headless frame without pointer events. + fn status_readout_frame(app: &mut crate::VectorcraftApp, ctx: &egui::Context, width: f32) -> Vec { + status_readout_frame_events(app, ctx, width, vec![]) + } + + /// Collect status-bar text, positions, clips and elision state with explicit pointer events. + fn status_readout_frame_events(app: &mut crate::VectorcraftApp, ctx: &egui::Context, width: f32, events: Vec) -> Vec { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 300.0)); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| super::status_bar(app, ui)); + out.textures_delta.clear(); + out.shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Text(t) => Some(StatusText { + text: t.galley.job.text.clone(), + at: t.pos, + clip: s.clip_rect, + bounds: egui::Rect::from_min_size(t.pos, t.galley.size()), + elided: t.galley.elided, + }), + _ => None, + }) + .collect() + } + + /// Find a required text record by prefix, failing the test when it is absent. + fn status_text<'a>(texts: &'a [StatusText], prefix: &str) -> &'a StatusText { + texts.iter().find(|t| t.text.starts_with(prefix)).unwrap_or_else(|| panic!("missing {prefix:?}: {texts:?}")) + } + + /// Prepare an English test document with the app fonts and a status message. + fn status_readout_app() -> (crate::VectorcraftApp, egui::Context) { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.ui.status = "Saved recovery data for Untitled-1".to_owned(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, crate::theme::Brightness::Dark); + (app, ctx) + } + + /// Draw the production readouts and observe the cached measurement object across frames. + fn status_width_cache_frame(app: &crate::VectorcraftApp, ctx: &egui::Context, width: f32, ppp: f32) -> Arc { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 300.0)); + let mut input = egui::RawInput { screen_rect: Some(screen), ..Default::default() }; + input.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(ppp); + let mut cache = None; + let mut output = ctx.run_ui(input, |ui| { + let t = Tokens::get(ui.ctx()); + status_readouts(app, ui, &t); + cache = ui.data(|data| data.get_temp::>(ui.id().with("status-readout-widths"))); + }); + output.textures_delta.clear(); + cache.expect("production status readouts populated their cache") + } + + /// Live values, hover state and window width reuse the same measurement object. + #[test] + fn status_width_measurements_are_reused_across_frames() { + let (mut app, ctx) = status_readout_app(); + let first = status_width_cache_frame(&app, &ctx, 1400.0, 1.0); + for width in [1400.0_f32, 500.0, 2200.0] { + app.perf = crate::Perf { render_ms: f64::from(width), frame_ms: f64::from(width) / 3.0, fps: 120.0 }; + app.hover_doc = Some(vectorcraft_geom::Point::new(-width as f64, width as f64)); + let cached = status_width_cache_frame(&app, &ctx, width, 1.0); + assert!(Arc::ptr_eq(&first, &cached), "live state or window size remeasured the samples"); + } + app.hover_doc = None; + assert!(Arc::ptr_eq(&first, &status_width_cache_frame(&app, &ctx, 1400.0, 1.0))); + } + + /// Each independent cache-key component refreshes widths, then subsequent frames reuse them. + #[test] + fn status_width_measurements_refresh_for_language_units_and_dpi() { + let (mut app, ctx) = status_readout_app(); + let mut previous = status_width_cache_frame(&app, &ctx, 4000.0, 1.0); + let french = crate::i18n::Lang::from_code("fr").unwrap(); + for (lang, unit, ppp) in [ + (french, vectorcraft_doc::Unit::Points, 1.0), + (french, vectorcraft_doc::Unit::Millimeters, 1.0), + (french, vectorcraft_doc::Unit::Millimeters, 1.5), + (crate::i18n::Lang::EN, vectorcraft_doc::Unit::Millimeters, 1.5), + (crate::i18n::Lang::EN, vectorcraft_doc::Unit::Points, 1.5), + (crate::i18n::Lang::EN, vectorcraft_doc::Unit::Points, 1.0), + ] { + crate::i18n::set_current(lang); + app.session.execute("document.setUnits", &json!({"units": unit.key()})).unwrap(); + let fresh = status_width_cache_frame(&app, &ctx, 4000.0, ppp); + assert_eq!(fresh.key, (lang, unit, ppp)); + assert!(!Arc::ptr_eq(&previous, &fresh), "changed language/units/DPI reused stale widths"); + assert!(fresh.values.iter().all(|w| w.is_finite() && *w > 0.0)); + assert!(Arc::ptr_eq(&fresh, &status_width_cache_frame(&app, &ctx, 4000.0, ppp))); + previous = fresh; + } + } + + /// These assertions require every target to be present, and cover the old padding limits. + #[test] + fn the_status_bar_stands_still_while_its_readouts_change() { + let (mut app, ctx) = status_readout_app(); + let mut baseline = None; + let mut message_baseline = None; + for (render, frame, fps, x, y) in [ + (233.4, 4.9, 80.0, -662.25, 1647.9), + (9.8, 1.0, 120.0, 7.0, 5.0), + (100000.0, 10000.0, 1000.0, -1000.0, 100000.0), + (99999.9, 9999.9, 999.0, -999.99, 9999.99), + ] { + app.perf = crate::Perf { render_ms: render, frame_ms: frame, fps }; + app.hover_doc = Some(vectorcraft_geom::Point::new(x, y)); + let texts = status_readout_frame(&mut app, &ctx, 1400.0); + let message = status_text(&texts, "Saved recovery data"); + let extent = (message.at, message.clip, message.bounds, message.elided); + if let Some(first) = message_baseline { + assert_eq!(extent, first, "message extent changed with readout values"); + } else { + message_baseline = Some(extent); + } + for (prefix, value) in [ + ("render", format!("{render:.1} ms")), + ("ui ", format!("{frame:.1} ms")), + ("X:", app.session.general_unit().readout(x)), + ("Y:", app.session.general_unit().readout(y)), + ] { + let text = status_text(&texts, prefix); + assert!(text.text.contains(&value), "{text:?} must contain {value:?}"); + assert!(text.bounds.width() <= text.clip.width() + 0.01, "field overflow: {text:?}"); + } + let fps_text = format!("{fps:.0} fps"); + let fps_label = status_text(&texts, &fps_text); + assert!(fps_label.bounds.width() <= fps_label.clip.width() + 0.01); + let positions = ["Saved recovery data", "render", "ui ", "X:", "Y:", fps_text.as_str()].map(|p| status_text(&texts, p).at); + if let Some(first) = baseline { + assert_eq!(positions, first, "readout origins changed"); + } else { + baseline = Some(positions); + } + } + app.perf.render_ms = 1000000.0; + let tree = crate::widgets::accessibility_tests::tree(|ui| super::status_bar(&mut app, ui)); + assert!( + tree.iter().any(|n| n.role() == egui::accesskit::Role::Label && n.value() == Some("render 1000000.0 ms")), + "screen readers receive the complete value" + ); + } + + /// Canvas hover entry and exit keep the status message at the same origin. + #[test] + fn status_messages_keep_their_origin_when_the_pointer_enters_and_leaves() { + let (mut app, ctx) = status_readout_app(); + let mut first = None; + for hover in [None, Some(vectorcraft_geom::Point::new(7.0, 5.0)), None] { + app.hover_doc = hover; + let texts = status_readout_frame(&mut app, &ctx, 1400.0); + let message = status_text(&texts, "Saved recovery data"); + assert!(!message.elided); + let position = (message.at, message.clip); + if let Some(first) = first { + assert_eq!(position, first); + } else { + first = Some(position); + } + assert_eq!(texts.iter().any(|t| t.text.starts_with("X:")), hover.is_some()); + } + } + + /// Hovering a coordinate preserves its document-scoped value for inspection. + #[test] + fn hovering_a_coordinate_retains_its_full_value_for_inspection() { + let (mut app, ctx) = status_readout_app(); + app.hover_doc = Some(vectorcraft_geom::Point::new(1e12, -1e12)); + let first = status_readout_frame(&mut app, &ctx, 1400.0); + let x = status_text(&first, "X:"); + assert!(x.elided); + let expected = x.text.clone(); + app.hover_doc = None; + let inspect = status_readout_frame_events(&mut app, &ctx, 1400.0, vec![egui::Event::PointerMoved(x.clip.center())]); + assert_eq!(status_text(&inspect, "X:").text, expected); + let gone = status_readout_frame_events(&mut app, &ctx, 1400.0, vec![egui::Event::PointerGone]); + assert!(!gone.iter().any(|t| t.text.starts_with("X:"))); + // A different document must not inherit the previous document's coordinate. + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let other = status_readout_frame_events(&mut app, &ctx, 1400.0, vec![egui::Event::PointerMoved(x.clip.center())]); + assert!(!other.iter().any(|t| t.text.starts_with("X:"))); + } + + /// Narrow windows hide optional readouts while keeping the status message visible. + #[test] + fn narrow_status_bars_preserve_the_message_and_hide_optional_readouts() { + let (mut app, ctx) = status_readout_app(); + app.hover_doc = Some(vectorcraft_geom::Point::new(7.0, 5.0)); + let mut origin = None; + for (width, coords, perf) in [(1400.0, true, true), (1000.0, true, false), (800.0, false, false)] { + let texts = status_readout_frame(&mut app, &ctx, width); + let message = status_text(&texts, "Saved recovery data"); + assert!(!message.elided, "{width}: message was truncated: {message:?}"); + if let Some(origin) = origin { + assert_eq!(message.at, origin); + } else { + origin = Some(message.at); + } + assert_eq!(texts.iter().any(|t| t.text.starts_with("X:")), coords, "{width}"); + assert_eq!(texts.iter().any(|t| t.text.starts_with("render")), perf, "{width}"); + let tool = status_text(&texts, "Selection"); + assert!(message.clip.left() >= tool.bounds.right(), "readouts must not overlap navigation: {texts:?}"); + for field in texts.iter().filter(|t| t.text.starts_with("X:") || t.text.starts_with("Y:") || t.text.starts_with("render")) { + assert!(field.clip.left() >= tool.bounds.right()); + assert!(!field.clip.intersects(message.clip)); + } + } + // Still narrower bars may truncate a long message but must not draw over navigation. + let texts = status_readout_frame(&mut app, &ctx, 600.0); + let message = status_text(&texts, "Saved recovery data"); + assert!(message.clip.left() >= status_text(&texts, "Selection").bounds.right()); + } + + /// Busy-job transitions preserve message placement, labels and accessibility. + #[test] + fn background_activity_keeps_the_status_message_origin() { + let (mut app, ctx) = status_readout_app(); + let before = status_readout_frame(&mut app, &ctx, 1400.0); + let before = status_text(&before, "Saved recovery data"); + let (tx, rx) = std::sync::mpsc::channel(); + app.services.write_shared = Some(std::sync::Arc::new(|_, _| Ok(()))); + crate::background::run( + &mut app, + true, + "Saving test.vectorcraft".to_owned(), + None, + move |_| { + rx.recv().unwrap(); + Ok(json!({})) + }, + |app, result| { + app.status("Saved recovery data for Untitled-1"); + result + }, + ) + .unwrap(); + let busy = status_readout_frame(&mut app, &ctx, 1400.0); + let message = status_text(&busy, "Saving test.vectorcraft"); + assert_eq!((before.at, before.clip), (message.at, message.clip)); + crate::background::run(&mut app, true, "Exporting test.svg".to_owned(), None, |_| Ok(json!({})), |_, result| result).unwrap(); + let several = status_readout_frame(&mut app, &ctx, 1400.0); + let message = status_text(&several, "Saving test.vectorcraft"); + assert!(message.text.ends_with("(+1)")); + assert_eq!((before.at, before.clip), (message.at, message.clip)); + let tree = crate::widgets::accessibility_tests::tree(|ui| super::status_bar(&mut app, ui)); + assert!(tree.iter().any(|n| n.role() == egui::accesskit::Role::ProgressIndicator), "the busy spinner remains accessible"); + tx.send(()).unwrap(); + crate::background::wait_all(&mut app); + let after = status_readout_frame(&mut app, &ctx, 1400.0); + let after = status_text(&after, "Saved recovery data"); + assert_eq!((before.at, before.clip), (after.at, after.clip)); + } + + /// Ordinary signed coordinates fit without elision in every supported unit. + #[test] + fn ordinary_coordinates_are_readable_in_every_unit() { + let (mut app, ctx) = status_readout_app(); + for unit in vectorcraft_doc::Unit::ALL { + app.session.execute("document.setUnits", &json!({"units": unit.key()})).unwrap(); + for (x, y) in [(-1234.56, 1234.56), (-9999.99, 9999.99), (9999.99, -9999.99)] { + let (x, y) = (unit.to_pt(x), unit.to_pt(y)); + app.hover_doc = Some(vectorcraft_geom::Point::new(x, y)); + let texts = status_readout_frame(&mut app, &ctx, 1400.0); + for (axis, value) in [("X:", x), ("Y:", y)] { + let field = status_text(&texts, axis); + assert_eq!(field.text, format!("{axis} {}", unit.readout(value))); + assert!(!field.elided, "{unit:?}: {field:?}"); + assert!(field.clip.contains_rect(field.bounds), "{unit:?}: {field:?}"); + } + } + } + } + + /// Localized diagnostics remain readable without moving neighboring fields. + #[test] + fn localized_diagnostics_are_readable_and_keep_their_field_bounds() { + let (mut app, ctx) = status_readout_app(); + for lang in crate::i18n::Lang::all() { + crate::i18n::set_current(lang); + let render = crate::i18n::tr_ctx(lang, "diagnostics", "render"); + let ui_name = crate::i18n::tr_ctx(lang, "diagnostics", "ui"); + let mut baseline = None; + for (render_ms, frame_ms, fps, readable) in [(233.4, 4.9, 80.0, true), (9999.9, 9999.9, 9999.0, true), (1e12, 1e12, 1e12, false)] { + app.perf = crate::Perf { render_ms, frame_ms, fps }; + let texts = status_readout_frame(&mut app, &ctx, 4000.0); + let fields = [format!("{render} {render_ms:.1} ms"), format!("{ui_name} {frame_ms:.1} ms"), format!("{fps:.0} fps")]; + let bounds = fields.map(|value| { + let field = status_text(&texts, &value); + assert_eq!(field.text, value); + assert_eq!(!field.elided, readable, "{}: {field:?}", lang.code()); + assert!(field.bounds.width() <= field.clip.width() + 0.01, "{}: {field:?}", lang.code()); + (field.at, field.clip) + }); + if let Some(first) = baseline { + assert_eq!(bounds, first, "{}: field allocation changed", lang.code()); + } else { + baseline = Some(bounds); + } + } + // Even long translations must yield their whole diagnostics group in a narrow + // window rather than overlapping the message or navigation controls. + let texts = status_readout_frame(&mut app, &ctx, 800.0); + assert!(!texts.iter().any(|t| t.text == format!("{render} {:.1} ms", app.perf.render_ms)), "{}", lang.code()); + } + crate::i18n::set_current(crate::i18n::Lang::EN); + } + /// A document tab's × sits where the platform puts it (#673): after the title on Windows, /// Linux and the web, before it on macOS; clicking it closes that document. #[test] @@ -1101,6 +1531,7 @@ mod tests { r } + /// Artboard navigation updates the active artboard and fitted view together. #[test] fn the_artboard_navigator_goes_to_artboards_and_fitting_shows_the_current_one() { use vectorcraft_geom::Point; @@ -1111,6 +1542,7 @@ mod tests { app.run("artboard.new", json!({})).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); let buttons = navigator(&mut app, &ctx, vec![]); assert_eq!(buttons.len(), 4); let click = |app: &mut crate::VectorcraftApp, r: egui::Rect| { @@ -1207,6 +1639,7 @@ mod tests { app.run("view.goToArtboard", json!({"index": 1})).unwrap(); let first = app.session.active().unwrap().doc.artboards[0].rect.center(); let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); let texts = status_texts(&mut app, &ctx, vec![]); let field = texts.iter().find(|(s, _)| s == "2 Back").map(|(_, r)| *r).expect("the field shows artboard 2's number and name"); assert!(!texts.iter().any(|(s, _)| s == "Front"), "the list is closed: {texts:?}"); @@ -1237,6 +1670,7 @@ mod tests { app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(460.0, 260.0))); app.run("view.goToArtboard", json!({"index": 699})).unwrap(); let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); let rows = |texts: &[(String, egui::Rect)]| texts.iter().filter(|(s, _)| s.starts_with("Artboard ")).cloned().collect::>(); let texts = status_texts(&mut app, &ctx, vec![]); let field = texts.iter().find(|(s, _)| s == "700 Artboard 700").map(|(_, r)| *r).expect("the field"); @@ -1318,6 +1752,7 @@ mod tests { let selection = st.selection.clone(); let undo = st.history.undo.len(); let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); artboard_navigation_next(&mut app, &ctx); @@ -1392,6 +1827,7 @@ mod tests { artboard_navigation_delete(None); } + /// Navigating artboards preserves other tools, their selections and undo history. #[test] fn artboard_navigation_preserves_other_tools_selection_and_history() { for tool in ["selection", "rectangle"] { @@ -1407,7 +1843,9 @@ mod tests { assert_eq!(history.1, 1); let options = app.session.tool_options(); - artboard_navigation_next(&mut app, &egui::Context::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + artboard_navigation_next(&mut app, &ctx); assert_eq!(app.view().unwrap().artboard, 1); assert_eq!(app.view().unwrap().center, before.artboards[1].rect.center()); @@ -1444,6 +1882,34 @@ mod tests { ctx.viewport(|vp| vp.prev_pass.widgets.get(egui::Id::new(super::ISOLATION_BUTTON)).map(|w| w.rect)) } + /// Entering isolation mode leaves the canvas where it was: the breadcrumb bar is drawn over the + /// canvas and takes no layout height from it (#3126). + #[test] + fn the_isolation_bar_does_not_take_layout_height_from_the_canvas() { + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 700.0)); + let top = |app: &mut crate::VectorcraftApp| { + let mut below = 0.0; + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| { + super::doc_tabs(app, ui); + below = ui.available_rect_before_wrap().top(); + let area = ui.available_rect_before_wrap(); + super::isolation_bar(app, ui, area); + assert_eq!(ui.available_rect_before_wrap().top(), below, "the bar takes no layout space"); + }); + out.textures_delta.clear(); + below + }; + let before = top(&mut app); + app.run("object.isolate", json!({"id": id})).unwrap(); + assert!(app.session.active().unwrap().isolation.is_some()); + assert_eq!(top(&mut app), before, "isolation mode leaves the canvas where it was"); + } + /// The Control bar's Isolate Selected Object isolates a path inside a group that Direct /// Selection selected, and Exit Isolation Mode leaves with the path selected. Type, symbol /// instances, blends, two objects and an envelope's contents get no isolate button, and pattern diff --git a/crates/ui-egui/src/cursors.rs b/crates/ui-egui/src/cursors.rs index 4af75c42ba..59dd138cd9 100644 --- a/crates/ui-egui/src/cursors.rs +++ b/crates/ui-egui/src/cursors.rs @@ -409,7 +409,7 @@ fn magnifier(p: &mut Ink, o: Pos2, out: bool) { /// Every cursor with a glyph: its own, drawn here, or the one it borrows. #[cfg(test)] -const GLYPHS: [Cursor; 75] = [ +const GLYPHS: [Cursor; 76] = [ Cursor::Hand, Cursor::HandGrab, Cursor::ZoomIn, @@ -454,6 +454,7 @@ const GLYPHS: [Cursor; 75] = [ Cursor::Blend, Cursor::BlendObject, Cursor::BlendAnchor, + Cursor::ObjectsOnPath, Cursor::PathBracket, Cursor::TypeWidget, Cursor::LoadedText, diff --git a/crates/ui-egui/src/dialogs/artboard_options.rs b/crates/ui-egui/src/dialogs/artboard_options.rs index 324ba88568..b99d7bafc0 100644 --- a/crates/ui-egui/src/dialogs/artboard_options.rs +++ b/crates/ui-egui/src/dialogs/artboard_options.rs @@ -1,6 +1,6 @@ //! Artboard Options (double-click with the Artboard tool, double-click the tool, or the Artboards //! panel's options icon or menu): the artboard's fields, sizes parsed with units, and its position -//! from a reference point. +//! from a reference point. A new size also goes to the other selected artboards. use serde_json::{Value, json}; use vectorcraft_doc::Unit; @@ -31,10 +31,12 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { form::grid_then(ui, d, unit, |ui, d| { let (w, h) = (d.f64("width", 0.0), d.f64("height", 0.0)); let n = artboard_rect(was, refi, None, None, Some(w), Some(h), false); - // Only the side that changed moves, so an untouched coordinate stays exactly as it was. - for (key, changed, at) in [("x", w != w0, n.x0), ("y", h != h0, n.y0)] { + // Only the side that changed moves, so an untouched coordinate stays exactly as it was. The + // reference point's column or row is kept for the other selected artboards (`confirm`). + for (key, changed, at, part) in [("x", w != w0, n.x0, refi % 3), ("y", h != h0, n.y0, refi / 3)] { if changed { d.fields.insert(key.into(), json!(at)); + d.fields.insert(format!("__ref{key}"), json!(part)); } } position_rows(ui, d, refi, unit, origin); @@ -92,6 +94,10 @@ pub fn open(app: &mut VectorcraftApp) -> Result { Ok(json!({ "dialog": KIND })) } +/// OK sets the artboard's fields. A Width or Height that differs from the artboard's also goes to +/// the other selected artboards (when this one is among them), each resized about the reference +/// point the form's last Width or Height change used (fields `__refx` and `__refy`, its column and +/// row; the top-left corner when the form set none), all in one undo step. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { if d.bool("new") { return confirm_new(app, d); @@ -102,7 +108,27 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { p[k] = json!(d.f64(k, 0.0)); } } - p["moveArt"] = json!(crate::panels::artboards::move_art(app)); + if let Some(o) = p.as_object_mut() { + o.retain(|k, _| !k.starts_with("__")); + } + let index = p["index"].as_u64().and_then(|i| usize::try_from(i).ok()).unwrap_or(0); + let was = app.session.active().and_then(|st| st.doc.artboards.get(index)).map(|a| a.rect); + let changed = |k: &str, old: Option| p[k].as_f64().filter(|v| old.is_some_and(|old| (v - old).abs() > 1e-6)); + let (w, h) = (changed("width", was.map(|r| r.width())), changed("height", was.map(|r| r.height()))); + let part = |k: &str| d.fields.get(k).and_then(Value::as_u64).map_or(0, |v| v.min(2) as usize); + let refi = part("__refy") * 3 + part("__refx"); + let mut entries = vec![]; + if w.is_some() || h.is_some() { + for i in crate::panels::artboards::resized_with(app, index).into_iter().filter(|i| *i != index) { + if let Some(r) = app.session.active().and_then(|st| st.doc.artboards.get(i)).map(|a| a.rect) { + let n = artboard_rect(r, refi, None, None, w, h, false); + entries.push(json!({"index": i, "x": n.x0, "y": n.y0, "width": n.width(), "height": n.height()})); + } + } + } + entries.insert(0, p); + let common = json!({"moveArt": crate::panels::artboards::move_art(app)}); + let p = crate::panels::artboards::set_props_params(common, entries).ok_or("no artboard")?; run_and_close(app, "artboard.setProps", p) } diff --git a/crates/ui-egui/src/dialogs/brush_art_options.rs b/crates/ui-egui/src/dialogs/brush_art_options.rs index cf2edf290c..43e747d8b3 100644 --- a/crates/ui-egui/src/dialogs/brush_art_options.rs +++ b/crates/ui-egui/src/dialogs/brush_art_options.rs @@ -8,7 +8,8 @@ //! Scatter: per value (`size`, `spacing`, `scatter` %, `rotation` °) `…Min`, `…Max` and `…Mode` //! (`fixed` | `random` | `pressure`), `rotationRelativeTo` (`page` | `path`). //! Art: `width` (%), `scaleMode` (`proportional` | `stretch` | `betweenGuides`), `guideStart` and -//! `guideEnd` (% of the art's length), `direction` (`leftToRight` …), `flipAlong`, `flipAcross`. +//! `guideEnd` (% of the art's length), `direction` (`leftToRight` …), `flipAlong`, `flipAcross`, +//! `overlap` (bend on each run between sharp corners). //! Pattern: `scale`, `spacing` (%), `fit` (`stretch` | `addSpace` | `approximate`), `flipAlong`, //! `flipAcross`, `__tiles` (slot → preview key, for the tiles the brush has). @@ -96,6 +97,7 @@ pub(super) fn fields(b: &Brush, def: Value, f: &mut Map) { f.insert("direction".into(), json!(id_of(&a.direction))); f.insert("flipAlong".into(), json!(a.flip_along)); f.insert("flipAcross".into(), json!(a.flip_across)); + f.insert("overlap".into(), json!(a.overlap)); } BrushKind::Pattern(p) => { f.insert("scale".into(), json!(p.scale)); @@ -168,6 +170,7 @@ pub(super) fn params(d: &Dialog) -> Value { "direction": id_of(&parse_field::(d, "direction")), "flip_along": d.bool("flipAlong"), "flip_across": d.bool("flipAcross"), + "overlap": d.bool("overlap"), }) } _ => json!({ @@ -284,6 +287,8 @@ fn art_body(ui: &mut egui::Ui, d: &mut Dialog) { } }); flips(ui, d); + ui.add_space(4.0); + super::form::check(ui, d, "overlap", tl!("Overlap")); } /// A toggle button showing an arrow pointing the way `dir` runs. Whether it was clicked. diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index 75d337c559..982355d925 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -16,8 +16,8 @@ use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::ColorMode; use vectorcraft_engine::cmd::color_value; -use super::DialogSpec; use super::form::PREVIEWED; +use super::{DialogAction, DialogSpec}; use crate::panels::color::{GAMUT_WARNING, WEB_WARNING, gamut_fix, hex_digits, is_web_safe, parse_hex, warning_chip, web_safe}; use crate::panels::{c32, color_json}; use crate::state::Dialog; @@ -28,18 +28,34 @@ pub(super) const KIND: &str = "colorPicker"; pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Color Picker").into(), - body, + header: Some(header), + body_with_actions: Some(body), confirm, preview: true, - min_width: 600.0, - max_width: Some(640.0), + min_width: 0.0, ..DialogSpec::FORM }; -/// Side of the colour field (and height of the channel slider). -const FIELD: f32 = 240.0; -/// Width of the value fields. -const VALUE_W: f32 = 54.0; +/// The preview and actions share the top row; the fields span both columns beneath it. +const HEADER_H: f32 = 30.0; +const CHIP_H: f32 = 64.0; +const ACTION_GAP: f32 = 2.0; +const ACTIONS_H: f32 = 3.0 * 28.0 + 2.0 * ACTION_GAP; +const ROW_H: f32 = 26.0; +const VALUE_GAP: f32 = 4.0; +const ROW_GAP: f32 = 1.0; +const GROUP_GAP: f32 = 2.0; +const PREVIEW_GAP: f32 = 12.0; +const FIELD: f32 = ACTIONS_H + PREVIEW_GAP + 7.0 * ROW_H + 6.0 * ROW_GAP + GROUP_GAP; +const MIN_FIELD: f32 = 160.0; +// channel_slider reserves 6 points on each side for its arrows: the painted ramp is 20 wide. +const SLIDER_W: f32 = 32.0; +const SLIDER_GAP: f32 = 16.0; +const COLUMN_GAP: f32 = 12.0; +// Leave room for two warning chips below the preview, instead of an empty side column. +const PREVIEW_W: f32 = 88.0; +/// Matches the outer width of the existing hex field. +const VALUE_W: f32 = 74.0; /// The component the channel slider edits; the colour field shows the other two. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -203,68 +219,152 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { Ok(Value::Null) } -fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { +/// Stable action width in both modes, including translated labels. +fn button_width(ui: &Ui) -> f32 { + ["OK", "Cancel", "Color Swatches", "Color Models"].into_iter().fold(110.0_f32, |w, label| { + let text = ui.painter().layout_no_wrap(tl!(label).into(), crate::theme::semibold(12.5), Tokens::get(ui.ctx()).text); + w.max(text.size().x + 32.0) + }) +} + +/// A compact width shared by the heading and body, bounded by the available window width. +fn layout_size(ui: &Ui) -> (f32, f32, f32, bool) { + 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) +} + +/// 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 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())); + 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)); + let t = Tokens::get(ui.ctx()); + let corners = ui.visuals().window_corner_radius; + // The band extends into the window's existing margins, stopping at its outer edges. + let painter = ui.painter().with_clip_rect(ui.ctx().content_rect()); + painter.rect_filled(band, egui::CornerRadius { sw: 0, se: 0, ..corners }, t.panel_darker); + painter.hline(band.x_range(), band.bottom(), egui::Stroke::new(1.0, t.divider)); + painter.text(band.center(), egui::Align2::CENTER_CENTER, title, crate::theme::semibold(16.0), t.text); + super::modal::drag_band(ui, band.bottom()); +} + +/// Draws the responsive picker and updates its color fields and live preview. +/// Returns the requested action for the shared frame to confirm or cancel. +fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> DialogAction { let channel = Channel::parse(&d.str("channel")).unwrap_or_default(); let web = d.bool("webOnly"); let swatches = d.bool("swatches"); let p = picked(d); let original = d.fields.get("original").and_then(color_value).unwrap_or(p.color); let gamut = gamut_fix(app, ui.ctx(), "picker-gamut", &p.color); + 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; let mut new_channel = None; let mut toggle_swatches = false; let mut sample = false; - ui.horizontal_top(|ui| { - if swatches { - pick = swatch_list(app, ui, &p.color).map(Picked::of); - } else { - let (z, x, y) = field_pos(channel, &p); - let at = |x: f32, y: f32| c32(&field_pick(channel, z, x, y).snapped(web).color); - if let (Some((x, y)), _) = widgets::color_field(ui, "cp-field", vec2(FIELD, FIELD), (x, y), &at) { - pick = Some(field_pick(channel, z, x, y)); - } - ui.add_space(6.0); - let track = |z: f32| c32(&Picked::of(slider_color(channel, z, x, y)).snapped(web).color); - let (v, suffix, max) = channel_value(channel, &p); - let shown = widgets::SliderValue::field(v as f64, 0.0..=max as f64, suffix, 0); - if let (Some(z), _) = widgets::channel_slider_valued(ui, "cp-slider", tl!(channel.label()), Some(shown), z, vec2(22.0, FIELD), &track) { - pick = Some(field_pick(channel, z, x, y)); - } - } - ui.add_space(14.0); - ui.vertical(|ui| { - ui.horizontal_top(|ui| { - if new_original_chips(ui, &p.color, &original) { - pick = Some(Picked::of(original)); - } - ui.add_space(4.0); + 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 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") + .max_width(ui.available_width()) + .max_height(height) + .min_scrolled_height((body_height + 32.0).min(height)) + .show(ui, |ui| { + ui.set_min_width(content_w); + // Keep the screen sampler above the field, outside the value grids' Tab order. + ui.allocate_ui_with_layout(vec2(side, 24.0), egui::Layout::right_to_left(egui::Align::Center), |ui| { sample = crate::screen_color::button(app, ui); - ui.add_space(4.0); - ui.vertical(|ui| { - if let Some(fix) = gamut - && warning_chip(ui, GAMUT_WARNING, &fix) - { - pick = Some(Picked::of(fix)); - } - let ws = web_safe(&p.color); - if !web && !is_web_safe(&p.color) && warning_chip(ui, WEB_WARNING, &ws) { - pick = Some(Picked::of(ws)); + }); + ui.add_space(4.0); + ui.with_layout(layout, |ui| { + ui.spacing_mut().item_spacing.x = 0.0; + ui.allocate_ui_with_layout(vec2(side + SLIDER_GAP + SLIDER_W, side), egui::Layout::top_down(egui::Align::Min), |ui| { + ui.horizontal_top(|ui| { + if swatches { + pick = swatch_list(app, ui, &p.color, side).map(Picked::of); + } else { + let (z, x, y) = field_pos(channel, &p); + let at = |x: f32, y: f32| c32(&field_pick(channel, z, x, y).snapped(web).color); + if let (Some((x, y)), _) = widgets::color_field(ui, "cp-field", vec2(side, side), (x, y), &at) { + pick = Some(field_pick(channel, z, x, y)); + } + ui.add_space(SLIDER_GAP); + let track = |z: f32| c32(&Picked::of(slider_color(channel, z, x, y)).snapped(web).color); + let (v, suffix, max) = channel_value(channel, &p); + let shown = widgets::SliderValue::field(v as f64, 0.0..=max as f64, suffix, 0); + if let (Some(z), _) = + widgets::channel_slider_valued(ui, "cp-slider", tl!(channel.label()), Some(shown), z, vec2(SLIDER_W, side), &track) + { + pick = Some(field_pick(channel, z, x, y)); + } + } + }); + ui.add_space(8.0); + if widgets::check(ui, tl!("Only Web Colors"), web, true) { + d.fields.insert("webOnly".into(), json!(!web)); } }); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| { - toggle_swatches = widgets::flat_button(ui, if swatches { tl!("Color Models") } else { tl!("Color Swatches") }, 110.0).clicked(); + ui.add_space(COLUMN_GAP); + ui.allocate_ui_with_layout(vec2(values_w, FIELD), egui::Layout::top_down(egui::Align::Min), |ui| { + ui.spacing_mut().item_spacing = vec2(VALUE_GAP, ROW_GAP); + ui.horizontal_top(|ui| { + ui.spacing_mut().item_spacing.x = 0.0; + ui.allocate_ui_with_layout(vec2(PREVIEW_W, ACTIONS_H), egui::Layout::top_down(egui::Align::Min), |ui| { + ui.set_min_size(vec2(PREVIEW_W, ACTIONS_H)); + if new_original_chips(ui, &p.color, &original) { + pick = Some(Picked::of(original)); + } + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = VALUE_GAP; + if let Some(fix) = gamut + && warning_chip(ui, GAMUT_WARNING, &fix) + { + pick = Some(Picked::of(fix)); + } + let ws = web_safe(&p.color); + if !web && !is_web_safe(&p.color) && warning_chip(ui, WEB_WARNING, &ws) { + pick = Some(Picked::of(ws)); + } + }); + }); + ui.add_space(COLUMN_GAP); + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = ACTION_GAP; + if widgets::primary_button_width(ui, "OK", button_w).clicked() { + action = DialogAction::Confirm; + } + if widgets::secondary_button_width(ui, "Cancel", button_w).clicked() { + action = DialogAction::Cancel; + } + toggle_swatches = + widgets::secondary_button_width(ui, if swatches { tl!("Color Models") } else { tl!("Color Swatches") }, button_w) + .clicked(); + }); + }); + ui.add_space(PREVIEW_GAP - ROW_GAP); + let (edit, ch) = value_fields(ui, &p, channel); + pick = pick.or(edit); + new_channel = ch; }); }); - ui.add_space(10.0); - let (edit, ch) = value_fields(ui, &p, channel); - pick = pick.or(edit); - new_channel = ch; }); - }); - ui.add_space(8.0); - if widgets::check(ui, tl!("Only Web Colors"), web, true) { - d.fields.insert("webOnly".into(), json!(!web)); - } if let Some(ch) = new_channel { d.fields.insert("channel".into(), json!(ch.id())); } @@ -276,7 +376,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { } store(d, &pick.unwrap_or(p).snapped(d.bool("webOnly"))); preview(app, d); - false + action } /// Show the picked colour on the selected art while the picker is open: each new colour replaces @@ -311,7 +411,7 @@ fn paint_command(app: &VectorcraftApp, d: &Dialog) -> (&'static str, Value) { /// The New (top) and Original (bottom) chips. Returns true when Original is clicked. fn new_original_chips(ui: &mut Ui, new: &Color, original: &Color) -> bool { let t = Tokens::get(ui.ctx()); - let (r, _) = ui.allocate_exact_size(vec2(64.0, 60.0), Sense::hover()); + let (r, _) = ui.allocate_exact_size(vec2(64.0, CHIP_H), Sense::hover()); let top = Rect::from_min_max(r.min, egui::pos2(r.right(), r.center().y)); let bottom = Rect::from_min_max(egui::pos2(r.left(), r.center().y), r.max); widgets::paint_chip(ui, top, &Paint::solid(*new)); @@ -335,11 +435,17 @@ fn value_fields(ui: &mut Ui, p: &Picked, channel: Channel) -> (Option, O let cmyk = p.color.to_cmyk_managed(cms.settings().intent); let mut edit = None; let mut chosen = None; - let spacing = vec2(6.0, 4.0); + let spacing = vec2(VALUE_GAP, ROW_GAP); ui.horizontal_top(|ui| { ui.spacing_mut().item_spacing.x = spacing.x; - let left = egui::Grid::new("cp-values").spacing(spacing).show(ui, |ui| { + let left = egui::Grid::new("cp-values").num_columns(2).min_row_height(0.0).spacing(spacing).show(ui, |ui| { for i in 0..7 { + if i == 3 { + for _ in 0..2 { + ui.allocate_exact_size(vec2(0.0, GROUP_GAP - ROW_GAP), Sense::hover()); + } + ui.end_row(); + } if let Some(&ch) = Channel::ALL.get(i) { if widgets::radio(ui, ch.label(), ch == channel, true) { chosen = Some(ch); @@ -370,8 +476,14 @@ fn value_fields(ui: &mut Ui, p: &Picked, channel: Channel) -> (Option, O ui.end_row(); } }); - egui::Grid::new("cp-values-right").spacing(spacing).show(ui, |ui| { + egui::Grid::new("cp-values-right").num_columns(2).min_row_height(0.0).spacing(spacing).show(ui, |ui| { for i in 0..7 { + if i == 3 { + for _ in 0..2 { + ui.allocate_exact_size(vec2(0.0, GROUP_GAP - ROW_GAP), Sense::hover()); + } + ui.end_row(); + } let (label, v, suffix) = match i { 0 => ("L", lab.l, ""), 1 => ("a", lab.a, ""), @@ -406,13 +518,14 @@ fn value_fields(ui: &mut Ui, p: &Picked, channel: Channel) -> (Option, O } /// The document's colour swatches as a list; returns the clicked swatch's colour. -fn swatch_list(app: &VectorcraftApp, ui: &mut Ui, current: &Color) -> Option { +fn swatch_list(app: &VectorcraftApp, ui: &mut Ui, current: &Color, side: f32) -> Option { let t = Tokens::get(ui.ctx()); let mut chosen = None; - ui.allocate_ui(vec2(FIELD + 28.0, FIELD), |ui| { + ui.allocate_ui(vec2(side + SLIDER_GAP + SLIDER_W, side), |ui| { + ui.set_min_size(vec2(side + SLIDER_GAP + SLIDER_W, side)); widgets::list_box(ui, |ui| { - egui::ScrollArea::vertical().id_salt("cp-swatches").max_height(FIELD).show(ui, |ui| { - ui.set_width(FIELD + 24.0); + egui::ScrollArea::vertical().id_salt("cp-swatches").max_height((side - 8.0).max(1.0)).show(ui, |ui| { + ui.set_width(side + SLIDER_GAP + SLIDER_W - 8.0); let Some(st) = app.session.active() else { widgets::dim_label(ui, tl!("Open a document to see its swatches.")); return; @@ -673,4 +786,346 @@ mod tests { super::super::confirm(&mut app).unwrap(); assert!(matches!(crate::panels::current_paints(&app).0.color(), Some(Color::Cmyk { .. }))); } + /// Inspect actual painted controls, rather than a second implementation of the layout. + #[derive(Default)] + struct Drawn { + texts: Vec<(String, Rect)>, + visible_texts: Vec, + boxes: Vec, + fields: Vec, + } + + impl Drawn { + /// Collects painted text, control bounds and color meshes, recording text visibility + /// against the clip rectangle so tests can detect clipped labels. + fn collect(&mut self, shape: &egui::Shape, clip: Rect) { + match shape { + egui::Shape::Text(t) => { + self.texts.push((t.galley.text().into(), t.visual_bounding_rect())); + if clip.expand(1.0).contains_rect(t.visual_bounding_rect()) { + self.visible_texts.push(t.galley.text().into()); + } + } + egui::Shape::Rect(r) => self.boxes.push(r.rect), + egui::Shape::Mesh(m) if m.vertices.len() > 100 => self.fields.push(m.calc_bounds()), + egui::Shape::Vec(v) => v.iter().for_each(|s| self.collect(s, clip)), + _ => {} + } + } + + /// Returns the bounds of exactly one painted label, failing on missing or duplicate text. + fn text(&self, label: &str) -> Rect { + let found: Vec<_> = self.texts.iter().filter(|(s, _)| s == label).collect(); + assert_eq!(found.len(), 1, "one {label}, including no duplicate footer: {:?}", self.texts); + found[0].1 + } + + /// Finds the smallest painted control containing a unique label's center. + fn control(&self, label: &str) -> Rect { + let center = self.text(label).center(); + self.boxes.iter().filter(|r| r.contains(center)).min_by(|a, b| a.area().total_cmp(&b.area())).copied().unwrap() + } + } + + /// Runs a dialog frame with real egui input at a physical window size, accounting for UI zoom, + /// and returns the painted controls for layout and interaction assertions. + fn draw(ctx: &egui::Context, app: &mut VectorcraftApp, size: egui::Vec2, events: Vec) -> Drawn { + let input = + egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, size / ctx.zoom_factor())), events, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + crate::shortcuts::handle(app, ui.ctx()); + super::super::show(app, ui.ctx()); + }); + let mut drawn = Drawn::default(); + for shape in &out.shapes { + drawn.collect(&shape.shape, shape.clip_rect); + } + out.textures_delta.clear(); + drawn + } + + /// The physical window size used for pointer and keyboard interaction tests. + fn screen() -> egui::Vec2 { + vec2(1280.0, 900.0) + } + + /// Lets the auto-sized dialog settle over six frames and returns the next frame's controls. + fn settled(ctx: &egui::Context, app: &mut VectorcraftApp, size: egui::Vec2) -> Drawn { + for _ in 0..6 { + draw(ctx, app, size, vec![]); + } + draw(ctx, app, size, vec![]) + } + + /// Creates a persistent test context with the application's fonts and default theme. + fn context() -> egui::Context { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + ctx + } + + /// Sends a primary pointer press and release in separate frames at the given position. + fn click_at(ctx: &egui::Context, app: &mut VectorcraftApp, at: egui::Pos2) { + for pressed in [true, false] { + draw( + ctx, + app, + screen(), + vec![ + egui::Event::PointerMoved(at), + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }, + ], + ); + } + } + + /// Creates an unmodified, non-repeating key press for dialog shortcut tests. + fn key(key: egui::Key) -> egui::Event { + egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() } + } + + /// Checks accessible action names and each channel slider's displayed value, range and units. + #[test] + fn compact_picker_preserves_screen_reader_controls_and_channel_values() { + use egui::accesskit::Role; + + for (channel, value, maximum, text) in [ + (Channel::Hue, 210.0, 360.0, "210°"), + (Channel::Saturation, 67.0, 100.0, "67%"), + (Channel::Brightness, 60.0, 100.0, "60%"), + (Channel::Red, 51.0, 255.0, "51"), + (Channel::Green, 102.0, 255.0, "102"), + (Channel::Blue, 153.0, 255.0, "153"), + ] { + let mut app = app(); + app.services.screen_color = Some(Box::new(|| Ok(std::sync::mpsc::channel().1))); + open(&mut app, &json!({"color": "#336699"})).unwrap(); + let mut d = app.ui.dialog.take().unwrap(); + d.fields.insert("channel".into(), json!(channel.id())); + let tree = widgets::accessibility_tests::tree(|ui| { + body(&mut app, ui, &mut d); + }); + let slider = tree.iter().find(|n| n.role() == Role::Slider && n.label() == Some(channel.label())).unwrap(); + assert_eq!(slider.numeric_value(), Some(value)); + assert_eq!(slider.min_numeric_value(), Some(0.0)); + assert_eq!(slider.max_numeric_value(), Some(maximum)); + assert_eq!(slider.value(), Some(text)); + for label in ["OK", "Cancel", "Color Swatches", "Sample Color from Screen"] { + assert!(tree.iter().any(|n| n.role() == Role::Button && n.label() == Some(label)), "missing button: {label}"); + } + } + } + + /// Checks aligned actions and input rows at two UI scales, and stable dimensions when + /// switching between color models and swatches. + #[test] + fn inline_actions_are_aligned_and_modes_keep_the_window_size() { + // Language selection is process-global; German is checked in the native app instead + // of racing the other parallel UI tests by changing the locale here. + for zoom in [1.0, 1.5] { + let (ctx, mut app) = (context(), app()); + ctx.set_zoom_factor(zoom); + app.run("ui.colorPicker", json!({})).unwrap(); + let drawn = settled(&ctx, &mut app, screen()); + let ok = drawn.control(tl!("OK")); + let cancel = drawn.control(tl!("Cancel")); + let toggle = drawn.control(tl!("Color Swatches")); + assert!(ok.bottom() < cancel.top() && cancel.bottom() < toggle.top()); + for r in [cancel, toggle] { + assert!((r.left() - ok.left()).abs() < 1.0 && (r.width() - ok.width()).abs() < 1.0); + } + let field = drawn.fields.iter().max_by(|a, b| a.area().total_cmp(&b.area())).unwrap(); + assert!((field.width() - field.height()).abs() < 1.0); + assert!((field.top() - ok.top()).abs() < 1.0); + let k = drawn.text("K"); + let last_input = drawn + .boxes + .iter() + .find(|r| (r.width() - VALUE_W).abs() < 0.5 && r.left() > k.right() && r.contains(egui::pos2(r.center().x, k.center().y))) + .unwrap(); + assert!((last_input.bottom() - field.bottom()).abs() < 2.0, "{last_input:?} vs {field:?}"); + // Fonts and translated actions may leave one normal gutter, but never an unused column. + assert!((last_input.right() - ok.right()).abs() < COLUMN_GAP, "no unused column beside the inputs: {last_input:?} vs {ok:?}"); + let id = egui::Id::new(("dialog", KIND)); + let before = ctx.memory(|m| m.area_rect(id)).unwrap(); + assert!(drawn.boxes.iter().all(|r| r.left() >= before.left() - 1.0 && r.right() <= before.right() + 1.0), "controls fit horizontally"); + let title = drawn.text(tl!("Color Picker")); + assert!((title.center().x - before.center().x).abs() < 1.0, "centred heading"); + assert!(title.bottom() < field.top(), "a separate title band above the content"); + assert!(drawn.visible_texts.iter().any(|s| s == tl!("Only Web Colors")), "the checkbox label is fully visible"); + assert!(drawn.text("L").top() - toggle.bottom() >= PREVIEW_GAP, "space below the actions"); + click_at(&ctx, &mut app, toggle.center()); + assert!(app.ui.dialog.as_ref().unwrap().bool("swatches")); + let drawn = settled(&ctx, &mut app, screen()); + assert!((drawn.control(tl!("Color Models")).width() - ok.width()).abs() < 1.0); + let after = ctx.memory(|m| m.area_rect(id)).unwrap(); + assert!((before.size() - after.size()).length() < 1.0, "{before:?} vs {after:?}"); + assert!( + drawn.boxes.iter().all(|r| r.left() >= after.left() - 1.0 && r.right() <= after.right() + 1.0), + "swatch controls fit horizontally" + ); + click_at(&ctx, &mut app, drawn.text(tl!("Color Models")).center()); + assert!(!app.ui.dialog.as_ref().unwrap().bool("swatches")); + } + } + + /// Clicks the sampler above the field, receives a color and checks Cancel restores the paint. + #[test] + fn sampler_above_the_field_previews_and_cancel_restores_the_original() { + let (ctx, mut app) = (context(), app()); + let (tx, rx) = std::sync::mpsc::channel(); + let mut receiver = Some(rx); + app.services.screen_color = Some(Box::new(move || receiver.take().ok_or("sampler already started".into()))); + app.run("ui.colorPicker", json!({})).unwrap(); + let original = fill_hex(&app); + let drawn = settled(&ctx, &mut app, screen()); + let field = drawn.fields.iter().max_by(|a, b| a.area().total_cmp(&b.area())).unwrap(); + let hover = egui::pos2(field.right() - 12.0, field.top() - 20.0); + draw(&ctx, &mut app, screen(), vec![egui::Event::PointerMoved(hover)]); + let drawn = settled(&ctx, &mut app, screen()); + let sampler = drawn.boxes.iter().find(|r| r.size() == vec2(24.0, 24.0) && r.bottom() < field.top()).unwrap(); + assert!(sampler.top() > drawn.text(tl!("Color Picker")).bottom() && sampler.right() <= field.right()); + click_at(&ctx, &mut app, sampler.center()); + assert!(app.screen_sampler.is_some(), "the button above the field starts the host sampler"); + tx.send(Ok(Some([0.0, 1.0, 0.0]))).unwrap(); + crate::screen_color::poll(&mut app, &ctx); + let drawn = settled(&ctx, &mut app, screen()); + assert_eq!(fill_hex(&app), "#00ff00"); + click_at(&ctx, &mut app, drawn.text(tl!("Cancel")).center()); + assert!(app.ui.dialog.is_none()); + assert_eq!(fill_hex(&app), original); + } + + /// Checks both correction warnings fit below the preview without widening the dialog, + /// and that clicking the web warning still corrects the color. + #[test] + fn warnings_fit_below_the_preview_without_widening_the_dialog() { + let (ctx, mut app) = (context(), app()); + app.run("ui.colorPicker", json!({"color":"#ffffff"})).unwrap(); + settled(&ctx, &mut app, screen()); + let id = egui::Id::new(("dialog", KIND)); + let before = ctx.memory(|m| m.area_rect(id)).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("hex".into(), json!("0000FE")); + let drawn = settled(&ctx, &mut app, screen()); + let ok = drawn.control(tl!("OK")); + let toggle = drawn.control(tl!("Color Swatches")); + let h = drawn.text("H"); + let mut warnings: Vec<_> = drawn + .boxes + .iter() + .filter(|r| (r.width() - 16.0).abs() < 0.5 && (r.height() - 16.0).abs() < 0.5 && r.bottom() < h.top()) + .copied() + .collect(); + warnings.dedup(); // The tile's fill and border share one rectangle. + assert_eq!(warnings.len(), 2, "gamut and web correction chips are both present"); + for r in &warnings { + assert!(r.right() < ok.left() && r.bottom() <= toggle.bottom()); + assert!(r.top() > ok.top() + CHIP_H, "warnings below the preview"); + } + let after = ctx.memory(|m| m.area_rect(id)).unwrap(); + assert!((before.size() - after.size()).length() < 1.0, "{before:?} vs {after:?}"); + click_at(&ctx, &mut app, warnings[1].center()); + assert!(is_web_safe(&picked(app.ui.dialog.as_ref().unwrap()).color), "web correction remains clickable"); + } + + /// Drags the custom title band and checks the dialog moves by the pointer's displacement. + #[test] + fn colour_picker_moves_by_its_title_band() { + let (ctx, mut app) = (context(), app()); + app.run("ui.colorPicker", json!({})).unwrap(); + let drawn = settled(&ctx, &mut app, screen()); + let title = drawn.text(tl!("Color Picker")).center(); + let id = egui::Id::new(("dialog", KIND)); + let before = ctx.memory(|m| m.area_rect(id)).unwrap(); + let pointer = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + draw(&ctx, &mut app, screen(), vec![egui::Event::PointerMoved(title), pointer(title, true)]); + for i in 1..=4 { + draw(&ctx, &mut app, screen(), vec![egui::Event::PointerMoved(title + vec2(6.0, 4.0) * i as f32)]); + } + draw(&ctx, &mut app, screen(), vec![pointer(title + vec2(24.0, 16.0), false)]); + settled(&ctx, &mut app, screen()); + let after = ctx.memory(|m| m.area_rect(id)).unwrap(); + assert!((after.center() - before.center() - vec2(24.0, 16.0)).length() < 1.5); + assert!(app.ui.dialog.is_some()); + } + + /// Checks OK and Enter commit typed values as one undo step, while Cancel and Escape + /// restore the original paint after a live preview. + #[test] + fn inline_ok_commits_typed_input_and_cancel_restores_the_preview() { + for enter in [false, true] { + let (ctx, mut app) = (context(), app()); + app.run("ui.colorPicker", json!({"color": "#ff0000"})).unwrap(); + let drawn = settled(&ctx, &mut app, screen()); + let undo = app.session.doc().unwrap().history.undo.len(); + // The first numeric field has selected text, just as in the other form dialogs. + draw(&ctx, &mut app, screen(), vec![egui::Event::Text("120".into())]); + if enter { + draw(&ctx, &mut app, screen(), vec![key(egui::Key::Enter)]); + } else { + click_at(&ctx, &mut app, drawn.text(tl!("OK")).center()); + } + assert!(app.ui.dialog.is_none()); + assert_eq!(fill_hex(&app), "#00ff00"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + app.run("ui.colorPicker", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("hex".into(), json!("0000ff")); + let drawn = settled(&ctx, &mut app, screen()); + assert_eq!(fill_hex(&app), "#0000ff"); + if enter { + draw(&ctx, &mut app, screen(), vec![key(egui::Key::Escape)]); + } else { + click_at(&ctx, &mut app, drawn.text(tl!("Cancel")).center()); + } + assert!(app.ui.dialog.is_none()); + assert_eq!(fill_hex(&app), "#00ff00"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + } + } + + /// Checks shrinking and stacking keep the dialog inside small windows, vertical scrolling + /// reaches the actions and last input, and Enter can still confirm. + #[test] + fn compact_picker_shrinks_then_scrolls_without_enlarging_the_window() { + for size in [vec2(740.0, 600.0), vec2(540.0, 420.0), vec2(400.0, 280.0)] { + let (ctx, mut app) = (context(), app()); + app.run("ui.colorPicker", json!({"color": "#0000ff"})).unwrap(); + let drawn = settled(&ctx, &mut app, size); + let outer = ctx.memory(|m| m.area_rect(egui::Id::new(("dialog", KIND)))).unwrap(); + assert!(outer.width() <= size.x && outer.height() <= size.y, "{outer:?} in {size:?}"); + let field = drawn.fields.iter().max_by(|a, b| a.area().total_cmp(&b.area())).unwrap(); + assert!((MIN_FIELD..=FIELD).contains(&field.width())); + assert!((field.width() - field.height()).abs() < 1.0); + assert!(drawn.boxes.iter().all(|r| r.left() >= outer.left() - 1.0 && r.right() <= outer.right() + 1.0), "controls fit horizontally"); + if size.x < 500.0 { + assert!(drawn.control(tl!("OK")).top() > field.bottom(), "narrow windows stack the controls below the field"); + let mut actions_visible = false; + let mut last_input_visible = false; + for _ in 0..30 { + draw( + &ctx, + &mut app, + size, + vec![ + egui::Event::PointerMoved(outer.min + vec2(30.0, 80.0)), + egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, -20.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + }, + ], + ); + let scrolled = settled(&ctx, &mut app, size); + actions_visible |= scrolled.visible_texts.iter().any(|s| s == tl!("OK")); + last_input_visible |= scrolled.visible_texts.iter().any(|s| s == "K"); + } + assert!(actions_visible && last_input_visible, "vertical scrolling reveals actions and the last input"); + } + // Keyboard confirmation remains available even when the actions require scrolling. + draw(&ctx, &mut app, size, vec![key(egui::Key::Enter)]); + assert!(app.ui.dialog.is_none()); + } + } } diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index 3e2c86798b..32b11744d6 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -90,6 +90,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { return Ok(json!({ "pending": EXISTS })); } fields.extend(info.defaults.as_object().cloned().unwrap_or_default()); + if super::warp_effect::is_warp(id) { + super::warp_effect::merge_remembered(&mut fields, app.last_warp.as_ref()); + } } } fields.insert("preview".into(), json!(true)); @@ -119,8 +122,12 @@ fn confirm_exists(app: &mut VectorcraftApp, d: &Dialog) -> Result let target = fields.remove("__target").unwrap_or(Value::Null); if d.bool("discard") { fields.remove("__index"); - let defaults = vectorcraft_effects::default_params(&d.str("__effect")); + let id = d.str("__effect"); + let defaults = vectorcraft_effects::default_params(&id); fields.extend(defaults.and_then(|v| v.as_object().cloned()).unwrap_or_default()); + if super::warp_effect::is_warp(id.as_str()) { + super::warp_effect::merge_remembered(&mut fields, app.last_warp.as_ref()); + } } else { let k = fields.get("__index").and_then(Value::as_u64).unwrap_or(0) as usize; fields.extend(target_effects(app, &target).get(k).map(params_of).unwrap_or_default()); @@ -147,7 +154,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } // Plug-in effects get fields from their parameter schema; colour adjustments their sliders. let changed = match vectorcraft_plugins::effect::installed(&id) { - Some(plugin) => form::schema_fields(ui, d, &plugin.manifest().params), + Some(plugin) => form::schema_fields(app, ui, d, plugin.manifest()), None if vectorcraft_effects::is_adjustment(&id) => adjust_fields(ui, d), None if id == GLASS => glass_fields(app, ui, d), None if id == TRANSFORM => transform_fields(ui, d, app.session.general_unit()), @@ -276,10 +283,12 @@ fn choices(effect: &str, key: &str) -> Option { ("brushStrokes.sprayedStrokes", "strokeDirection") => Some(&vectorcraft_effects::pixel::STROKE_DIRECTIONS), ("distort.glass", "texture") => Some(&vectorcraft_effects::pixel::GLASS_TEXTURES), ("pixelate.mezzotint", "type") => Some(&vectorcraft_effects::pixel::MEZZOTINT_TYPES), + ("sketch.graphicPen", "strokeDirection") => Some(&vectorcraft_effects::pixel::STROKE_DIRECTIONS), ("sketch.halftonePattern", "patternType") => Some(&vectorcraft_effects::pixel::HALFTONE_TYPES), + ("sketch.plaster", "lightDirection") => Some(&vectorcraft_effects::pixel::LIGHT_DIRECTIONS), ("texture.grain", "grainType") => Some(&vectorcraft_effects::pixel::GRAIN_TYPES), ("texture.texturizer", "texture") => Some(&vectorcraft_effects::pixel::TEXTURES), - ("texture.texturizer", "lightDirection") => Some(&vectorcraft_effects::pixel::LIGHT_DIRECTIONS), + ("sketch.basRelief" | "texture.texturizer", "lightDirection") => Some(&vectorcraft_effects::pixel::LIGHT_DIRECTIONS), ("video.deinterlace", "eliminate") => Some(&[("Odd Fields", "odd"), ("Even Fields", "even")]), ("video.deinterlace", "create") => Some(&[("Duplication", "duplication"), ("Interpolation", "interpolation")]), ("stylize.innerGlow", "source") => Some(&[("Center", "center"), ("Edge", "edge")]), @@ -327,7 +336,7 @@ pub(super) fn own_choices(effect: &str, key: &str, cmyk: bool) -> Option, cmyk: bool) -> Option> { if let Some(plugin) = vectorcraft_plugins::effect::installed(effect) { - return plugin.manifest().params.iter().find(|(k, _)| k == key).and_then(|(_, spec)| match spec { + return plugin.manifest().param(key).and_then(|p| match &p.spec { vectorcraft_plugins::ParamSpec::Choice { options, .. } => Some(options.iter().map(|o| (o.clone(), o.clone())).collect()), _ => None, }); @@ -673,7 +682,11 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let r = form::commit_preview(app, cmd, p.clone())?; // Last Effect repeats applied effects, not edits. if cmd == "effect.apply" { - app.last_effect = Some((d.str("__effect"), p["params"].clone())); + let id = d.str("__effect"); + app.last_effect = Some((id.clone(), p["params"].clone())); + if super::warp_effect::is_warp(id.as_str()) { + app.last_warp = Some(super::warp_effect::remembered_params(d)); + } } Ok(r) } diff --git a/crates/ui-egui/src/dialogs/export_as.rs b/crates/ui-egui/src/dialogs/export_as.rs index 60142f9624..8e55a31bdf 100644 --- a/crates/ui-egui/src/dialogs/export_as.rs +++ b/crates/ui-egui/src/dialogs/export_as.rs @@ -2,14 +2,16 @@ //! artboard, 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 for artboards as pages), -//! else the file is written. DWG is listed, greyed out, with what to use instead. +//! 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, and one +//! with parameters asks for them before writing (`plugin::open_export`). 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, png_options, save_pdf, svg_options, text_export}; +use super::{DialogSpec, dxf_options, eps_options, form, plugin, png_options, save_pdf, svg_options, text_export}; use crate::state::Dialog; use crate::theme::Tokens; use crate::{VectorcraftApp, io, widgets}; @@ -17,12 +19,21 @@ use crate::{VectorcraftApp, io, widgets}; pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Export As").into(), body, confirm, ok: Some("Export…"), min_width: 380.0, ..DialogSpec::FORM }; -/// The formats Export As writes (the native format and `.ai` are Save As's). -static FORMATS: LazyLock> = +/// The built-in formats Export As writes (the native format and `.ai` are Save As's). +static BUILT_IN: LazyLock> = LazyLock::new(|| fileio::FORMATS.iter().filter(|f| f.write && !matches!(f.id, "vectorcraft" | "ai")).collect()); /// Formats listed after them that can't be written (`fileio::unsupported` ids), greyed out. const UNAVAILABLE: [(&str, &str); 1] = [("dwg", "DWG (use DXF)")]; -static LABELS: LazyLock> = LazyLock::new(|| FORMATS.iter().map(|f| f.label).chain(UNAVAILABLE.iter().map(|u| u.1)).collect()); + +/// The formats Export As writes: the built-in ones, then those of the installed exporter plug-ins. +pub(super) fn formats() -> Vec<&'static Format> { + BUILT_IN.iter().copied().chain(fileio::plugin_formats()).collect() +} + +/// Is `f` an exporter plug-in's format? +fn from_plugin(f: &Format) -> bool { + vectorcraft_plugins::export::by_format(f.id).is_some() +} /// What to use instead when the field names a format that can't be written (DWG). fn unavailable(d: &Dialog) -> Option<(&'static str, &'static str)> { @@ -38,7 +49,7 @@ pub fn open(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) { let missing = format.and_then(|f| UNAVAILABLE.iter().find(|u| u.0.eq_ignore_ascii_case(f.trim_start_matches('.')))); let format = match missing { Some((id, _)) => id, - None => format.and_then(fileio::format).filter(|f| FORMATS.iter().any(|g| g.id == f.id)).map_or("png", |f| f.id), + None => format.and_then(fileio::format).filter(|f| formats().iter().any(|g| g.id == f.id)).map_or("png", |f| f.id), }; let range = p.get("range").and_then(Value::as_str); app.ui.dialog = Some(Dialog::new( @@ -55,7 +66,8 @@ pub fn open(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) { /// The chosen format (PNG when the field names none Export As writes). fn chosen(d: &Dialog) -> Option<&'static Format> { let id = d.str("format"); - let find = |id: &str| FORMATS.iter().copied().find(|f| f.id == id); + let all = formats(); + let find = |id: &str| all.iter().copied().find(|f| f.id == id); find(&id).or_else(|| find("png")) } @@ -66,7 +78,9 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { egui::Grid::new("export-as").num_columns(2).spacing([10.0, 8.0]).show(ui, |ui| { ui.label(egui::RichText::new(tl!("Format:")).color(t.text_dim)); let shown = missing.map_or(f.label, |(label, _)| label); - if let Some(g) = widgets::dropdown_with(ui, "export-as-format", shown, &LABELS, 160.0, |i| i < FORMATS.len()).and_then(|i| FORMATS.get(i)) { + let all = formats(); + let labels: Vec<&str> = all.iter().map(|f| f.label).chain(UNAVAILABLE.iter().map(|u| u.1)).collect(); + if let Some(g) = widgets::dropdown_with(ui, "export-as-format", shown, &labels, 160.0, |i| i < all.len()).and_then(|i| all.get(i)) { d.fields.insert("format".into(), json!(g.id)); } ui.end_row(); @@ -76,8 +90,10 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { form::caption(ui, hint); } ui.add_space(10.0); - form::check(ui, d, "useArtboards", tl!("Use Artboards")); - let use_artboards = d.bool("useArtboards"); + // An exporter plug-in writes the whole document: Use Artboards is not its to apply. + let whole = from_plugin(f); + ui.add_enabled_ui(!whole, |ui| form::check(ui, d, "useArtboards", tl!("Use Artboards"))); + let use_artboards = d.bool("useArtboards") && !whole; ui.add_enabled_ui(use_artboards, |ui| { ui.horizontal(|ui| { ui.add_space(22.0); @@ -94,6 +110,7 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.add_space(8.0); let ext = f.extensions[0]; let hint = match (use_artboards, f.id) { + _ if whole => tl!("The plug-in writes the whole document.").to_string(), (true, "pdf") => tl!("One page per artboard.").to_string(), (true, _) => crate::i18n::fmt(tl!("One file per artboard: -.{ext}"), &[("ext", ext)]), (false, _) => tl!("The bounds of the visible art.").to_string(), @@ -108,7 +125,8 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { return Err(hint.into()); } let f = chosen(d).ok_or("no format to export to")?; - let use_artboards = d.bool("useArtboards"); + let plugin = vectorcraft_plugins::export::by_format(f.id); + let use_artboards = d.bool("useArtboards") && plugin.is_none(); let all = d.bool("all"); let range = d.str("range"); if use_artboards && !all { @@ -116,8 +134,9 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let n = app.session.active().map_or(0, |s| s.doc.artboards.len()); ArtboardPick { range: Some(range.clone()), ..Default::default() }.resolve(n)?; } - // Nothing to export keeps the dialog open too (before the save dialog, not after it). - if !use_artboards && app.session.active().is_some_and(|s| vectorcraft_render::encode::art_bounds(&s.doc).is_none()) { + // Nothing to export keeps the dialog open too (before the save dialog, not after it). An + // exporter plug-in decides for itself what it can write. + if !use_artboards && plugin.is_none() && app.session.active().is_some_and(|s| vectorcraft_render::encode::art_bounds(&s.doc).is_none()) { return Err("nothing to export: the document has no visible art (or turn on Use Artboards)".into()); } app.ui.dialog = None; @@ -142,6 +161,10 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { if use_artboards { params["range"] = json!(range); } + if let Some(plugin) = plugin.filter(|p| !p.manifest().params.is_empty()) { + plugin::open_export(app, &plugin, params); + return Ok(Value::Null); + } if f.raster { png_options::open(app, f, params); return Ok(Value::Null); diff --git a/crates/ui-egui/src/dialogs/export_for_screens.rs b/crates/ui-egui/src/dialogs/export_for_screens.rs index f71847f03e..e8fc114846 100644 --- a/crates/ui-egui/src/dialogs/export_for_screens.rs +++ b/crates/ui-egui/src/dialogs/export_for_screens.rs @@ -133,6 +133,10 @@ pub(crate) fn open_assets(app: &mut VectorcraftApp, checked: Option<&[u64]>) { d.fields.insert("tab".into(), json!("assets")); if let Some(c) = checked { d.fields.insert("assets".into(), json!(c)); + // The list scrolls to the first of them once: new assets land at its end. + if let Some(first) = c.first() { + d.fields.insert("__scrollTo".into(), json!(first)); + } } } } @@ -544,9 +548,12 @@ fn assets(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { on.clear(); } }); + // Asked for until the row is in view: the dialog's first frame only measures it. + let scroll_to = d.fields.get("__scrollTo").and_then(Value::as_u64).filter(|id| st.doc.assets.iter().any(|a| a.id == *id)); + let mut in_view = scroll_to.is_none(); egui::ScrollArea::vertical().max_height(330.0).show(ui, |ui| { for a in &st.doc.assets { - ui.horizontal(|ui| { + let row = ui.horizontal(|ui| { let (r, _) = ui.allocate_exact_size(egui::vec2(46.0, 46.0), egui::Sense::hover()); crate::panels::asset_export::paint_thumb(ui, st, a, r); let checked = on.contains(&a.id); @@ -557,8 +564,18 @@ fn assets(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { } } }); + if scroll_to == Some(a.id) { + if ui.clip_rect().contains_rect(row.response.rect) { + in_view = true; + } else { + row.response.scroll_to_me(Some(egui::Align::Center)); + } + } } }); + if in_view { + d.fields.remove("__scrollTo"); + } if on != before { d.fields.insert("assets".into(), json!(on)); } diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index a1d3b54c12..a61fbdbb01 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -3,6 +3,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::Unit; +use vectorcraft_plugins::{Manifest, Param, ParamSpec}; use crate::state::Dialog; use crate::theme::Tokens; @@ -369,64 +370,175 @@ fn typed_number(x: f64) -> Value { if x.fract() == 0.0 && x.abs() < 1e15 { json!(x as i64) } else { json!(x) } } -/// Editor for a plug-in's parameters from its schema (plug-in filter and effect dialogs): numbers -/// within their range, whole numbers, checkboxes and dropdowns, in declaration order, a row each. -/// Returns true when a value changed. The labels (from the parameter keys) and choices are the -/// plug-in's text, shown as they are. A plug-in may declare more of them +/// Editor for a plug-in's parameters from its manifest (the filter, live effect and exporter +/// dialogs): numbers within their range, whole numbers, checkboxes, dropdowns, text and lists of +/// numbers, a row each. A row is labelled as the manifest says (else from the parameter's name), +/// with its unit after the value and its help on the label and on a help button that opens its +/// page. Parameters outside any group come first, then each group as a section that folds +/// ([`Manifest::sections`]); a parameter whose `visibleWhen` the values don't meet is left out +/// ([`Manifest::visible`]). Returns true when a value changed. Labels, choices, groups and help are +/// the plug-in's text, shown as they are. A plug-in may declare more parameters /// ([`MAX_PARAMS`](vectorcraft_plugins::manifest::MAX_PARAMS)) than the window has room for, and /// the rows then scroll ([`super::modal::scrolled_rows`]). -pub(super) fn schema_fields(ui: &mut egui::Ui, d: &mut Dialog, specs: &[(String, vectorcraft_plugins::ParamSpec)]) -> bool { - use vectorcraft_plugins::ParamSpec; - let t = Tokens::get(ui.ctx()); - let mut changed = false; - super::modal::scrolled_rows(ui, "plugin-fields", |ui| { - egui::Grid::new("plugin-grid").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| { - for (k, spec) in specs { - ui.label(egui::RichText::new(humanize(k)).color(t.text)); - let cur = d.fields.get(k).cloned().unwrap_or_else(|| spec.default_value()); - let new = match spec { - ParamSpec::Number { min, max, .. } => { - let x = cur.as_f64().unwrap_or(*min); - crate::widgets::range_field(ui, ("plugin-num", k), x, *min..=*max, "", 2, 100.0).map(|x| json!(x)) - } - ParamSpec::Int { min, max, .. } => { - let x = cur.as_i64().unwrap_or(*min).clamp(*min, *max); - // An f64 holds every whole number up to 2^53, so the numeric field (arrows, wheel, arithmetic) is exact there. - // Past it, the number typed is read as an integer. - const EXACT: i64 = 1 << 53; - if -EXACT <= *min && *max <= EXACT { - crate::widgets::range_field(ui, ("plugin-int", k), x as f64, *min as f64..=*max as f64, "", 0, 100.0) - .map(|x| json!(x as i64)) - } else { - let shown = x.to_string(); - crate::widgets::take_dialog_focus(ui, ui.id().with(("plugin-int", k)), &shown); - crate::widgets::text_field(ui, ("plugin-int", k), Some(&shown), 100.0, 1) - .and_then(|text| text.parse::().ok()) - .map(|x| json!(x.clamp(*min, *max))) - } - } - ParamSpec::Bool { .. } => { - let b = cur.as_bool().unwrap_or(false); - crate::widgets::check_box(ui, &humanize(k), b, true).then(|| json!(!b)) - } - ParamSpec::Choice { options, .. } => { - let labels: Vec<&str> = options.iter().map(String::as_str).collect(); - crate::widgets::dropdown_names(ui, ("plugin-choice", k), cur.as_str().unwrap_or_default(), &labels, 140.0) - .and_then(|i| options.get(i)) - .map(|o| json!(o)) - } - }; - if let Some(v) = new { - d.fields.insert(k.clone(), v); - changed = true; - } - ui.end_row(); - } - }); - }); +pub(super) fn schema_fields(app: &mut crate::VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, m: &Manifest) -> bool { + let (changed, help) = schema_rows(ui, d, m); + if let Some(url) = help { + app.open_url(&url); + } changed } +/// [`schema_fields`] → whether a value changed, and the help page asked for, left to the caller to +/// open. +pub(super) fn schema_rows(ui: &mut egui::Ui, d: &mut Dialog, m: &Manifest) -> (bool, Option) { + let mut changed = false; + let mut help = None; + let visible = m.visible(&d.fields); + let sections = m.sections(); + // Every section's label column is as wide as the longest label shown, so the fields line up + // down the dialog; the rows outside groups make up for the indent of a group's rows. + let font = egui::TextStyle::Body.resolve(ui.style()); + let label_width = (m.params.iter().filter(|(k, _)| visible.contains(k.as_str()))) + .map(|(k, p)| ui.painter().layout_no_wrap(param_label(k, p), font.clone(), egui::Color32::WHITE).size().x) + .fold(0.0, f32::max); + let indent = if sections.iter().any(|(group, _)| group.is_some()) { ui.spacing().indent } else { 0.0 }; + super::modal::scrolled_rows(ui, "plugin-fields", |ui| { + for (section, (group, params)) in sections.into_iter().enumerate() { + let shown: Vec<&(String, Param)> = params.into_iter().filter(|(k, _)| visible.contains(k.as_str())).collect(); + if shown.is_empty() { + continue; + } + let rows = |ui: &mut egui::Ui, label_width: f32| { + let grid = egui::Grid::new(("plugin-grid", section)).num_columns(2).spacing([12.0, 8.0]).min_col_width(label_width); + grid.show(ui, |ui| { + for (k, p) in shown { + let (row_changed, opened) = param_row(ui, d, k, p); + changed |= row_changed; + help = help.take().or(opened); + ui.end_row(); + } + }); + }; + match group { + None => rows(ui, label_width + indent), + Some(g) => { + egui::CollapsingHeader::new(g).id_salt(("plugin-group", g)).default_open(true).show(ui, |ui| rows(ui, label_width)); + } + } + } + }); + (changed, help) +} + +/// The label of parameter `k`'s row: its manifest `label`, else its name spaced out. +fn param_label(k: &str, p: &Param) -> String { + p.ui.label.as_ref().map_or_else(|| humanize(k), |l| format!("{l}:")) +} + +/// One row of [`schema_fields`]: parameter `k`'s label and value field → whether the value changed, +/// and the help page asked for. +fn param_row(ui: &mut egui::Ui, d: &mut Dialog, k: &str, p: &Param) -> (bool, Option) { + let t = Tokens::get(ui.ctx()); + let label = param_label(k, p); + let shown_label = ui.label(egui::RichText::new(&label).color(t.text)); + if let Some(help) = &p.ui.help { + shown_label.on_hover_text(help); + } + let cur = d.fields.get(k).cloned().unwrap_or_else(|| p.spec.default_value()); + let unit = p.ui.unit.as_deref().unwrap_or_default(); + let suffix = unit_suffix(unit); + let mut opened = None; + let new = ui + .horizontal(|ui| { + let (new, in_field) = value_field(ui, k, &label, &p.spec, &cur, &suffix); + if !in_field && !unit.is_empty() { + ui.label(egui::RichText::new(unit).color(t.text_dim)); + } + if let Some(url) = &p.ui.help_url + && crate::widgets::icon_button(ui, "external-link", tl!("Open this setting's help page"), false, 20.0).clicked() + { + opened = Some(url.clone()); + } + new + }) + .inner; + let changed = new.map(|v| d.fields.insert(k.to_string(), v)).is_some(); + (changed, opened) +} + +/// The field of parameter `k`'s value `cur` (a checkbox is called by the row's `label`) → the new +/// value when it changed, and whether the field shows `suffix` (numbers do; the other fields leave +/// the unit to a label after them). +fn value_field(ui: &mut egui::Ui, k: &str, label: &str, spec: &ParamSpec, cur: &Value, suffix: &str) -> (Option, bool) { + match spec { + ParamSpec::Number { min, max, .. } => { + let x = cur.as_f64().unwrap_or(*min); + (crate::widgets::range_field(ui, ("plugin-num", k), x, *min..=*max, suffix, 2, 100.0).map(|x| json!(x)), true) + } + ParamSpec::Int { min, max, .. } => { + let x = cur.as_i64().unwrap_or(*min).clamp(*min, *max); + // An f64 holds every whole number up to 2^53, so the numeric field (arrows, wheel, arithmetic) is exact there. + // Past it, the number typed is read as an integer. + const EXACT: i64 = 1 << 53; + if -EXACT <= *min && *max <= EXACT { + let field = crate::widgets::range_field(ui, ("plugin-int", k), x as f64, *min as f64..=*max as f64, suffix, 0, 100.0); + (field.map(|x| json!(x as i64)), true) + } else { + let shown = x.to_string(); + crate::widgets::take_dialog_focus(ui, ui.id().with(("plugin-int", k)), &shown); + let typed = crate::widgets::text_field(ui, ("plugin-int", k), Some(&shown), 100.0, 1); + (typed.and_then(|text| text.parse::().ok()).map(|x| json!(x.clamp(*min, *max))), false) + } + } + ParamSpec::Bool { .. } => { + let b = cur.as_bool().unwrap_or(false); + (crate::widgets::check_box(ui, label, b, true).then(|| json!(!b)), false) + } + ParamSpec::Choice { options, .. } => { + let labels: Vec<&str> = options.iter().map(String::as_str).collect(); + let chosen = crate::widgets::dropdown_names(ui, ("plugin-choice", k), cur.as_str().unwrap_or_default(), &labels, 140.0); + (chosen.and_then(|i| options.get(i)).map(|o| json!(o)), false) + } + ParamSpec::Text { max_length, .. } => { + let typed = crate::widgets::text_field(ui, ("plugin-text", k), cur.as_str(), 160.0, 1); + (typed.map(|text| json!(text.chars().take(*max_length).collect::())), false) + } + ParamSpec::NumberList { .. } => { + let typed = crate::widgets::text_field(ui, ("plugin-list", k), Some(&number_list_text(cur)), 160.0, 1); + (typed.and_then(|text| read_number_list(&text, spec)), false) + } + } +} + +/// A `numberList` value as its field shows it: "45, 135". +pub(crate) fn number_list_text(cur: &Value) -> String { + let numbers: Vec = cur.as_array().into_iter().flatten().filter_map(Value::as_f64).map(number_text).collect(); + numbers.join(", ") +} + +/// The list typed in a `numberList` parameter's field: numbers separated by commas, semicolons or +/// spaces, each clamped into the parameter's range. `None` (the value stays as it was) when a +/// number doesn't read, there are too few or too many, or `spec` isn't a number list. +pub(crate) fn read_number_list(text: &str, spec: &ParamSpec) -> Option { + let ParamSpec::NumberList { min, max, min_items, max_items, .. } = spec else { return None }; + let parts = text.split([',', ';', ' ']).filter(|p| !p.trim().is_empty()); + let list: Vec = parts.map(|p| vectorcraft_doc::parse_number(p).filter(|x| x.is_finite())).collect::>()?; + (*min_items..=*max_items).contains(&list.len()).then(|| json!(list.into_iter().map(|x| x.clamp(*min, *max)).collect::>())) +} + +/// What a number field shows after its value for a plug-in parameter's `unit` (none: nothing): a +/// sign such as ° or % joins the number ("45°"), and any other unit is spaced from it ("0.4 mm", +/// "5 1/min"), so a unit starting with a digit isn't read as more of the number. +pub(crate) fn unit_suffix(unit: &str) -> String { + if unit.is_empty() || unit.starts_with(['°', '%', '′', '″']) { unit.to_string() } else { format!(" {unit}") } +} + +/// A number of a list as [`value_field`] shows it: at most 4 decimals, without trailing zeros. +fn number_text(x: f64) -> String { + let s = format!("{x:.4}"); + if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.').to_string() } else { s } +} + /// A field label from its camelCase key (`miterLimit` → "Miter Limit:"). pub(crate) fn humanize(k: &str) -> String { let mut s = String::new(); @@ -453,6 +565,7 @@ pub(crate) fn humanize(k: &str) -> String { "Channel2" => "Channel 2:".into(), "Channel3" => "Channel 3:".into(), "Channel4" => "Channel 4:".into(), + "Light Dark Balance" => "Light/Dark Balance:".into(), "Include Cmy Blacks" => "Include Blacks with CMY:".into(), "Align To Path" => "Align to Path:".into(), "Overlap Variation" | "Curviness Variation" | "Spacing Variation" => "Variation:".into(), @@ -611,14 +724,21 @@ pub(super) fn preview_result( } return None; } + preview_now(app, d, label, cmd, params) +} + +/// The preview of [`preview_result`] without its checkbox: `params` run again on the interaction's +/// snapshot when they differ from the last preview. Returns the command's result only when a new +/// preview succeeds. +pub(super) fn preview_now(app: &mut crate::VectorcraftApp, d: &mut Dialog, label: &str, cmd: &str, params: Value) -> Option { let mut result = None; - if d.fields.get(LAST) != Some(¶ms) || !app.session.in_interaction() { + if d.fields.get(PREVIEWED) != Some(¶ms) || !app.session.in_interaction() { let _ = app.session.begin_interaction(label); match app.session.preview(cmd, ¶ms) { Ok(r) => result = Some(r), Err(e) => app.status(e.to_string()), } - d.fields.insert(LAST.into(), params); + d.fields.insert(PREVIEWED.into(), params); } result } @@ -707,6 +827,31 @@ pub(super) fn caption(ui: &mut egui::Ui, text: &str) { ui.label(egui::RichText::new(tl!(text)).size(11.0).color(t.text_dim)); } +#[cfg(test)] +mod plugin_field_tests { + use super::*; + + /// A unit reads after its number as it is written: a sign joins it ("45°", "50%"), anything + /// else is spaced, so a unit starting with a digit isn't read as more of the number. + #[test] + fn units_follow_the_number() { + let shown = |unit| format!("5{}", unit_suffix(unit)); + assert_eq!([shown("mm"), shown("°"), shown("%"), shown("1/min"), shown("µm")], ["5 mm", "5°", "5%", "5 1/min", "5 µm"]); + } + + #[test] + fn number_lists_read_as_typed_within_their_limits() { + let spec = ParamSpec::NumberList { min: 0.0, max: 360.0, default: vec![45.0], min_items: 1, max_items: 3 }; + assert_eq!(number_list_text(&json!([45.0, 135.5, 0.125])), "45, 135.5, 0.125"); + assert_eq!(read_number_list("10; 400 20", &spec), Some(json!([10.0, 360.0, 20.0])), "separators, and clamped"); + assert_eq!(read_number_list(" 90 , 2*45 ", &spec), Some(json!([90.0, 90.0]))); + for bad in ["", "1, 2, 3, 4", "1, x", "1, inf"] { + assert_eq!(read_number_list(bad, &spec), None, "{bad:?}"); + } + assert_eq!(read_number_list("1", &ParamSpec::Bool { default: false }), None, "not a list"); + } +} + #[cfg(test)] mod typed_number_tests { use super::*; diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index 28592c85d9..a39139f676 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -24,7 +24,7 @@ pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, min_wid pub const TOOLS: [&str; 5] = ["pencil", "paintbrush", "smooth", "blobBrush", "eraser"]; /// The options the dialog edits, in the order it shows them (a tool has those it reports). -const KEYS: [&str; 7] = ["fidelity", "size", "fill", "keepSelected", "mergeOnlySelection", "closeWithin", "editWithin"]; +const KEYS: [&str; 8] = ["fidelity", "size", "fill", "altSmooth", "keepSelected", "mergeOnlySelection", "closeWithin", "editWithin"]; /// Width of the label column: wide enough for the tolerances' labels when there are any. fn label_w(d: &Dialog) -> f32 { @@ -103,6 +103,9 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if d.fields.contains_key("fill") { check(ui, d, "fill", tl!("Fill new strokes")); } + if d.fields.contains_key("altSmooth") { + check(ui, d, "altSmooth", tl!("Alt key toggles to Smooth Tool")); + } if d.fields.contains_key("keepSelected") { check(ui, d, "keepSelected", tl!("Keep selected")); if d.fields.contains_key("mergeOnlySelection") { @@ -153,6 +156,7 @@ mod tests { "Accurate", "Smooth", "Fill new strokes", + "Alt key toggles to Smooth Tool", "Close paths when ends are within:", "Edit selected paths within:", ] { @@ -160,27 +164,40 @@ mod tests { } assert!(!text.contains("Size:"), "{text}"); let d = app.ui.dialog.as_mut().unwrap(); - assert_eq!((d.f64("fidelity", 0.0), d.bool("fill"), d.f64("closeWithin", 0.0), d.f64("editWithin", 0.0)), (1.5, false, 15.0, 12.0)); - for (k, v) in [("fidelity", json!(6.5)), ("fill", json!(true)), ("closeWithin", json!(0)), ("editWithin", json!(20))] { + assert_eq!( + (d.f64("fidelity", 0.0), d.bool("fill"), d.bool("altSmooth"), d.f64("closeWithin", 0.0), d.f64("editWithin", 0.0)), + (1.5, false, false, 15.0, 12.0) + ); + for (k, v) in + [("fidelity", json!(6.5)), ("fill", json!(true)), ("altSmooth", json!(true)), ("closeWithin", json!(0)), ("editWithin", json!(20))] + { d.fields.insert(k.into(), v); } super::super::confirm(&mut app).unwrap(); assert!(app.ui.dialog.is_none()); let o = app.session.tool_options_of("pencil"); assert_eq!( - (o["fidelity"].as_f64(), o["fill"].as_bool(), o["closeWithin"].as_f64(), o["editWithin"].as_f64()), - (Some(6.5), Some(true), Some(0.0), Some(20.0)) + (o["fidelity"].as_f64(), o["fill"].as_bool(), o["altSmooth"].as_bool(), o["closeWithin"].as_f64(), o["editWithin"].as_f64()), + (Some(6.5), Some(true), Some(true), Some(0.0), Some(20.0)) ); // The Paintbrush keeps its own: the Pencil's change left it alone. app.run("tool.options", json!({"tool": "paintbrush"})).unwrap(); let d = app.ui.dialog.as_ref().unwrap(); assert_eq!((d.f64("fidelity", 0.0), d.bool("fill")), (1.5, false)); - assert!(painted(&mut app).contains("Paintbrush Tool Options")); + let pb_text = painted(&mut app); + assert!(pb_text.contains("Paintbrush Tool Options")); + assert!(!pb_text.contains("Alt key toggles to Smooth Tool")); // Smooth has Fidelity only, the Eraser Size only, and the Blob Brush Size, Keep selected and Merge only with selection. app.run("tool.options", json!({"tool": "smooth"})).unwrap(); let text = painted(&mut app); assert!(text.contains("Smooth Tool Options") && text.contains("Fidelity:"), "{text}"); - assert!(!text.contains("Fill new strokes") && !text.contains("Keep selected") && !text.contains("Size:"), "{text}"); + assert!( + !text.contains("Fill new strokes") + && !text.contains("Keep selected") + && !text.contains("Alt key toggles to Smooth Tool") + && !text.contains("Size:"), + "{text}" + ); for tool in ["blobBrush", "eraser"] { app.run("tool.options", json!({"tool": tool})).unwrap(); let text = painted(&mut app); diff --git a/crates/ui-egui/src/dialogs/graph_data.rs b/crates/ui-egui/src/dialogs/graph_data.rs index fa9f5e65e6..33227897ca 100644 --- a/crates/ui-egui/src/dialogs/graph_data.rs +++ b/crates/ui-egui/src/dialogs/graph_data.rs @@ -593,21 +593,26 @@ mod tests { assert_eq!(sel(app.ui.dialog.as_ref().unwrap()), (0, 1), "Up"); } - #[test] - fn a_full_size_sheet_draws_only_what_is_in_view() { - let rows: Vec> = (0..MAX_GRAPH_CATEGORIES).map(|i| vec![i as f64; 256]).collect(); + /// How many buttons (the sheet's cells and the window's own) Graph Data draws in the second of two + /// frames in a 1280 × 900 window, for a graph of `categories` rows of `series` values. + fn buttons_drawn(categories: usize, series: usize) -> usize { + let rows: Vec> = (0..categories).map(|i| vec![i as f64; series]).collect(); let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); app.run("graph.create", json!({"type": "column", "x": 0, "y": 0, "width": 200, "height": 150, "rows": rows})).unwrap(); open(&mut app).unwrap(); - let ctx = egui::Context::default(); - crate::theme::install_fonts(&ctx); - let t = std::time::Instant::now(); - for _ in 0..3 { - let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::show(&mut app, ui.ctx())); - out.textures_delta.clear(); - } - assert!(t.elapsed() < std::time::Duration::from_secs(20), "{:?}", t.elapsed()); + let tree = crate::widgets::accessibility_tests::tree(|ui| super::super::show(&mut app, ui.ctx())); assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); + tree.iter().filter(|n| n.role() == egui::accesskit::Role::Button).count() + } + + #[test] + fn a_full_size_sheet_draws_only_what_is_in_view() { + // 40 categories of 40 values fill 41 × 41 cells of a 42 × 42 sheet, larger than the view both ways: it + // draws some cells, but fewer than the data fill. + let some = buttons_drawn(40, 40); + assert!(some > 20 && some < 41 * 41, "{some} buttons"); + // A full-size sheet draws the same cells in view, and none more. + assert_eq!(buttons_drawn(MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES), some); } } diff --git a/crates/ui-egui/src/dialogs/layers_panel_options.rs b/crates/ui-egui/src/dialogs/layers_panel_options.rs index 87b93d4085..72e518fdeb 100644 --- a/crates/ui-egui/src/dialogs/layers_panel_options.rs +++ b/crates/ui-egui/src/dialogs/layers_panel_options.rs @@ -1,8 +1,9 @@ -//! Layers panel › Panel Options…: Show Layers Only, the row size and which rows show thumbnails. +//! Layers panel › Panel Options…: Show Layers Only, Locate Selected Objects, the row size and +//! which rows show thumbnails. //! -//! Fields: `layersOnly`, `rowSize` (`small`, `medium`, `large` or `other`), `otherSize` (points, -//! 12–100, for `other`), `thumbLayers`, `thumbGroups` and `thumbObjects`. OK applies them to the -//! panel (kept with the UI state). +//! Fields: `layersOnly`, `locateSelected`, `rowSize` (`small`, `medium`, `large` or `other`), +//! `otherSize` (points, 12–100, for `other`), `thumbLayers`, `thumbGroups` and `thumbObjects`. OK +//! applies them to the panel (kept with the UI state). use serde_json::{Value, json}; @@ -25,7 +26,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result { let o = &app.ui.layers_panel; let size = SIZES.iter().find(|s| (s.2 - o.row()).abs() < 0.01).map_or("other", |s| s.0); let fields = json!({ - "layersOnly": o.layers_only, "rowSize": size, "otherSize": o.row(), + "layersOnly": o.layers_only, "locateSelected": o.locate_selected, "rowSize": size, "otherSize": o.row(), "thumbLayers": o.thumb_layers, "thumbGroups": o.thumb_groups, "thumbObjects": o.thumb_objects, }); app.ui.dialog = Some(Dialog::new(KIND, fields)); @@ -41,6 +42,7 @@ fn check(ui: &mut egui::Ui, d: &mut Dialog, key: &str, text: &str) { fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { check(ui, d, "layersOnly", tl!("Show Layers Only")); + check(ui, d, "locateSelected", tl!("Locate Selected Objects")); ui.add_space(8.0); grid(ui, |ui| { label(ui, tl!("Row Size:")); @@ -73,6 +75,7 @@ pub(crate) fn options(d: &Dialog) -> PanelOptions { let row_size = SIZES.iter().find(|s| s.0 == size).map_or_else(|| (d.f64("otherSize", f64::from(ROW_MEDIUM)) as f32).clamp(12.0, 100.0), |s| s.2); PanelOptions { layers_only: d.bool("layersOnly"), + locate_selected: d.bool("locateSelected"), row_size: if row_size.is_finite() { row_size } else { ROW_MEDIUM }, thumb_layers: d.bool("thumbLayers"), thumb_groups: d.bool("thumbGroups"), @@ -115,4 +118,23 @@ mod tests { super::super::confirm(&mut app).unwrap(); assert_eq!(app.ui.layers_panel.row(), ROW_LARGE); } + + /// Locate Selected Objects is off by default and in options saved without it; OK turns it on + /// and keeps it with the UI state, and the dialog opens on it again. + #[test] + fn locate_selected_objects_is_off_by_default_and_kept_with_the_ui_state() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.run("ui.layersPanelOptions", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(d.fields.get("locateSelected"), Some(&json!(false))); + d.fields.insert("locateSelected".into(), json!(true)); + super::super::confirm(&mut app).unwrap(); + let back: crate::UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap(); + assert!(back.layers_panel.locate_selected, "kept with the UI state"); + app.run("ui.layersPanelOptions", json!({})).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().bool("locateSelected")); + let old: crate::UiState = serde_json::from_value(json!({"layers_panel": {"layersOnly": true}})).unwrap(); + assert!(old.layers_panel.layers_only && !old.layers_panel.locate_selected, "options saved without it"); + } } diff --git a/crates/ui-egui/src/dialogs/live_paint_selection.rs b/crates/ui-egui/src/dialogs/live_paint_selection.rs new file mode 100644 index 0000000000..a7e4c4149c --- /dev/null +++ b/crates/ui-egui/src/dialogs/live_paint_selection.rs @@ -0,0 +1,142 @@ +//! Live Paint Selection Tool Options (double-click the Live Paint Selection tool): what a click +//! with the tool selects and how the face or edge under the pointer highlights. The options last +//! across tool switches and are saved with the preferences. OK sets them with +//! `tool.setOption {tool: "livePaintSelection", values}`. +//! +//! Fields: `selectFills` and `selectStrokes` (the faces and the edges of Live Paint groups), +//! `color` (the highlight color: `#rrggbb`, or a layer color's name such as "Red") and `width` +//! (the highlight's width in screen pixels). + +use serde_json::{Map, Value, json}; +use vectorcraft_color::Color; +use vectorcraft_doc::LAYER_COLORS; +use vectorcraft_tools::builder::LP_SELECT_WIDTH_RANGE; + +use super::tile_edge_color::resolve; +use super::{DialogSpec, form, run_and_close}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of the Live Paint Selection Tool Options. +pub const KIND: &str = "livePaintSelectionOptions"; + +/// The tool the dialog serves. +const TOOL: &str = "livePaintSelection"; + +/// The options the dialog edits. +const KEYS: [&str; 4] = ["selectFills", "selectStrokes", "color", "width"]; + +/// Width of the label column. +const LABEL_W: f32 = 60.0; + +pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, min_width: 300.0, ..DialogSpec::FORM }; + +fn heading(_: &Dialog) -> String { + let label = vectorcraft_tools::tool_info(TOOL).map_or("", |t| t.label); + crate::i18n::fmt(tl!("{tool} Options"), &[("tool", tl!(label))]) +} + +/// Open the Live Paint Selection Tool Options with the tool's current values. +pub fn open(app: &mut VectorcraftApp) -> Result { + let o = app.session.tool_options_of(TOOL); + let fields: Map = KEYS.iter().filter_map(|key| Some((key.to_string(), o.get(*key)?.clone()))).collect(); + app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); + Ok(json!({ "dialog": KIND })) +} + +fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + form::check(ui, d, "selectFills", tl!("Select Fills")); + form::check(ui, d, "selectStrokes", tl!("Select Strokes")); + ui.add_space(6.0); + let color = resolve(&d.str("color")).unwrap_or(Color::BLACK); + let [r, g, b, _] = color.to_rgba8(1.0); + let preset = LAYER_COLORS.iter().position(|(_, c)| *c == [r, g, b]); + let names: Vec<&str> = LAYER_COLORS.iter().map(|(n, _)| *n).chain(["Custom"]).collect(); + widgets::label_row(ui, tl!("Color:"), LABEL_W, |ui| { + if let Some((_, [r, g, b])) = + widgets::dropdown(ui, "lp-select-color", names[preset.unwrap_or(LAYER_COLORS.len())], &names, 130.0).and_then(|i| LAYER_COLORS.get(i)) + { + d.fields.insert("color".into(), json!(Color::rgb8(*r, *g, *b).to_hex())); + } + // The color button sets any other color; the dropdown then shows Custom. + let mut rgb = [r, g, b]; + if ui.color_edit_button_srgb(&mut rgb).changed() { + d.fields.insert("color".into(), json!(Color::rgb8(rgb[0], rgb[1], rgb[2]).to_hex())); + } + }); + let (min, max) = LP_SELECT_WIDTH_RANGE; + let v = d.f64("width", min); + widgets::label_row(ui, tl!("Width:"), LABEL_W, |ui| { + if let Some(x) = widgets::plain_field(ui, "lp-select-width", v, "px", 0, 72.0) { + d.fields.insert("width".into(), json!(x.round().clamp(min, max))); + } + }); + false +} + +/// OK: set the tool's options. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); + run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + use vectorcraft_tools::{Overlay, PointerEvent, PointerKind}; + + /// 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())) + } + + #[test] + fn double_clicking_the_tool_opens_its_options_and_ok_sets_them() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + // Two squares side by side, made a Live Paint group: two faces and the edge between them. + for x in [0, 100] { + app.run("shape.rectangle", json!({"x": 50 + x, "y": 50, "width": 100, "height": 100})).unwrap(); + } + app.run("select.all", json!({})).unwrap(); + app.run("livePaint.make", json!({})).unwrap(); + app.run("select.set", json!({"ids": []})).unwrap(); + app.select_tool(TOOL); + let click = |app: &mut VectorcraftApp, x: f64| { + let view = app.view_info(); + crate::canvas::dispatch(app, &PointerEvent::new(PointerKind::Down, x, 100.0), view); + crate::canvas::dispatch(app, &PointerEvent::new(PointerKind::Up, x, 100.0), view); + app.session.doc().unwrap().selection.objects.len() + }; + assert_eq!(click(&mut app, 100.0), 1, "a face is selected by default"); + + app.run("tool.options", json!({"tool": TOOL})).unwrap(); + let text = painted(&mut app); + for label in ["Live Paint Selection Tool Options", "Select Fills", "Select Strokes", "Color:", "Width:"] { + assert!(text.contains(label), "{label} in {text}"); + } + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(d.kind, KIND); + assert_eq!((d.bool("selectFills"), d.bool("selectStrokes"), d.str("color"), d.f64("width", 0.0)), (true, true, "#ff2a2a".to_string(), 4.0)); + d.fields.insert("selectFills".into(), json!(false)); + d.fields.insert("color".into(), json!("Green")); + d.fields.insert("width".into(), json!(8)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + // The tool takes them: a click inside a face selects nothing, and the highlight shows the edge + // in the new color and width. + assert_eq!(click(&mut app, 100.0), 0); + let view = app.view_info(); + crate::canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::Move, 151.0, 100.0), view); + let ov = app.session.overlays(view); + assert!(ov.iter().any(|o| matches!(o, Overlay::Path { color: [0x4f, 0xff, 0x4f], width: 8.0, .. })), "{ov:?}"); + // They last while another tool is chosen, and the dialog opens on them again. + app.select_tool("selection"); + let o = app.session.tool_options_of(TOOL); + assert_eq!((o["selectFills"].as_bool(), o["color"].as_str(), o["width"].as_f64()), (Some(false), Some("#4fff4f"), Some(8.0))); + app.run("tool.options", json!({"tool": TOOL})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.bool("selectFills"), d.str("color")), (false, "#4fff4f".to_string())); + } +} diff --git a/crates/ui-egui/src/dialogs/mod.rs b/crates/ui-egui/src/dialogs/mod.rs index bc6504d624..8ca1a2b84e 100644 --- a/crates/ui-egui/src/dialogs/mod.rs +++ b/crates/ui-egui/src/dialogs/mod.rs @@ -51,6 +51,7 @@ pub mod layer_options; pub mod layers_panel_options; pub mod liquify; pub mod live_paint_gaps; +pub mod live_paint_selection; pub mod missing_fonts; pub mod missing_links; pub(crate) mod modal; @@ -88,6 +89,7 @@ pub mod save_swatch_library; pub mod script_check; mod shapes; pub mod shortcut_import; +pub(crate) mod simplify_slider; pub mod slices; pub mod spot_colors; pub(crate) mod svg_options; @@ -118,7 +120,7 @@ pub(crate) use export_for_screens::{ KIND as EXPORT_FOR_SCREENS, formats as screen_formats, open_assets as open_export_for_screens_assets, saved_options as screen_saved_options, saved_rows as screen_saved_rows, }; -pub(crate) use form::humanize; +pub(crate) use form::{humanize, number_list_text, read_number_list, unit_suffix}; pub(crate) use new_document::preset_name; pub use new_document::{open as open_new_document, preset_card}; pub use png_options::open as open_raster_options; @@ -134,6 +136,15 @@ type DialogResult = Result; const MARGIN: i8 = 22; const EDGE_GAP: f32 = 8.0; +/// An action requested by a dialog that draws its buttons inside its body. +#[derive(Default)] +pub(crate) enum DialogAction { + #[default] + None, + Confirm, + Cancel, +} + /// How a dialog draws and applies itself. Specs start from [`DialogSpec::FORM`] and override what /// differs. pub(crate) struct DialogSpec { @@ -142,8 +153,12 @@ pub(crate) struct DialogSpec { /// The heading (and window title), in the UI language: the spec translates its own text and /// leaves names in it (a document's, a plug-in's) as they are. pub heading: fn(&Dialog) -> String, + /// Optional heading band inside the shared window; normal dialogs use `modal::heading`. + pub header: Option, /// Draws the fields. Returns true to close the dialog as Cancel would. pub body: fn(&mut VectorcraftApp, &mut egui::Ui, &mut Dialog) -> bool, + /// Optional body with inline buttons; replaces `body` and the shared footer. + pub body_with_actions: Option DialogAction>, /// OK, Enter or `ui.dialog.confirm`: applies the dialog and closes it when done. pub confirm: fn(&mut VectorcraftApp, &Dialog) -> DialogResult, /// The OK button's label. None: no OK button, Enter does nothing and Cancel reads "Close". @@ -166,10 +181,12 @@ impl DialogSpec { pub const FORM: Self = Self { window: None, heading: |_| tl!("Dialog").into(), + header: None, body: |app, ui, d| { form::grid(ui, d, app.session.general_unit()); false }, + body_with_actions: None, confirm: |app, _| { app.ui.dialog = None; Ok(Value::Null) @@ -307,8 +324,10 @@ registry! { PrintPreset: [print::PRESET_KIND] => print::PRESET_SPEC, PrintPresets: [print_presets::KIND] => print_presets::SPEC, Plugin: [plugin::KIND] => plugin::SPEC, + PluginExport: [plugin::EXPORT_KIND] => plugin::EXPORT_SPEC, ScriptCheck: [script_check::KIND] => script_check::SPEC, VectorHalftone: [halftone::KIND] => halftone::SPEC, + SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC, PerspectiveGrid: [perspective_grid::KIND] => perspective_grid::SPEC, Envelope: [envelope::WARP, envelope::MESH, envelope::OPTIONS] => envelope::SPEC, LiquifyOptions: [liquify::KIND] => liquify::SPEC, @@ -320,6 +339,7 @@ registry! { PerspectiveGridOptions: [perspective_options::KIND] => perspective_options::SPEC, BlendOptions: [blend_options::KIND] => blend_options::SPEC, LivePaintGaps: [live_paint_gaps::KIND] => live_paint_gaps::SPEC, + LivePaintSelectionOptions: [live_paint_selection::KIND] => live_paint_selection::SPEC, BrushOptions: [brush_options::KIND] => brush_options::SPEC, EditSelection: [edit_selection::KIND] => edit_selection::SPEC, PerspectivePlane: [perspective_plane::KIND] => perspective_plane::SPEC, @@ -402,6 +422,8 @@ pub(crate) fn settle(app: &mut VectorcraftApp) { /// until Enter has been let go. pub(crate) const AFTER_PANEL: &str = "__afterPanel"; +/// 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) { about::show(app, ctx); settle(app); @@ -461,18 +483,33 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { 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)); ui.set_max_width(spec.max_width.map_or(room, |w| w.min(room))); - modal::heading(ui, &heading); + if let Some(header) = spec.header { + header(ui, &heading); + } else { + modal::heading(ui, &heading); + } ui.add_space(12.0); // Just opened: its first enabled field takes the keyboard focus, as in the reference app // (type a value, press Enter). Only the body's fields can take it. if focus_first { ui.data_mut(|m| m.insert_temp(widgets::dialog_focus_flag(), true)); } - cancel = (spec.body)(app, ui, &mut d); + if let Some(body) = spec.body_with_actions { + match body(app, ui, &mut d) { + DialogAction::None => {} + DialogAction::Confirm => ok = true, + DialogAction::Cancel => cancel = true, + } + } else { + cancel = (spec.body)(app, ui, &mut d); + } // Taken (the flag is gone): done. Still there (the window's measuring frame): next frame. if focus_first && ui.data_mut(|m| m.remove_temp::(widgets::dialog_focus_flag())).is_none() { ui.data_mut(|m| m.remove::(focus_id)); } + if spec.body_with_actions.is_some() { + return; + } ui.add_space(16.0); // The button row is as wide as the fields above it and as tall as the buttons: a // right-to-left layout would otherwise take all the room left in the window, so the @@ -541,6 +578,10 @@ mod tests_import_pdf; #[cfg(test)] mod tests_package; #[cfg(test)] +mod tests_plugin_export; +#[cfg(test)] +mod tests_plugin_fields; +#[cfg(test)] mod tests_raster_formats; #[cfg(test)] mod tests_svg_options_range; diff --git a/crates/ui-egui/src/dialogs/path_ops.rs b/crates/ui-egui/src/dialogs/path_ops.rs index 162435462a..c46096a00e 100644 --- a/crates/ui-egui/src/dialogs/path_ops.rs +++ b/crates/ui-egui/src/dialogs/path_ops.rs @@ -101,9 +101,18 @@ fn split_grid(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { form::check(ui, d, "addGuides", tl!("Add Guides")); } +/// The fields the Simplify dialog opens with at `tolerance` (points): the slider's tolerance when +/// its More Options opens the dialog. +pub(crate) fn simplify_dialog(tolerance: f64) -> Value { + json!({"tolerance": tolerance, "angleThreshold": ANGLE_THRESHOLD, "straightLines": false, "showOriginal": false, "retain": false, "preview": true}) +} + +/// The fields the Simplify dialog keeps when OK confirms it with `retain` ticked. +const SIMPLIFY_KEPT: [&str; 6] = ["tolerance", "angleThreshold", "straightLines", "showOriginal", "retain", "preview"]; + /// Simplify's fields: Tolerance, Corner Point Angle Threshold (its label above a slider from 0° on -/// the left, the smoothest, to 180°, the sharpest), Convert to Straight Lines and Show Original -/// Path. +/// the left, the smoothest, to 180°, the sharpest), Convert to Straight Lines, Show Original Path +/// and Open this dialog with these settings next time. fn simplify_fields(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { let rail = Tokens::get(ui.ctx()).input_border; egui::Grid::new("dlg").num_columns(2).spacing([10.0, 8.0]).show(ui, |ui| { @@ -115,6 +124,7 @@ fn simplify_fields(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { ui.add_space(8.0); form::check(ui, d, "straightLines", tl!("Convert to Straight Lines")); form::check(ui, d, "showOriginal", tl!("Show Original Path")); + form::check(ui, d, "retain", tl!("Open this dialog with these settings next time")); } /// Simplify's Show Original Path: while the dialog previews with it on, every path the preview ran @@ -175,6 +185,12 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { return run_and_close(app, id, params); } let r = form::commit_preview(app, id, params)?; + // Simplify: with retain ticked, the menu item opens this dialog on these fields next time; with it + // unticked, the menu item opens the slider. + if d.kind == "simplify" { + let kept = SIMPLIFY_KEPT.into_iter().filter_map(|k| Some((k.to_string(), d.fields.get(k)?.clone()))); + app.ui.simplify = if d.bool("retain") { Value::Object(kept.collect()) } else { Value::Null }; + } // The fields as the dialog held them, so they show as typed when it opens again. if d.kind == "offsetPath" { let kept = ["offset", "joins", "miterLimit"].into_iter().filter_map(|k| Some((k.to_string(), d.fields.get(k)?.clone()))); diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index d2e9cad222..152e8f0258 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -5,10 +5,13 @@ //! effect dialog (`effect.dialog`). A filter with parameters opens dialog `plugin`: one field per //! declared parameter (fields named after them; `__plugin` is the plug-in id) with a live //! Preview, and OK keeps the run as one undo step (`plugin.run`). A filter without parameters runs -//! at once. +//! at once. Exporters are formats of File › Export › Export As; one with parameters opens dialog +//! `pluginExport` once the file is picked, and its Export button writes the file. + +use std::sync::Arc; use serde_json::{Map, Value, json}; -use vectorcraft_plugins::{Kind, registry}; +use vectorcraft_plugins::{Kind, Manifest, Plugin, registry}; use super::{DialogSpec, form}; use crate::VectorcraftApp; @@ -70,34 +73,49 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { let id = p.get("id").and_then(Value::as_str).ok_or("missing `id` (see plugin.list)")?; let plugin = registry::get(id).ok_or_else(|| format!("no plug-in {id:?} is installed"))?; let m = plugin.manifest(); - if m.kind != Kind::Filter { - return Err(format!("{} is a live effect (Effect › Plug-ins)", m.name)); + match m.kind { + Kind::Filter => {} + Kind::Effect => return Err(format!("{} is a live effect (Effect › Plug-ins)", m.name)), + Kind::Exporter => return Err(format!("{} is an exporter (File › Export › Export As…)", m.name)), } let given = p.get("params").filter(|v| v.as_object().is_some_and(|o| !o.is_empty())); if m.params.is_empty() || given.is_some() { return app.run(CMD, json!({"id": id, "params": given.cloned().unwrap_or(Value::Null)})); } - let mut fields: Map = m.defaults(); - fields.insert("__plugin".into(), json!(id)); - fields.insert("__label".into(), json!(m.name.trim_end_matches('…'))); + let mut fields = fields_for(m); fields.insert("preview".into(), json!(true)); app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); Ok(Value::Null) } +/// The fields of plug-in `m`'s dialog: its parameters at their defaults, `__plugin` (its id) and +/// `__label` (its name, the heading). +fn fields_for(m: &Manifest) -> Map { + let mut fields = m.defaults(); + fields.insert("__plugin".into(), json!(m.id)); + fields.insert("__label".into(), json!(m.name.trim_end_matches('…'))); + fields +} + +/// The plug-in dialog `d` is for, its description drawn above the fields. `None` once it was +/// uninstalled, which closes the dialog. +fn described(ui: &mut egui::Ui, d: &Dialog) -> Option> { + let plugin = registry::get(&d.str("__plugin"))?; + let m = plugin.manifest(); + if !m.description.is_empty() { + ui.label(egui::RichText::new(&m.description).color(crate::theme::Tokens::get(ui.ctx()).text_dim)); + ui.add_space(8.0); + } + Some(plugin) +} + fn params(d: &Dialog) -> Value { json!({"id": d.str("__plugin"), "params": form::params(d)}) } fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - // A plug-in uninstalled while its dialog is open closes it. - let Some(plugin) = registry::get(&d.str("__plugin")) else { return true }; - let m = plugin.manifest(); - if !m.description.is_empty() { - ui.label(egui::RichText::new(&m.description).color(crate::theme::Tokens::get(ui.ctx()).text_dim)); - ui.add_space(8.0); - } - form::schema_fields(ui, d, &m.params); + let Some(plugin) = described(ui, d) else { return true }; + form::schema_fields(app, ui, d, plugin.manifest()); let (label, p) = (d.str("__label"), params(d)); form::preview(app, ui, d, &label, CMD, p); false @@ -106,3 +124,40 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { form::commit_preview(app, CMD, params(d)) } + +/// The dialog kind of an exporter's parameters, after Export As picked the file. +pub const EXPORT_KIND: &str = "pluginExport"; + +/// Headed by the plug-in's name, as it is; Export writes the file. +pub(super) const EXPORT_SPEC: DialogSpec = DialogSpec { + heading: |d| d.str("__label"), + body: export_body, + confirm: export_confirm, + ok: Some("Export"), + max_width: Some(420.0), + ..DialogSpec::FORM +}; + +/// Export As with exporter `plugin`, which has parameters: its fields at their defaults, and +/// `export`, the export's own parameters (`format`, `path`, …), kept for Export. +pub fn open_export(app: &mut VectorcraftApp, plugin: &Plugin, export: Value) { + let mut fields = fields_for(plugin.manifest()); + fields.insert("__export".into(), export); + app.ui.dialog = Some(Dialog { kind: EXPORT_KIND.into(), fields }); +} + +fn export_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let Some(plugin) = described(ui, d) else { return true }; + form::schema_fields(app, ui, d, plugin.manifest()); + false +} + +/// Writes the file with the export's parameters and the plug-in's, as `params`. +fn export_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let mut p = d.fields.get("__export").cloned().filter(Value::is_object).ok_or("no format to export to")?; + p["params"] = form::params(d); + let format = p.get("format").and_then(Value::as_str).map(str::to_string); + let path = p.get("path").and_then(Value::as_str).map(str::to_string); + app.ui.dialog = None; + crate::io::export(app, format.as_deref(), path, &p) +} diff --git a/crates/ui-egui/src/dialogs/shapes.rs b/crates/ui-egui/src/dialogs/shapes.rs index 9df9280cca..55181043bf 100644 --- a/crates/ui-egui/src/dialogs/shapes.rs +++ b/crates/ui-egui/src/dialogs/shapes.rs @@ -2,10 +2,13 @@ //! Star, Line Segment Tool Options and the two grids (size, divider counts and skews, switches). use serde_json::{Value, json}; +use vectorcraft_geom::{Point, Rect}; use super::{DialogSpec, form, run_and_close}; use crate::VectorcraftApp; +use crate::panels::transform::artboard_rect; use crate::state::Dialog; +use crate::widgets; pub(super) const SPEC: DialogSpec = DialogSpec { heading: |d| title(&d.kind).into(), body, confirm, ..DialogSpec::FORM }; @@ -27,9 +30,57 @@ fn grid_keys(kind: &str) -> ([&'static str; 2], [&'static str; 2]) { if kind == "polarGrid" { (["concentric", "radial"], ["concentricSkew", "radialSkew"]) } else { (["rows", "columns"], ["rowSkew", "columnSkew"]) } } +/// The 9-point locator index for a grid dialog (`reference`, default top-left). +fn grid_reference(d: &Dialog) -> usize { + d.fields.get("reference").and_then(|v| v.as_u64()).map(|n| (n as usize).min(8)).unwrap_or(0) +} + +/// A grid dialog's bounding box from its top-left `x`/`y` and size fields. +fn grid_placed(d: &Dialog) -> Rect { + let (x, y) = (d.f64("x", 0.0), d.f64("y", 0.0)); + Rect::new(x, y, x + d.f64("width", 100.0), y + d.f64("height", 100.0)) +} + +fn set_grid_placed(d: &mut Dialog, r: Rect) { + d.fields.insert("x".into(), json!(r.x0)); + d.fields.insert("y".into(), json!(r.y0)); + d.fields.insert("width".into(), json!(r.width())); + d.fields.insert("height".into(), json!(r.height())); +} + +/// Top-left `x`/`y` so reference point `refi` sits on the canvas click (`__anchorX`/`__anchorY`). +pub(crate) fn grid_pin_to_anchor(d: &mut Dialog) { + let anchor = Point::new(d.f64("__anchorX", d.f64("x", 0.0)), d.f64("__anchorY", d.f64("y", 0.0))); + let refi = grid_reference(d); + let (w, h) = (d.f64("width", 100.0), d.f64("height", 100.0)); + let rp = vectorcraft_geom::reference_point(Rect::new(0.0, 0.0, w, h), refi); + d.fields.insert("x".into(), json!(anchor.x - rp.x)); + d.fields.insert("y".into(), json!(anchor.y - rp.y)); +} + /// The form's fields, then a grid's switches. fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - form::grid(ui, d, app.session.general_unit()); + let unit = app.session.general_unit(); + if matches!(d.kind.as_str(), "rectangularGrid" | "polarGrid") { + ui.horizontal(|ui| { + let refi = grid_reference(d); + if let Some(i) = widgets::reference_point(ui, refi) { + d.fields.insert("reference".into(), json!(i)); + grid_pin_to_anchor(d); + } + }); + ui.add_space(4.0); + let refi = grid_reference(d); + let (was, w0, h0) = (grid_placed(d), d.f64("width", 100.0), d.f64("height", 100.0)); + form::grid_then(ui, d, unit, |_, d| { + let (w, h) = (d.f64("width", 100.0), d.f64("height", 100.0)); + if (w - w0).abs() > 1e-9 || (h - h0).abs() > 1e-9 { + set_grid_placed(d, artboard_rect(was, refi, None, None, Some(w), Some(h), false)); + } + }); + } else { + form::grid(ui, d, unit); + } let own = match d.kind.as_str() { "rectangularGrid" => ("frame", tl!("Use Outside Rectangle As Frame")), "polarGrid" => ("compound", tl!("Create Compound Path From Ellipses")), @@ -54,8 +105,9 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { kind @ ("rectangularGrid" | "polarGrid") => { // The switches as they are; the typed fields as numbers. let (mut p, (counts, skews)) = (form::params(d), grid_keys(kind)); - for (k, default) in [("width", 100.0), ("height", 100.0)] { - p[k] = json!(d.f64(k, default)); + let r = grid_placed(d); + for (k, v) in [("x", r.x0), ("y", r.y0), ("width", r.width()), ("height", r.height())] { + p[k] = json!(v); } for (count, skew) in counts.into_iter().zip(skews) { p[count] = json!((d.f64(count, 5.0) as u64).min(999)); diff --git a/crates/ui-egui/src/dialogs/simplify_slider.rs b/crates/ui-egui/src/dialogs/simplify_slider.rs new file mode 100644 index 0000000000..a1c8871dea --- /dev/null +++ b/crates/ui-egui/src/dialogs/simplify_slider.rs @@ -0,0 +1,165 @@ +//! Object › Path › Simplify's slider: a strip under the selection with Auto-Simplify, a slider from +//! the fewest anchor points (left) to the closest fit to the original (right), and More Options, +//! which opens the Simplify dialog at the slider's tolerance. While the strip is open, the canvas +//! previews `object.path.simplify {level}`; Enter or a click outside the strip keeps the result as +//! one undo step, and Escape puts the paths back. The slider opens at level 50, a tolerance of +//! 1 pt (`vectorcraft_pathops::simplify_level_tolerance` maps levels to tolerances). +//! +//! Fields: `level` (0..=100, the command's parameter). + +use egui::{Color32, CornerRadius, Order, Pos2, Sense, Stroke, vec2}; +use serde_json::{Value, json}; +use vectorcraft_engine::{SIMPLIFY_LEVEL, simplify_level_tolerance}; +use vectorcraft_geom::Rect; + +use super::{DialogResult, DialogSpec, form, modal}; +use crate::state::Dialog; +use crate::theme::Tokens; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of the Simplify slider. +pub(crate) const KIND: &str = "simplifySlider"; + +pub(super) const SPEC: DialogSpec = DialogSpec { window: Some(show), confirm, preview: true, ..DialogSpec::FORM }; + +/// The command the slider previews, and its undo label. +const CMD: &str = "object.path.simplify"; +const LABEL: &str = "Simplify"; + +/// The fields the slider opens with. +pub(crate) fn fields() -> Value { + json!({ "level": SIMPLIFY_LEVEL }) +} + +/// Whether the Simplify slider is open. +pub(crate) fn showing(app: &VectorcraftApp) -> bool { + app.ui.dialog.as_ref().is_some_and(|d| d.kind == KIND) +} + +/// The slider's level, a whole number from 0 to 100. +fn level(d: &Dialog) -> f64 { + let l = d.f64("level", SIMPLIFY_LEVEL); + if l.is_finite() { l.round().clamp(0.0, 100.0) } else { SIMPLIFY_LEVEL } +} + +fn params(d: &Dialog) -> Value { + json!({ "level": level(d) }) +} + +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { + form::commit_preview(app, CMD, params(d)) +} + +/// The open slider, or an error when it isn't open. +fn open_slider(app: &VectorcraftApp) -> Result { + app.ui.dialog.clone().filter(|d| d.kind == KIND).ok_or_else(|| "the Simplify slider is not open".to_string()) +} + +/// Auto-Simplify (`ui.simplifyAuto`): the open slider moves to the level `object.path.simplify +/// {auto: true}` picks for the selection, and the canvas previews it → {level}. +pub(crate) fn auto(app: &mut VectorcraftApp) -> Result { + let mut d = open_slider(app)?; + let _ = app.session.begin_interaction(LABEL); + let r = app.session.preview(CMD, &json!({ "auto": true })).map_err(|e| e.to_string())?; + let level = r["level"].as_f64().unwrap_or(SIMPLIFY_LEVEL); + d.fields.insert("level".into(), json!(level)); + d.fields.insert(form::PREVIEWED.into(), params(&d)); + app.ui.dialog = Some(d); + Ok(json!({ "level": level })) +} + +/// More Options (`ui.simplifyMoreOptions`): the Simplify dialog takes the slider's place, at the +/// slider's tolerance → {tolerance}. +pub(crate) fn more_options(app: &mut VectorcraftApp) -> Result { + let d = open_slider(app)?; + let tolerance = simplify_level_tolerance(level(&d)); + app.ui.dialog = Some(Dialog::new("simplify", super::path_ops::simplify_dialog(tolerance))); + Ok(json!({ "tolerance": tolerance })) +} + +/// The private field that holds the selection's bounds before the preview, `[x0, y0, x1, y1]`. +const BOUNDS: &str = "__bounds"; + +/// The selection's bounds before the preview: the interaction's snapshot when a preview runs, read +/// once and kept in `d`, so the strip stays where it opened while the preview changes the paths. +fn bounds(app: &mut VectorcraftApp, d: &mut Dialog) -> Option { + if let Some([x0, y0, x1, y1]) = d.fields.get(BOUNDS).and_then(|v| serde_json::from_value::<[f64; 4]>(v.clone()).ok()) { + return Some(Rect::new(x0, y0, x1, y1)); + } + let b = match app.session.active().and_then(|st| st.interaction.as_ref()) { + Some(it) => it.doc.bounds_of(&it.selection.objects, true), + None => app.selection_bounds(), + }?; + d.fields.insert(BOUNDS.into(), json!([b.x0, b.y0, b.x1, b.y1])); + Some(b) +} + +/// Where the strip goes: under the lowest corner on screen of `bounds` (the selection's, before the +/// preview), centered on them, kept on the canvas. +fn place(app: &mut VectorcraftApp, ctx: &egui::Context, id: egui::Id, bounds: Option) -> Pos2 { + let size = egui::AreaState::load(ctx, id).and_then(|s| s.size).unwrap_or(vec2(270.0, 42.0)); + let screen = ctx.content_rect(); + let Some((rect, view)) = app.canvas_rect.zip(app.view().copied()) else { return screen.center() - size / 2.0 }; + let xf = crate::canvas::Xf::new(rect, &view); + let under = match bounds { + Some(b) => { + let lowest = xf.quad(b).iter().map(|c| c.y).fold(f32::NEG_INFINITY, f32::max); + Pos2::new(xf.to_screen(b.center()).x - size.x / 2.0, lowest + 28.0) + } + None => rect.center() - size / 2.0, + }; + let bounds = rect.shrink(8.0); + under.clamp(bounds.min, (bounds.max - size).max(bounds.min)) +} + +/// What a button of the strip asked for. +enum Action { + Auto, + MoreOptions, +} + +fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { + let Some(mut d) = app.ui.dialog.clone() else { return }; + let t = Tokens::get(ctx); + let id = egui::Id::new(("dialog", KIND)); + let b = bounds(app, &mut d); + let pos = place(app, ctx, id, b); + // A click anywhere else keeps the result, and the rest of the app doesn't take it. + let dim = modal::backdrop(); + let outside = + egui::Area::new(dim.id).order(dim.order).fixed_pos(Pos2::ZERO).show(ctx, |ui| ui.allocate_rect(ctx.content_rect(), Sense::click())).inner; + let mut action = None; + egui::Area::new(id).order(Order::Foreground).fixed_pos(pos).show(ctx, |ui| { + egui::Frame::NONE + .fill(t.panel) + .stroke(Stroke::new(1.0, t.tool_active)) + .corner_radius(CornerRadius::same(5)) + .inner_margin(egui::Margin::symmetric(8, 6)) + .shadow(egui::epaint::Shadow { offset: [0, 3], blur: 10, spread: 0, color: Color32::from_black_alpha(70) }) + .show(ui, |ui| { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + if widgets::icon_button(ui, "wand-sparkles", tl!("Auto-Simplify"), false, 28.0).clicked() { + action = Some(Action::Auto); + } + let rail = t.input_border; + form::slider_rail_named(ui, &mut d, "level", tl!("Simplify"), 0.0..=100.0, &|_| rail); + if widgets::icon_button(ui, "ellipsis", tl!("More Options"), false, 28.0).clicked() { + action = Some(Action::MoreOptions); + } + }); + }); + }); + let p = params(&d); + let _ = form::preview_now(app, &mut d, LABEL, CMD, p); + app.ui.dialog = Some(d); + let r = match action { + Some(Action::Auto) => auto(app), + Some(Action::MoreOptions) => more_options(app), + None if outside.clicked() || ctx.input(|i| i.key_pressed(egui::Key::Enter)) => super::confirm(app), + None => Ok(Value::Null), + }; + if let Err(e) = r { + app.status(e); + } +} diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 2d12c7fd2b..be41199baf 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -202,6 +202,9 @@ fn raster_filter_dialogs_preview_and_apply() { ("artistic.cutout", "levels", "6"), ("artistic.neonGlow", "color", "#ff00ff"), ("artistic.posterEdges", "edgeThickness", "5"), + ("artistic.smudgeStick", "strokeLength", "6"), + ("artistic.sponge", "definition", "20"), + ("artistic.watercolor", "texture", "2"), ("blur.radial", "method", "zoom"), ("blur.smart", "quality", "high"), ("blur.smart", "blurMode", "overlayEdge"), @@ -210,7 +213,12 @@ fn raster_filter_dialogs_preview_and_apply() { ("pixelate.crystallize", "cellSize", "20"), ("pixelate.mezzotint", "type", "longLines"), ("pixelate.pointillize", "cellSize", "12"), + ("sketch.basRelief", "lightDirection", "left"), + ("sketch.charcoal", "thickness", "5"), ("sketch.halftonePattern", "patternType", "line"), + ("sketch.photocopy", "darkness", "40"), + ("sketch.stamp", "lightDarkBalance", "10"), + ("sketch.plaster", "lightDirection", "bottomLeft"), ("texture.craquelure", "crackDepth", "9"), ("texture.grain", "grainType", "stippled"), ("texture.mosaicTiles", "tileSize", "20"), @@ -474,6 +482,10 @@ fn menu_parameter_dialogs_are_compact() { app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); app.run("select.all", json!({})).unwrap(); crate::menus::invoke(&mut app, id, json!({})); + // Simplify opens its slider; More Options opens the dialog. + if id == "object.path.simplify" { + app.run("ui.simplifyMoreOptions", json!({})).unwrap(); + } assert!(app.ui.dialog.is_some(), "{id} opened no dialog"); let wide = dialog_rect(&mut app, 1600.0); eprintln!("{id}: {:.0} × {:.0} in a 1600-point window", wide.width(), wide.height()); @@ -510,7 +522,7 @@ fn given_headings_are_shown_as_they_are() { struct PluginIntField { ctx: egui::Context, d: Dialog, - specs: Vec<(String, vectorcraft_plugins::ParamSpec)>, + m: vectorcraft_plugins::Manifest, pos: egui::Pos2, } @@ -519,8 +531,17 @@ impl PluginIntField { let ctx = egui::Context::default(); theme::install_fonts(&ctx); theme::apply(&ctx, Default::default()); - let specs = vec![("seed".into(), vectorcraft_plugins::ParamSpec::Int { min, max, default: 0 })]; - let mut f = PluginIntField { ctx, d: Dialog::new(plugin::KIND, json!({ "seed": start })), specs, pos: egui::Pos2::ZERO }; + let m = vectorcraft_plugins::Manifest { + id: "test.seed".into(), + name: "Seed".into(), + version: String::new(), + kind: vectorcraft_plugins::Kind::Filter, + description: String::new(), + author: String::new(), + params: vec![("seed".into(), vectorcraft_plugins::ParamSpec::Int { min, max, default: 0 }.into())], + extensions: Vec::new(), + }; + let mut f = PluginIntField { ctx, d: Dialog::new(plugin::KIND, json!({ "seed": start })), m, pos: egui::Pos2::ZERO }; fn number_rect(shape: &egui::Shape, text: &str) -> Option { match shape { egui::Shape::Text(t) if t.galley.text() == text => Some(t.visual_bounding_rect()), @@ -534,9 +555,9 @@ impl PluginIntField { } fn run(&mut self, events: Vec) -> egui::FullOutput { - let (d, specs) = (&mut self.d, &self.specs); + let (d, m) = (&mut self.d, &self.m); let mut out = self.ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| { - form::schema_fields(ui, d, specs); + form::schema_rows(ui, d, m); }); out.textures_delta.clear(); out @@ -1019,6 +1040,72 @@ fn artboard_options_position_follows_the_tool_option_with_another_tool() { } } +/// #1482: with Artboards 1 and 3 selected with the Artboard tool, a new Width in Artboard Options +/// goes to both, each keeping its top-left corner and its height, in one undo step. The new name +/// goes only to the artboard the dialog shows, and Artboard 2 keeps its size. A name alone resizes +/// nothing. +#[test] +fn artboard_options_width_resizes_every_selected_artboard() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100, "artboards": 3})).unwrap(); + app.run("artboard.setProps", json!({"index": 2, "width": 300, "height": 150})).unwrap(); + app.select_tool("artboard"); + crate::panels::artboards::select(&mut app, 0); + app.session.set_tool_option("selected", &json!([0, 2])); + let boards = |app: &VectorcraftApp| app.session.doc().unwrap().doc.artboards.clone(); + let before = boards(&app); + let undo = app.session.doc().unwrap().history.undo.len(); + crate::dialogs::artboard_options::open(&mut app).unwrap(); + let fields = &mut app.ui.dialog.as_mut().unwrap().fields; + fields.insert("width".into(), json!("250 pt")); + fields.insert("name".into(), json!("Cover")); + frame(&mut app, Default::default()); + super::confirm(&mut app).unwrap(); + let mut want = before.clone(); + want[0].name = "Cover".into(); + for i in [0, 2] { + want[i].rect.x1 = want[i].rect.x0 + 250.0; + } + assert_eq!(boards(&app), want); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(boards(&app), before); + crate::dialogs::artboard_options::open(&mut app).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("name".into(), json!("Cover")); + frame(&mut app, Default::default()); + super::confirm(&mut app).unwrap(); + want = before.clone(); + want[0].name = "Cover".into(); + assert_eq!(boards(&app), want, "a name alone"); +} + +/// #1482 with #1876: a Width typed in Artboard Options resizes each selected artboard about the +/// reference point the form uses, the center by default, as the Transform panel's W does. +#[test] +fn artboard_options_width_resizes_every_selected_artboard_about_the_reference_point() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300, "artboards": 2})).unwrap(); + app.select_tool("artboard"); + crate::panels::artboards::select(&mut app, 0); + app.session.set_tool_option("selected", &json!([0, 1])); + let before: Vec = app.session.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + crate::dialogs::artboard_options::open(&mut app).unwrap(); + let mut f = Frames::new(); + let shown = f.texts(&mut app); + let (width, height) = (field_after(&shown, "Width:"), field_after(&shown, "Height:")); + f.press(&mut app, width, true); + f.press(&mut app, width, false); + f.run(&mut app, vec![egui::Event::Text("500".into())]); + // A click on Height ends the Width field's editing. + f.press(&mut app, height, true); + f.press(&mut app, height, false); + f.key(&mut app, egui::Key::Enter, egui::Modifiers::NONE); + assert!(app.ui.dialog.is_none(), "Enter applies the dialog"); + let after: Vec = app.session.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + let want: Vec = before.iter().map(|r| vectorcraft_geom::Rect::new(r.x0 - 50.0, r.y0, r.x1 + 50.0, r.y1)).collect(); + assert_eq!(after, want); +} + /// The strings a frame painted, each with its rectangle. fn painted(out: &egui::FullOutput) -> Vec<(String, egui::Rect)> { fn walk(s: &egui::Shape, v: &mut Vec<(String, egui::Rect)>) { diff --git a/crates/ui-egui/src/dialogs/tests_modal.rs b/crates/ui-egui/src/dialogs/tests_modal.rs index cee3d1cc6b..8831949161 100644 --- a/crates/ui-egui/src/dialogs/tests_modal.rs +++ b/crates/ui-egui/src/dialogs/tests_modal.rs @@ -144,12 +144,13 @@ fn check_plugin_dialog(kind: &str, count: usize, check: impl FnOnce(&egui::Conte /// settings is as tall as they are. #[test] fn a_plug_in_dialog_of_many_settings_fits_the_window() { - use vectorcraft_plugins::manifest::MAX_PARAMS; + // As many as a plug-in may declare outside groups. + use vectorcraft_plugins::manifest::MAX_UNGROUPED; let screen = Rect::from_min_size(Pos2::ZERO, SCREEN); let shown = |texts: &[(String, Rect)], text: &str| texts.iter().find(|(t, r)| t == text && screen.contains_rect(*r)).map(|(_, r)| *r); for kind in ["effect", "filter"] { - check_plugin_dialog(kind, MAX_PARAMS, |ctx, app, window, heading| { - let last = format!("Setting{}:", MAX_PARAMS - 1); + check_plugin_dialog(kind, MAX_UNGROUPED, |ctx, app, window, heading| { + let last = format!("Setting{}:", MAX_UNGROUPED - 1); let texts = frame(ctx, app, vec![]); let rect = rect_of(ctx, window); assert!(screen.contains_rect(rect) && rect.height() > 0.75 * SCREEN.y, "{kind}: the dialog is at {rect:?} in the {SCREEN:?} window"); @@ -292,13 +293,181 @@ fn app_with_dense_path() -> VectorcraftApp { app } +/// Object › Path › Simplify, then the slider's More Options: the Simplify dialog. +fn open_simplify_dialog(app: &mut VectorcraftApp) { + crate::menus::invoke(app, "object.path.simplify", json!({})); + app.run("ui.simplifyMoreOptions", json!({})).unwrap(); +} + +/// The anchors of the paths in `app`'s document. +fn anchor_count(app: &VectorcraftApp) -> usize { + let mut n = 0; + app.session.doc().unwrap().doc.walk(|node| { + if let vectorcraft_doc::NodeKind::Path { path, .. } = &node.kind { + n += path.anchor_count(); + } + }); + n +} + +/// The parameters of the Simplify preview on the canvas. +fn simplify_preview(app: &VectorcraftApp) -> serde_json::Value { + app.session.doc().unwrap().interaction.as_ref().and_then(|it| it.preview.clone()).expect("a preview").1 +} + +/// The Simplify slider's strip, and the centers of its Auto-Simplify button, its rail and its More +/// Options button. +fn slider_strip(ctx: &egui::Context) -> (Rect, Pos2, Pos2, Pos2) { + let r = rect_of(ctx, egui::Id::new(("dialog", simplify_slider::KIND))); + let y = r.center().y; + (r, Pos2::new(r.left() + 8.0 + 14.0, y), Pos2::new(r.left() + 8.0 + 28.0 + 6.0 + 90.0, y), Pos2::new(r.right() - 8.0 - 14.0, y)) +} + +/// Object › Path › Simplify opens a slider under the selection that previews the 1 pt result. +/// Dragging it to the right previews more anchor points and to the left fewer, and Enter keeps the +/// result as one undo step. +#[test] +fn simplify_opens_a_slider_whose_drag_previews_fewer_or_more_points() { + let (ctx, mut app) = (ctx(), app_with_dense_path()); + let undo_len = app.session.doc().unwrap().history.undo.len(); + crate::menus::invoke(&mut app, "object.path.simplify", json!({})); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(simplify_slider::KIND)); + settle(&ctx, &mut app); + assert_eq!(simplify_preview(&app), json!({"level": 50.0})); + assert_eq!(anchor_count(&app), 2, "the 1 pt result"); + let (_, _, rail, _) = slider_strip(&ctx); + drag(&ctx, &mut app, rail, vec2(100.0, 0.0)); + assert_eq!(simplify_preview(&app), json!({"level": 100.0})); + let most = anchor_count(&app); + assert!(most > 2, "{most}"); + let (_, _, rail, _) = slider_strip(&ctx); + drag(&ctx, &mut app, rail + vec2(90.0, 0.0), vec2(-190.0, 0.0)); + assert_eq!(simplify_preview(&app), json!({"level": 0.0})); + assert_eq!(anchor_count(&app), 2); + frame( + &ctx, + &mut app, + vec![Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }], + ); + assert!(app.ui.dialog.is_none() && !app.session.in_interaction()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo_len + 1); + assert_eq!(anchor_count(&app), 2); +} + +/// Escape, taken by the app's key handling before the dialog layer draws, closes the Simplify +/// slider and puts the paths back as they were, with no undo step. +#[test] +fn simplify_slider_escape_puts_the_paths_back() { + let (ctx, mut app) = (ctx(), app_with_dense_path()); + let before = app.session.doc().unwrap().doc.clone(); + let undo_len = app.session.doc().unwrap().history.undo.len(); + crate::menus::invoke(&mut app, "object.path.simplify", json!({})); + settle(&ctx, &mut app); + let (_, _, rail, _) = slider_strip(&ctx); + drag(&ctx, &mut app, rail, vec2(100.0, 0.0)); + assert_eq!(simplify_preview(&app), json!({"level": 100.0})); + assert_ne!(app.session.doc().unwrap().doc, before, "the preview changes the path"); + let escape = Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, SCREEN)), events: vec![escape], ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + crate::shortcuts::handle(&mut app, ui.ctx()); + show(&mut app, ui.ctx()); + }); + out.textures_delta.clear(); + assert!(app.ui.dialog.is_none() && !app.session.in_interaction()); + assert_eq!(app.session.doc().unwrap().doc, before); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo_len); + assert_eq!(anchor_count(&app), 20); +} + +/// The Simplify slider stays where it opened, under the paths as they were, while the preview +/// changes their bounds, so a drag doesn't move the rail under the pointer. +#[test] +fn simplify_slider_stays_where_it_opened_while_the_preview_changes_the_bounds() { + let ctx = ctx(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.canvas_rect = Some(Rect::from_min_size(Pos2::ZERO, SCREEN)); + // A hump 20 pt high, which level 0 (32 pt) fits with a lower curve, seen at 400%. + let anchors: Vec<_> = (0..20).map(|i| json!({"x": 30 + i * 15, "y": 100.0 + 20.0 * (std::f64::consts::PI * i as f64 / 19.0).sin()})).collect(); + app.run("path.create", json!({"anchors": anchors})).unwrap(); + app.run("view.setZoom", json!({"zoom": 400})).unwrap(); + app.view_mut().unwrap().center = vectorcraft_geom::Point::new(172.5, 60.0); + let before = app.selection_bounds().unwrap(); + crate::menus::invoke(&mut app, "object.path.simplify", json!({})); + settle(&ctx, &mut app); + let opened = rect_of(&ctx, egui::Id::new(("dialog", simplify_slider::KIND))); + app.ui.dialog.as_mut().unwrap().fields.insert("level".into(), json!(0)); + settle(&ctx, &mut app); + assert_eq!(simplify_preview(&app), json!({"level": 0.0})); + let after = app.selection_bounds().unwrap(); + assert!(after.height() < before.height() - 0.5, "the preview changes the bounds: {before:?} → {after:?}"); + assert_eq!(rect_of(&ctx, egui::Id::new(("dialog", simplify_slider::KIND))), opened); +} + +/// Auto-Simplify moves the slider to the level that keeps the path within 1/400 of its size, and a +/// click outside the strip keeps the result as one undo step. +#[test] +fn simplify_slider_auto_simplify_and_a_click_outside_keep_the_result() { + let (ctx, mut app) = (ctx(), app_with_dense_path()); + let before = app.session.doc().unwrap().doc.clone(); + let undo_len = app.session.doc().unwrap().history.undo.len(); + crate::menus::invoke(&mut app, "object.path.simplify", json!({})); + settle(&ctx, &mut app); + let (_, auto, ..) = slider_strip(&ctx); + click(&ctx, &mut app, auto); + // The path is 285 pt wide: 0.7125 pt at most, level 55. + assert_eq!(app.ui.dialog.as_ref().unwrap().f64("level", 0.0), 55.0); + assert_eq!(app.session.doc().unwrap().interaction.as_ref().and_then(|it| it.preview.clone()).unwrap().1, json!({"auto": true})); + frame(&ctx, &mut app, vec![]); + assert_eq!(anchor_count(&app), 2); + assert!(app.session.in_interaction(), "the result waits for a click outside"); + click(&ctx, &mut app, Pos2::new(20.0, 20.0)); + assert!(app.ui.dialog.is_none() && !app.session.in_interaction()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo_len + 1); + assert_ne!(app.session.doc().unwrap().doc, before); +} + +/// More Options opens the Simplify dialog at the slider's tolerance. With "Open this dialog with +/// these settings next time" ticked, OK makes the menu item open the dialog on its settings; with +/// it unticked, the slider again. +#[test] +fn simplify_slider_more_options_and_the_dialog_that_opens_directly() { + let (ctx, mut app) = (ctx(), app_with_dense_path()); + crate::menus::invoke(&mut app, "object.path.simplify", json!({})); + app.ui.dialog.as_mut().unwrap().fields.insert("level".into(), json!(60)); + settle(&ctx, &mut app); + assert_eq!(simplify_preview(&app), json!({"level": 60.0})); + let (_, _, _, more) = slider_strip(&ctx); + click(&ctx, &mut app, more); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), d.f64("tolerance", 0.0), d.bool("retain")), ("simplify", 0.5, false)); + settle(&ctx, &mut app); + assert_eq!(simplify_preview(&app)["tolerance"], json!(0.5)); + let texts = frame(&ctx, &mut app, vec![]); + let retain = texts.iter().find(|(t, _)| t == "Open this dialog with these settings next time").map(|(_, r)| *r).expect("the checkbox"); + click(&ctx, &mut app, retain.center()); + app.ui.dialog.as_mut().unwrap().fields.insert("straightLines".into(), json!(true)); + confirm(&mut app).unwrap(); + crate::menus::invoke(&mut app, "object.path.simplify", json!({})); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!((d.kind.as_str(), d.f64("tolerance", 0.0), d.bool("straightLines"), d.bool("retain")), ("simplify", 0.5, true, true)); + app.ui.dialog.as_mut().unwrap().fields.insert("retain".into(), json!(false)); + confirm(&mut app).unwrap(); + crate::menus::invoke(&mut app, "object.path.simplify", json!({})); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(simplify_slider::KIND)); + assert!(app.run("ui.simplifyAuto", json!({})).is_ok()); + cancel(&mut app); + assert!(app.run("ui.simplifyMoreOptions", json!({})).is_err(), "the slider is not open"); +} + #[test] fn simplify_dialog_preview_counts_and_cancel_restore_the_original() { let (ctx, mut app) = (ctx(), app_with_dense_path()); let before = app.session.doc().unwrap().doc.clone(); let selection = app.session.doc().unwrap().selection.clone(); let undo_len = app.session.doc().unwrap().history.undo.len(); - crate::menus::invoke(&mut app, "object.path.simplify", json!({})); + open_simplify_dialog(&mut app); settle(&ctx, &mut app); let texts = frame(&ctx, &mut app, vec![]); let preview = texts.iter().find(|(t, _)| t == "Preview").map(|(_, r)| *r).expect("a Preview checkbox"); @@ -337,7 +506,7 @@ fn simplify_dialog_ok_keeps_exactly_one_undo_with_or_without_preview() { let before = app.session.doc().unwrap().doc.clone(); let selection = app.session.doc().unwrap().selection.clone(); let undo_len = app.session.doc().unwrap().history.undo.len(); - crate::menus::invoke(&mut app, "object.path.simplify", json!({})); + open_simplify_dialog(&mut app); app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(on)); settle(&ctx, &mut app); if on { @@ -381,7 +550,7 @@ fn only_straight_segments(app: &VectorcraftApp) -> bool { fn simplify_dialog_sends_corner_angle_and_straight_lines() { let (ctx, mut app) = (ctx(), app_with_selection()); app.run("shape.ellipse", json!({"x": 100, "y": 200, "width": 160, "height": 90})).unwrap(); - crate::menus::invoke(&mut app, "object.path.simplify", json!({})); + open_simplify_dialog(&mut app); settle(&ctx, &mut app); let texts = frame(&ctx, &mut app, vec![]); assert!(texts.iter().any(|(t, _)| t == "Corner Point Angle Threshold:"), "{texts:?}"); @@ -407,7 +576,7 @@ fn simplify_dialog_corner_point_angle_threshold_keeps_or_smooths_corners() { let (ctx, mut app) = (ctx(), app_with_selection()); app.run("edit.clear", json!({})).unwrap(); app.run("shape.polygon", json!({"cx": 200, "cy": 200, "radius": 100, "sides": 8})).unwrap(); - crate::menus::invoke(&mut app, "object.path.simplify", json!({})); + open_simplify_dialog(&mut app); app.ui.dialog.as_mut().unwrap().fields.insert("tolerance".into(), json!("10 pt")); settle(&ctx, &mut app); assert!(only_straight_segments(&app), "the corners stay and the sides stay straight"); @@ -426,7 +595,7 @@ fn simplify_dialog_show_original_path_outlines_the_paths_before_the_preview() { Some((id, vectorcraft_doc::NodeKind::Path { path, .. })) => (id, path.clone()), _ => panic!("a path is selected"), }; - crate::menus::invoke(&mut app, "object.path.simplify", json!({})); + open_simplify_dialog(&mut app); settle(&ctx, &mut app); let texts = frame(&ctx, &mut app, vec![]); assert!(super::path_ops::original_paths(&app).is_empty(), "Show Original Path is off as the dialog opens"); diff --git a/crates/ui-egui/src/dialogs/tests_plugin_export.rs b/crates/ui-egui/src/dialogs/tests_plugin_export.rs new file mode 100644 index 0000000000..85156326f0 --- /dev/null +++ b/crates/ui-egui/src/dialogs/tests_plugin_export.rs @@ -0,0 +1,116 @@ +//! Exporter plug-ins in File › Export › Export As: listed after the built-in formats, written +//! whole (Use Artboards is not theirs to apply), and their parameters asked for once the file is +//! picked. Each test installs exporters of its own: plug-ins are process-wide. + +use serde_json::{Value, json}; +use vectorcraft_plugins::wat::{self as tpl, Echo}; + +use super::tests_export::{app, frame, kind, names, set}; +use super::*; + +fn install(app: &mut VectorcraftApp, src: &str) { + let wasm = wat::parse_str(src).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm)})).unwrap(); +} + +#[test] +fn export_as_lists_exporters_and_writes_their_file_whole() { + let (mut app, written) = app(2); + install(&mut app, &tpl::returning(&tpl::exporter("test.ui.whole", r#"["tuw"]"#, "{}"), r#"{"dataBase64":"SGk=","warnings":["a note"]}"#)); + // After the built-in formats, with the other exporters installed. + let listed: Vec<&str> = export_as::formats().iter().map(|f| f.id).collect(); + let first = listed.iter().position(|id| id.starts_with("plugin.")).expect("an exporter listed"); + let added = listed.get(first..).unwrap_or_default(); + assert!(added.iter().all(|id| id.starts_with("plugin.")) && added.contains(&"plugin.test.ui.whole"), "{listed:?}"); + // It isn't a filter: Object › Plug-ins' command says where it is. + let e = app.run("plugin.dialog", json!({"id": "test.ui.whole"})).unwrap_err(); + assert!(e.contains("is an exporter (File › Export › Export As…)"), "{e}"); + + app.run("file.exportAs", json!({"format": "plugin.test.ui.whole"})).unwrap(); + assert_eq!(kind(&app), Some("exportAs")); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("format"), "plugin.test.ui.whole"); + // Use Artboards is greyed out and doesn't apply: one file of the whole document. + set(&mut app, "useArtboards", json!(true)); + frame(&mut app); + confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none(), "an exporter without parameters writes at once"); + assert_eq!(names(&written), ["/out/Untitled-1.tuw"]); + assert_eq!(written.borrow()[0].1, b"Hi"); + assert!(app.ui.status.contains("a note"), "{}", app.ui.status); +} + +#[test] +fn an_exporter_with_parameters_asks_for_them_once_the_file_is_picked() { + let (mut app, written) = app(1); + let params = r#"{"density":{"type":"number","min":0,"max":10,"default":4}}"#; + install(&mut app, &tpl::echo_exporter(&tpl::exporter("test.ui.params", r#"["tup"]"#, params), Echo::Params)); + // Asked for by its extension, as agents may. + app.run("file.exportAs", json!({"format": "tup"})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("format"), "plugin.test.ui.params"); + confirm(&mut app).unwrap(); + assert_eq!(kind(&app), Some(plugin::EXPORT_KIND)); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("__label"), d.fields.get("density")), ("Test test.ui.params".to_string(), Some(&json!(4.0)))); + assert!(written.borrow().is_empty(), "nothing written before Export"); + frame(&mut app); + set(&mut app, "density", json!(7)); + confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(names(&written), ["/out/Untitled-1.tup"]); + let sent: Value = serde_json::from_slice(&written.borrow()[0].1).unwrap(); + assert_eq!(sent, json!({"density": 7.0, "_context": {"mode": "export", "extension": "tup", "name": "Untitled-1"}})); +} + +/// `CRAFT_UI_PLUGIN_EXPORT_SHOT=` saves the pictures of the dialogs to that folder: Export As +/// with an exporter's format chosen, then the exporter's own dialog. The plug-in is a test one with +/// parameters a plotter's exporter could have, saved beside them (`plotter-test-exporter.wasm`) to +/// install in the app. +#[test] +fn export_as_and_exporter_dialog_pictures() { + let Some(dir) = std::env::var_os("CRAFT_UI_PLUGIN_EXPORT_SHOT") else { return }; + let dir = std::path::PathBuf::from(dir); + let (mut app, _) = app(1); + let params = r#"{"speed":{"type":"number","min":1,"max":100,"default":40},"passes":{"type":"int","min":1,"max":10,"default":1}, + "optimizeTravel":{"type":"bool","default":true},"paper":{"type":"choice","options":["A4","A3","Letter"],"default":"A4"}}"#; + let manifest = r#"{"id":"org.example.plotter","name":"Plotter (test exporter)","version":"1","kind":"exporter","extensions":["plt"], + "description":"Writes the document as pen plotter commands.","params":PARAMS}"# + .replace("PARAMS", params); + let src = tpl::echo_exporter(&manifest, Echo::Params); + std::fs::write(dir.join("plotter-test-exporter.wasm"), wat::parse_str(&src).unwrap()).unwrap(); + install(&mut app, &src); + app.run("file.exportAs", json!({"format": "plugin.org.example.plotter"})).unwrap(); + let shot = |app: VectorcraftApp, name: &str| -> VectorcraftApp { + let mut ready = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(720.0, 520.0)).wgpu().build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !ready { + crate::theme::install_fonts(ui.ctx()); + crate::theme::apply(ui.ctx(), crate::theme::Brightness::MediumDark); + ready = true; + return; + } + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(6); + h.render().unwrap().save(dir.join(name)).unwrap(); + h.into_state() + }; + app = shot(app, "export-as-exporter.png"); + confirm(&mut app).unwrap(); + assert_eq!(kind(&app), Some(plugin::EXPORT_KIND)); + shot(app, "exporter-options.png"); +} + +/// A plug-in that declines keeps nothing written and says why. +#[test] +fn a_declining_exporter_writes_nothing() { + let (mut app, written) = app(1); + install(&mut app, &tpl::returning(&tpl::exporter("test.ui.declines", r#"["tud"]"#, "{}"), r#"{"error":"Nothing to plot."}"#)); + app.run("file.exportAs", json!({"format": "plugin.test.ui.declines"})).unwrap(); + let r = confirm(&mut app); + assert!(written.borrow().is_empty()); + let said = r.err().unwrap_or_default() + &app.ui.status; + assert!(said.contains("Nothing to plot."), "{said}"); +} diff --git a/crates/ui-egui/src/dialogs/tests_plugin_fields.rs b/crates/ui-egui/src/dialogs/tests_plugin_fields.rs new file mode 100644 index 0000000000..8a66bc8a94 --- /dev/null +++ b/crates/ui-egui/src/dialogs/tests_plugin_fields.rs @@ -0,0 +1,171 @@ +//! A plug-in's parameters in its dialog as its manifest presents them (docs/plugins.md › +//! Parameters): labels, units after the values, help on the labels and a button to its page, +//! sections by group, text and lists of numbers, and parameters shown only while their +//! `visibleWhen` holds. The plug-in is removed after each test: plug-ins are process-wide. + +use std::sync::{Arc, Mutex}; + +use egui::vec2; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use vectorcraft_engine::Session; +use vectorcraft_plugins::wat as tpl; + +use super::*; + +/// A filter whose parameters use every presentation key. +fn manifest(id: &str) -> String { + format!( + r#"{{"id":"{id}","name":"Hatch Test","version":"1","kind":"filter","params":{{ + "outline":{{"type":"bool","default":true,"label":"Outline"}}, + "title":{{"type":"string","default":"Poster","maxLength":8,"label":"Title"}}, + "pattern":{{"type":"choice","options":["lines","crosshatch","dots"],"default":"lines","label":"Pattern", + "group":"Fill","help":"How the shape is filled."}}, + "spacing":{{"type":"number","min":0.1,"max":10,"default":0.25,"label":"Spacing","unit":"mm","group":"Fill", + "helpUrl":"https://example.org/params/spacing","visibleWhen":{{"pattern":["lines","crosshatch"]}}}}, + "angles":{{"type":"numberList","min":0,"max":360,"default":[45,135],"minItems":1,"maxItems":4,"label":"Angles", + "unit":"°","group":"Fill","visibleWhen":{{"pattern":["lines","crosshatch"]}}}}, + "width":{{"type":"number","min":0,"max":10,"default":0.5,"label":"Width","unit":"pt","group":"Outline", + "visibleWhen":{{"outline":[true]}}}}}}}}"# + ) +} + +/// The dialog of plug-in `id` in a kittest harness; the web pages it opens go to `opened`. +fn harness(id: &str, opened: Arc>>) -> Harness { + let services = crate::Services { open_url: Some(Box::new(move |u: &str| opened.lock().unwrap().push(u.to_string()))), ..Default::default() }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let wasm = wat::parse_str(tpl::module(&manifest(id), tpl::ECHO, "", 1)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm)})).unwrap(); + app.run("plugin.dialog", json!({"id": id})).unwrap(); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 800.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + h +} + +type Harness = egui_kittest::Harness<'static, VectorcraftApp>; + +/// The text label `text` (a checkbox is called by its row's label too). +fn label<'h>(h: &'h Harness, text: &'h str) -> Option> { + h.query_by_role_and_label(egui::accesskit::Role::Label, text) +} + +fn set(h: &mut Harness, key: &str, value: Value) { + h.state_mut().ui.dialog.as_mut().expect("the dialog is open").fields.insert(key.into(), value); + h.run_steps(2); +} + +fn remove(h: &mut Harness, id: &str) { + h.state_mut().run("plugin.remove", json!({"id": id})).unwrap(); +} + +#[test] +fn labels_units_sections_text_and_lists_come_from_the_manifest() { + let id = "test.ui.fields.shown"; + let mut h = harness(id, Arc::default()); + for text in ["Outline:", "Title:", "Pattern:", "Spacing:", "Angles:", "Width:", "°"] { + assert!(label(&h, text).is_some(), "{text} isn't shown"); + } + for section in ["Fill", "Outline"] { + assert!(h.query_by_label(section).is_some(), "the {section} section isn't shown"); + } + for value in ["Poster", "0.25 mm", "45, 135", "0.5 pt"] { + // A text field and the text inside it both carry the value. + assert!(h.query_all_by_value(value).next().is_some(), "the value {value} isn't shown"); + } + // The parameters outside groups come first, then each group's section. + let top = |text: &str| label(&h, text).map(|n| n.rect().top()).unwrap_or_default(); + let (fill, outline) = (h.get_by_label("Fill").rect().top(), h.get_by_label("Outline").rect().top()); + assert!(top("Title:") < fill && fill < top("Spacing:") && top("Angles:") < outline && outline < top("Width:")); + // The fields line up down the dialog, in sections and out of them. + let left = |value: &str| h.query_all_by_value(value).next().map(|n| n.rect().left()).unwrap_or_default(); + let (title, spacing, width) = (left("Poster"), left("0.25 mm"), left("0.5 pt")); + assert!((title - spacing).abs() < 0.5 && (spacing - width).abs() < 0.5, "fields at {title}, {spacing} and {width}"); + remove(&mut h, id); +} + +#[test] +fn visible_when_shows_a_parameter_only_while_its_condition_holds() { + let id = "test.ui.fields.visible"; + let mut h = harness(id, Arc::default()); + set(&mut h, "pattern", json!("dots")); + assert!(label(&h, "Spacing:").is_none() && label(&h, "Angles:").is_none(), "dots have no line spacing"); + set(&mut h, "outline", json!(false)); + assert!(label(&h, "Width:").is_none() && h.query_by_label("Outline").is_none(), "without an outline, nor its section"); + set(&mut h, "pattern", json!("crosshatch")); + assert!(label(&h, "Spacing:").is_some()); + // A hidden parameter still goes to the plug-in: the preview runs with every value. + let fields = &h.state().ui.dialog.as_ref().unwrap().fields; + assert_eq!(fields.get("width"), Some(&json!(0.5))); + remove(&mut h, id); +} + +#[test] +fn the_help_button_opens_the_parameter_s_page() { + let id = "test.ui.fields.help"; + let opened: Arc>> = Arc::default(); + let mut h = harness(id, opened.clone()); + let buttons = h.query_all_by_label("Open this setting's help page").count(); + assert_eq!(buttons, 1, "only Spacing has a page"); + h.get_by_label("Open this setting's help page").click(); + h.run_steps(2); + assert_eq!(*opened.lock().unwrap(), ["https://example.org/params/spacing"]); + remove(&mut h, id); +} + +/// `CRAFT_UI_PLUGIN_FIELDS_SHOT=` saves a picture of a dialog whose parameters use every +/// presentation key there, and the test plug-in beside it (`hatch-test-filter.wasm`) to install in +/// the app. Its parameter names are written as many plug-ins write them, in snake case, and it uses +/// only the types every host reads, so a host from before the keys installs it too and shows it as +/// it did. +#[test] +fn plugin_fields_picture() { + let Some(dir) = std::env::var_os("CRAFT_UI_PLUGIN_FIELDS_SHOT") else { return }; + let dir = std::path::PathBuf::from(dir); + let manifest = r#"{"id":"org.example.hatch","name":"Hatch Fill (test plug-in)","version":"1","kind":"filter", + "description":"Fills the selected shapes with lines.","params":{ + "pattern":{"type":"choice","options":["lines","crosshatch","dots"],"default":"lines", + "label":"Pattern","help":"How the shapes are filled."}, + "line_angle":{"type":"number","min":0,"max":360,"default":45,"label":"Angle","unit":"°","group":"Lines", + "help":"The direction of the lines.","visibleWhen":{"pattern":["lines","crosshatch"]}}, + "line_spacing_mm":{"type":"number","min":0.1,"max":10,"default":1.5,"label":"Spacing","unit":"mm","group":"Lines", + "help":"Distance between the lines. Smaller is denser.","helpUrl":"https://example.org/params/line_spacing_mm", + "visibleWhen":{"pattern":["lines","crosshatch"]}}, + "pen_width_mm":{"type":"number","min":0.1,"max":5,"default":0.3,"label":"Pen width","unit":"mm","group":"Lines"}, + "outline":{"type":"bool","default":true,"label":"Outline","group":"Outline"}, + "outline_inset_mm":{"type":"number","min":-10,"max":10,"default":0,"label":"Inset","unit":"mm","group":"Outline", + "visibleWhen":{"outline":[true]}}, + "outline_passes":{"type":"int","min":1,"max":4,"default":1,"label":"Passes","group":"Outline", + "visibleWhen":{"outline":[true]}}}}"#; + let src = tpl::module(manifest, tpl::ECHO, "", 1); + std::fs::write(dir.join("hatch-test-filter.wasm"), wat::parse_str(&src).unwrap()).unwrap(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wat::parse_str(&src).unwrap())})).unwrap(); + app.run("plugin.dialog", json!({"id": "org.example.hatch"})).unwrap(); + let mut ready = false; + let mut h = egui_kittest::Harness::builder().with_size(vec2(720.0, 620.0)).wgpu().build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut ready, true) { + crate::theme::install_fonts(ui.ctx()); + crate::theme::apply(ui.ctx(), crate::theme::Brightness::MediumDark); + return; + } + show(app, ui.ctx()); + }, + app, + ); + h.run_steps(6); + h.render().unwrap().save(dir.join("plugin-fields.png")).unwrap(); + h.state_mut().run("plugin.remove", json!({"id": "org.example.hatch"})).unwrap(); +} diff --git a/crates/ui-egui/src/dialogs/tests_rectangular_grid.rs b/crates/ui-egui/src/dialogs/tests_rectangular_grid.rs index 8d9f8c56bf..8c6f6331e1 100644 --- a/crates/ui-egui/src/dialogs/tests_rectangular_grid.rs +++ b/crates/ui-egui/src/dialogs/tests_rectangular_grid.rs @@ -159,6 +159,31 @@ fn key_frame(app: &mut VectorcraftApp, key: egui::Key) { out.textures_delta.clear(); } +#[test] +fn rectangular_grid_reference_locator_reanchors_to_the_click() { + let mut app = app(); + click(&mut app, Point::new(100.0, 100.0)); + set(&mut app, "reference", json!(4)); + super::shapes::grid_pin_to_anchor(app.ui.dialog.as_mut().unwrap()); + assert_eq!((field(&app, "x"), field(&app, "y")), (json!(50.0), json!(50.0))); + let id = confirm(&mut app); + assert_grid(&app, id, Rect::new(50.0, 50.0, 150.0, 150.0), 5, 5); +} + +/// #1377: OK uses the bounding box after a reference-point resize (`artboard_rect` keeps the +/// center pinned when width doubles). +#[test] +fn rectangular_grid_reference_point_pins_center_when_width_changes() { + let mut app = app(); + click(&mut app, Point::new(100.0, 100.0)); + assert_eq!(field(&app, "reference"), json!(0)); + for (key, value) in [("reference", json!(4)), ("x", json!(50.0)), ("y", json!(50.0)), ("width", json!(200)), ("height", json!(100))] { + set(&mut app, key, value); + } + let id = confirm(&mut app); + assert_grid(&app, id, Rect::new(50.0, 50.0, 250.0, 150.0), 5, 5); +} + #[test] fn rectangular_grid_canvas_click_opens_registered_dialog_with_saved_counts_and_point_defaults() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/tests_screen_assets.rs b/crates/ui-egui/src/dialogs/tests_screen_assets.rs index 60d47b39af..18111e5526 100644 --- a/crates/ui-egui/src/dialogs/tests_screen_assets.rs +++ b/crates/ui-egui/src/dialogs/tests_screen_assets.rs @@ -52,7 +52,7 @@ fn assets(app: &mut VectorcraftApp) -> Vec { fn export_selection_collects_the_selection_and_opens_the_assets_tab() { let (mut app, log, _) = app(true); assert!(crate::menus::enabled(&app, "file.exportSelection")); - let r = app.run("file.exportSelection", json!({})).unwrap(); + let r = app.run("file.exportSelection", json!({"multiple": true})).unwrap(); let list = assets(&mut app); assert_eq!(list.len(), 2, "one asset per object"); let ids: Vec = list.iter().map(|a| a["id"].clone()).collect(); @@ -61,7 +61,7 @@ fn export_selection_collects_the_selection_and_opens_the_assets_tab() { assert_eq!((field(&app, "tab"), field(&app, "assets")), (json!("assets"), json!(ids))); // Collecting the same art again opens on the same assets. super::cancel(&mut app); - app.run("file.exportSelection", json!({})).unwrap(); + app.run("file.exportSelection", json!({"multiple": true})).unwrap(); assert_eq!(assets(&mut app).len(), 2); assert_eq!(field(&app, "assets"), json!(ids)); let text = painted_text(&mut app, |app, ui| super::show(app, ui.ctx())); @@ -80,12 +80,15 @@ fn export_selection_collects_the_selection_and_opens_the_assets_tab() { #[test] fn export_selection_as_one_asset() { - let (mut app, _, ids) = app(true); - app.run("file.exportSelection", json!({"multiple": false})).unwrap(); - let list = assets(&mut app); - assert_eq!(list.len(), 1); - assert_eq!(list[0]["nodes"], json!(ids)); - assert_eq!(field(&app, "assets"), json!([list[0]["id"]])); + // By default the selection, ungrouped, becomes one asset of it all; `multiple: false` says so too. + for p in [json!({}), json!({"multiple": false})] { + let (mut app, _, ids) = app(true); + app.run("file.exportSelection", p.clone()).unwrap(); + let list = assets(&mut app); + assert_eq!(list.len(), 1, "{p}"); + assert_eq!(list[0]["nodes"], json!(ids), "{p}"); + assert_eq!(field(&app, "assets"), json!([list[0]["id"]]), "{p}"); + } } #[test] @@ -142,3 +145,38 @@ fn the_menus_reach_asset_export() { app.run("assets.add", json!({"multiple": false})).unwrap(); assert_eq!(assets(&mut app).len(), 1); } + +/// The Assets tab opened on new assets scrolls its list to the first checked one, once: they land +/// at the end of a long list. +#[test] +fn the_assets_tab_scrolls_to_the_new_asset() { + let (mut app, _, ids) = app(true); + for i in 0..30 { + let id = app.run("shape.rectangle", json!({"x": 5 * i, "y": 50, "width": 4, "height": 4})).unwrap()["id"].clone(); + app.run("assets.add", json!({"ids": [id]})).unwrap(); + } + app.run("select.set", json!({"ids": ids})).unwrap(); + let r = app.run("file.exportSelection", json!({"multiple": false})).unwrap(); + let new = r["assets"][0].clone(); + assert_eq!(assets(&mut app).len(), 31); + assert_eq!(assets(&mut app).last().unwrap()["id"], new); + assert_eq!(field(&app, "__scrollTo"), new); + let name = assets(&mut app).last().unwrap()["name"].as_str().unwrap().to_string(); + // The rows below the list's visible part are painted but clipped away: the new one is inside + // its clip once the frame after the opening one has scrolled. + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut shown = false; + // Scrolling is animated: a second of frames lets it land. + for i in 0..60 { + let input = egui::RawInput { time: Some(f64::from(i) / 60.0), ..egui::RawInput::default() }; + let mut out = ctx.run_ui(input, |ui| super::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + shown = out.shapes.iter().any(|c| match &c.shape { + egui::Shape::Text(t) => t.galley.text() == name && c.clip_rect.contains_rect(t.visual_bounding_rect()), + _ => false, + }); + } + assert!(shown, "{name} is clipped out of the list"); + assert_eq!(field(&app, "__scrollTo"), Value::Null, "scrolled once"); +} diff --git a/crates/ui-egui/src/dialogs/tests_warp.rs b/crates/ui-egui/src/dialogs/tests_warp.rs index de2b53aa9e..184ca1c0b7 100644 --- a/crates/ui-egui/src/dialogs/tests_warp.rs +++ b/crates/ui-egui/src/dialogs/tests_warp.rs @@ -187,6 +187,25 @@ fn warp_options_existing_style_edit_keeps_stack_target_visibility_and_history() } } +/// A new Warp Options dialog opens on the sliders confirmed last time (#1760 follow-up). +#[test] +fn warp_dialog_remembers_last_confirmed_sliders() { + let (mut app, _) = app(); + app.run("effect.dialog", json!({"effect": "warp.arc", "item": null})).unwrap(); + let ctx = context(); + settle(&mut app, &ctx); + set(&mut app, json!({"bend": -40.0, "horizontal": 12.0, "vertical": -8.0, "orientation": "vertical"})); + confirm(&mut app).unwrap(); + app.run("effect.dialog", json!({"effect": "warp.flag", "item": null})).unwrap(); + settle(&mut app, &ctx); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.str("__effect"), "warp.flag"); + assert_eq!(d.f64("bend", 0.0), -40.0); + assert_eq!(d.f64("horizontal", 0.0), 12.0); + assert_eq!(d.f64("vertical", 0.0), -8.0); + assert_eq!(d.str("orientation"), "vertical"); +} + #[test] fn warp_options_preview_toggle_and_ok_use_latest_values() { let (mut app, id) = app(); diff --git a/crates/ui-egui/src/dialogs/tools.rs b/crates/ui-egui/src/dialogs/tools.rs index 034295ff3d..0b1cd94d01 100644 --- a/crates/ui-egui/src/dialogs/tools.rs +++ b/crates/ui-egui/src/dialogs/tools.rs @@ -3,6 +3,7 @@ use serde_json::{Value, json}; +use super::shapes::grid_pin_to_anchor; use crate::VectorcraftApp; use crate::state::Dialog; @@ -18,11 +19,17 @@ pub fn open_tool_dialog(app: &mut VectorcraftApp, kind: &str, p: Value) { "lineSegment" => Dialog::new(kind, json!({"x": x, "y": y, "length": "100 pt", "angle": 0})), // The grids: the tool's stored options (divider counts and skews, switches) at the default size. "rectangularGrid" | "polarGrid" => { - let mut fields = app.session.tool_options_of(kind); - for (key, value) in [("x", json!(x)), ("y", json!(y)), ("width", json!("100 pt")), ("height", json!("100 pt"))] { - fields[key] = value; + let mut obj = match app.session.tool_options_of(kind) { + Value::Object(o) => o, + _ => serde_json::Map::new(), + }; + for (key, value) in [("__anchorX", json!(x)), ("__anchorY", json!(y)), ("width", json!("100 pt")), ("height", json!("100 pt"))] { + obj.insert(key.into(), value); } - Dialog::new(kind, fields) + obj.insert("reference".into(), json!(0)); + let mut d = Dialog::new(kind, Value::Object(obj)); + grid_pin_to_anchor(&mut d); + d } // Graph tool click: the graph's size. "graph" => Dialog::new( diff --git a/crates/ui-egui/src/dialogs/warp_effect.rs b/crates/ui-egui/src/dialogs/warp_effect.rs index 1b06fbbef9..e0a2490aaf 100644 --- a/crates/ui-egui/src/dialogs/warp_effect.rs +++ b/crates/ui-egui/src/dialogs/warp_effect.rs @@ -1,6 +1,6 @@ //! Effect > Warp controls. The style remains an effect ID; Envelope Warp has a different schema. use egui::{Pos2, Rect, Stroke, vec2}; -use serde_json::json; +use serde_json::{Map, Value, json}; use vectorcraft_effects::{WARP_STYLES, WarpStyle, warp_point}; use super::form; @@ -8,10 +8,28 @@ use crate::state::Dialog; use crate::theme::Tokens; use crate::widgets; +const REMEMBERED: [&str; 4] = ["bend", "horizontal", "vertical", "orientation"]; + pub(super) fn is_warp(id: &str) -> bool { id.strip_prefix("warp.").and_then(WarpStyle::from_id).is_some() } +/// Slider and orientation values to seed the next new Warp Options dialog. +pub(super) fn remembered_params(d: &Dialog) -> Value { + let kept = REMEMBERED.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))); + Value::Object(kept.collect()) +} + +/// Last confirmed warp settings over the catalog defaults for a new dialog. +pub(super) fn merge_remembered(fields: &mut Map, remembered: Option<&Value>) { + let Some(obj) = remembered.and_then(Value::as_object) else { return }; + for key in REMEMBERED { + if let Some(v) = obj.get(key) { + fields.insert(key.into(), v.clone()); + } + } +} + fn shown(label: &str) -> String { tl!(label).trim_end_matches('…').to_string() } diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index e881559d18..8e0c63dcfd 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -467,7 +467,11 @@ pub(crate) fn panel_body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, width: ui.set_max_height(tall); panels::layers::show(app, ui); } - Some(DockTab::Libraries) => panels::libraries(app, ui), + Some(DockTab::Libraries) => { + // Its list scrolls inside `tall` (as in the dock) instead of growing the flyout. + ui.set_max_height(tall); + panels::libraries(app, ui); + } None => panels::show_icon_panel(app, ui, id), } }); diff --git a/crates/ui-egui/src/edit_toolbar.rs b/crates/ui-egui/src/edit_toolbar.rs index c2d1c4bf75..98e316f066 100644 --- a/crates/ui-egui/src/edit_toolbar.rs +++ b/crates/ui-egui/src/edit_toolbar.rs @@ -354,6 +354,7 @@ fn heading(id: &str) -> &'static str { _ if id.starts_with("perspective") => "Perspective", "artboard" => "Artboards", "slice" | "sliceSelection" => "Slices", + "objectsOnPath" => "Modify", _ => "More", } } @@ -742,6 +743,8 @@ mod tests { assert_eq!(under("pencil"), Some("Draw")); assert_eq!(under("shaper"), Some("Draw"), "framed with the Pencil"); assert_eq!(under("rectangle"), Some("Shapes")); + assert_eq!(under("objectsOnPath"), Some("Modify"), "framed with the Blend tool"); + assert_eq!(heading("objectsOnPath"), "Modify", "though not in the Basic toolbar"); } /// The Show section's controls (#1736): each shows (true), hides (false) or toggles, saved with diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index bd723456ea..3629760a7a 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -89,7 +89,8 @@ const SCRIPTS: usize = 4; fn script_label(i: usize) -> &'static str { match i { - 1 => tl!("Japanese"), + // CJK families use the `japanese` font trait; Chinese UI calls this 汉字 (#2206). + 1 => crate::i18n::tr_ctx(crate::i18n::current(), "font-script", "Japanese"), 2 => tl!("Latin"), 3 => tl!("Thai"), _ => tl!("All Scripts"), @@ -776,6 +777,11 @@ mod tests { assert_eq!(passing(japanese), [0, 1]); assert_eq!(passing(latin), [0, 2]); assert_eq!(super::script_label(3), "Thai"); + let zh = crate::i18n::Lang::from_code("zh-hans").unwrap(); + crate::i18n::set_current(zh); + assert_eq!(super::script_label(1), "汉字"); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(super::script_label(1), "Japanese"); } /// #2277: the list's scroll bar has a column of its own, so the stars at the rows' right ends diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 5c86db4924..1f8e7ec876 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1058,6 +1058,7 @@ Fill (X), double-click for the Color Picker Запълване (X), щракнете двукратно за избор на цвят Fill and Stroke Запълване и щрих Fill new strokes Запълване на нови щрихове + Alt key toggles to Smooth Tool Клавишът Alt превключва към инструмент „Гладкост“ Fill Color Цвят на запълване Fill New Type Objects With Placeholder Text Запълване на нови текстови обекти с примесен текст Fill Rule Правило за запълване @@ -1174,6 +1175,8 @@ Large Gaps Големи пролуки Gap Preview Color: Цвят за преглед на пролуките: Close Gaps With Paths Затваряне на пролуките с пътища + Select Fills Избиране на запълвания + Select Strokes Избиране на щрихове Gaussian Blur… Гаусово размазване… General Общи General › Placement › X Общи › Разположение › X @@ -1370,6 +1373,12 @@ Release Blend Освобождаване на преливане Release Envelope Освобождаване на обвивка Release Intertwine Освобождаване на преплитане + Objects on Path Обекти по пътя + Attach Прикрепяне + Objects on Path Options Опции за обекти по пътя + Objects on Path Tool Инструмент „Обекти по пътя“ + Attach Objects on Path Прикрепяне на обекти към пътя + Expand Objects on Path Разширяване на обекти по пътя Release Live Paint Освобождаване на динамично оцветяване Release Repeat Освобождаване на повторение Release Slice Освобождаване на отрязък @@ -1485,6 +1494,7 @@ Inspect Object Инспектиране на обекта Install Plug-in Инсталиране на приставка Install Plug-in… Инсталиране на приставка… + Open this setting's help page Отваряне на страницата с помощ за тази настройка Installed plug-in {} Инсталирана приставка {} Intensity: Интензивност: Intent: Цел: @@ -1672,6 +1682,7 @@ Load Text into Clipboard Зареждане на текст в клипборда Local Libraries Локални библиотеки Locate Object Намиране на обект + Locate Selected Objects Намиране на избраните обекти Location Местоположение Location: Местоположение: Lock Заключване @@ -2102,6 +2113,7 @@ Output White Изходно бяло Output › Mode Изход › Режим Output: Изход: + Overlap Застъпване Overlap: Застъпване: Overlapping Застъпващи се Overlay Прекриване @@ -2858,6 +2870,8 @@ Show Note Показване на бележка Show Options Показване на опциите Show Original Path Показване на оригиналния път + Open this dialog with these settings next time Отваряне на този прозорец с тези настройки следващия път + Auto-Simplify Автоматично опростяване Show Package Показване на пакет Show Panel Показване на панел Show Pattern Swatches Показване на образци за мостра @@ -2952,6 +2966,7 @@ Snap to Pixel Прилепване към пиксел Precise Cursors Прецизни курсори Snap to Point Прилепване към точка + Snap to Unit Прилепване към мерна единица Snapping Tolerance Толеранс на прилепване Social Square Post 1080×1080 Публикация за квадрат в социални мрежи 1080×1080 Soft Light Мека светлина @@ -3079,7 +3094,7 @@ Delete Library Item Изтриване на елемент от библиотека No results Няма резултати No items in this library match “{query}”. Няма елементи в тази библиотека, съвпадащи с „{query}“. - Right-click an item to move it into this group. Щракнете с десния бутон върху елемент, за да го преместите в тази група. + Drag an item here, or right-click one, to put it in this group. Плъзнете елемент тук или щракнете с десния бутон върху него, за да го поставите в тази група. New Group Нова група New Group… Нова група… Move to Group Преместване в група @@ -3139,6 +3154,7 @@ Text Wrap Options Опции за обтичане на текст Text Wrap Options… Опции за обтичане на текст… The bounds of the visible art. Границите на видимия макет. + The plug-in writes the whole document. Приставката експортира целия документ. The cell shows the type object's text as HTML. Клетката показва текста на текстовия обект като HTML. The document has no colour swatches. Документът няма цветови образци. The edge of the paper the printer can't reach: the art goes inside it, and the preview shows it dashed. Краят на хартията, до който принтерът не може да стигне: макетът навлиза в него, а прегледът го показва с пунктир. @@ -5151,6 +5167,27 @@ theme Appearance Външен вид Movie Clip Филмов клип @msg name is empty името е празно @msg no symbol named `{n}` няма символ с име `{n}` + Smudge Stick… Размазваща пръчка… + Smudge Stick Размазваща пръчка + Sponge… Гъба… + Sponge Гъба + Watercolor… Акварел… + Watercolor Акварел + Brush Size Размер на четката + Definition Дефиниция + Brush Detail Детайл на четката + Shadow Intensity Интензивност на сенките + Bas Relief… Барелеф… + Bas Relief Барелеф + Charcoal… Въглен… + Charcoal Въглен + Photocopy… Фотокопие… + Photocopy Фотокопие + Stamp… Печат… + Stamp Печат + Thickness Дебелина + Detail Детайл + Light/Dark Balance Баланс светло/тъмно # Links and Attributes: files and URLs handed to other apps. @msg Edit Original opens image and document files only; “{name}” is not one „Редактиране на оригинал“ отваря само файлове с изображения и документи; „{name}“ не е такъв файл @msg only http, https and mailto URLs open in the browser, not “{url}” в браузъра се отварят само URL адреси с http, https и mailto, не „{url}“ @@ -5178,3 +5215,21 @@ theme Appearance Външен вид @msg the file's variables and data sets weren't read (variables: {variables}, data sets: {data_sets}): the Variables panel doesn't list them променливите и наборите от данни на файла не бяха прочетени (променливи: {variables}, набори от данни: {data_sets}): панелът „Променливи“ не ги показва # Select by Color (select.color) Select by Color Избиране по цвят + Move Anchor Point Преместване на опорна точка +@msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} запазва 1 от {n} работни области на документа: файлът се отваря отново с един. Включете „Запазване на възможностите за редактиране“, за да запазите всички. + Chalk & Charcoal… Креда и въглен… + Chalk & Charcoal Креда и въглен + Graphic Pen… Графична писалка… + Graphic Pen Графична писалка + Reticulation… Ретикулация… + Reticulation Ретикулация + Plastic Wrap… Найлоново фолио… + Plastic Wrap Найлоново фолио + Chrome… Хром… + Chrome Хром + Drop here to take it out of its group Пуснете тук, за да го извадите от групата му + Move Library Group Преместване на библиотечна група + Plaster… Гипс… + Plaster Гипс + Note Paper… Хартия за писма… + Note Paper Хартия за писма diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index f2a494991c..a3a1db5d02 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -264,6 +264,8 @@ Large Gaps Velké mezery Gap Preview Color: Barva náhledu mezer: Close Gaps With Paths Uzavřít mezery cestami + Select Fills Vybírat výplně + Select Strokes Vybírat tahy Image Trace Vektorizace obrazu Image Trace (Make and Expand) Vektorizace obrazu (vytvořit a rozložit) Release Image Trace Uvolnit vektorizaci obrazu @@ -303,6 +305,7 @@ Plug-ins Zásuvné moduly No filter plug-ins installed Nejsou nainstalovány žádné filtry Install Plug-in… Nainstalovat zásuvný modul… + Open this setting's help page Otevřít stránku nápovědy k tomuto nastavení Reload Plug-ins Znovu načíst zásuvné moduly Type Text Font Písmo @@ -1565,6 +1568,12 @@ lighting Light Světlo Release Blend Uvolnit prolnutí Release Envelope Uvolnit obálku Release Intertwine Uvolnit propletení + Objects on Path Objekty na cestě + Attach Připojit + Objects on Path Options Možnosti objektů na cestě + Objects on Path Tool Nástroj Objekty na cestě + Attach Objects on Path Připojit objekty na cestu + Expand Objects on Path Rozložit objekty na cestě Release Live Paint Uvolnit živou malbu Release Repeat Uvolnit opakování Release Slice Uvolnit řez @@ -1649,7 +1658,7 @@ lighting Light Světlo This library is empty Tato knihovna je prázdná No results Žádné výsledky No items in this library match “{query}”. Žádná položka v této knihovně neodpovídá „{query}“. - Right-click an item to move it into this group. Kliknutím pravým tlačítkem na položku ji přesunete do této skupiny. + Drag an item here, or right-click one, to put it in this group. Přetáhněte sem položku nebo na ni klikněte pravým tlačítkem a vložte ji do této skupiny. New Group Nová skupina New Group… Nová skupina… Move to Group Přesunout do skupiny @@ -1704,6 +1713,8 @@ lighting Light Světlo Corner Point Angle Threshold: Prahový úhel rohových bodů: Convert to Straight Lines Převést na přímé čáry Show Original Path Zobrazit původní cestu + Open this dialog with these settings next time Příště otevřít toto dialogové okno s tímto nastavením + Auto-Simplify Automaticky zjednodušit Transparency Options Možnosti průhlednosti Color Mixer (Shift-click the chip) Míchání barev (Shift+kliknutí na políčko) Fill: click for swatches, Shift-click for the color mixer Výplň: kliknutím otevřete vzorník, Shift+kliknutím míchání barev @@ -1778,6 +1789,7 @@ lighting Light Světlo Left in Front Levý vpředu No document Žádný dokument Open a document to edit its patterns. Otevřete dokument, abyste mohli upravit jeho vzorky. + Overlap Překrytí Overlap: Překrytí: Pattern options are available in pattern editing mode. Možnosti vzorku jsou dostupné v režimu úprav vzorku. Right in Front Pravý vpředu @@ -1905,6 +1917,7 @@ lighting Light Světlo Right-Justified Tab Tabulátor zarovnaný doprava Select a text object to set its tab stops. Vyberte textový objekt, abyste mohli nastavit jeho zarážky tabulátoru. Select text Vyberte text + Snap to Unit Přichytávat k jednotkám + Add Scale + Přidat měřítko Add Selected Artwork as One Asset Přidat vybranou kresbu jako jeden prvek Export Settings Nastavení exportu @@ -2156,6 +2169,7 @@ lighting Light Světlo One file per artboard: -.{ext} Jeden soubor na pracovní plochu: -.{ext} One page per artboard. Jedna stránka na pracovní plochu. The bounds of the visible art. Hranice viditelné kresby. + The plug-in writes the whole document. Zásuvný modul exportuje celý dokument. Use Artboards Použít pracovní plochy Choose a folder Vyberte složku Create Sub-folders Vytvořit podsložky @@ -2241,6 +2255,7 @@ lighting Light Světlo Edit selected paths within: Upravovat vybrané cesty do: Fidelity: Věrnost: Fill new strokes Vyplňovat nové tahy + Alt key toggles to Smooth Tool Klávesa Alt přepíná na nástroj Vyhlazení Keep selected Ponechat vybrané Merge only with selection Sloučit jen s výběrem The document has no colour swatches. Dokument nemá ve vzorníku žádné barvy. @@ -2260,6 +2275,7 @@ lighting Light Světlo Layers Panel Options Možnosti panelu Vrstvy Row Size: Velikost řádků: Show Layers Only Zobrazit pouze vrstvy + Locate Selected Objects Najít vybrané objekty Thumbnails: Miniatury: Anchor Points Kotevní body Brush Affects: Štětec ovlivňuje: @@ -4162,6 +4178,7 @@ imageTrace Outline Obrys @msg background {other}: transparent, white, black or a colour such as "#ff8800" pozadí {other}: transparent, white, black nebo barva jako "#ff8800" @msg bad color {v} chybná barva {v} @msg the Color Picker is not open Výběr barvy není otevřený +@msg the Simplify slider is not open Posuvník Zjednodušit není otevřený @msg the screen color sampler is already open nástroj pro nabírání barvy z obrazovky už je otevřený @msg this system has no screen color sampler tento systém nemá nástroj pro nabírání barvy z obrazovky @msg bad colour `{hex}` (#rrggbb) chybná barva `{hex}` (#rrggbb) @@ -4398,6 +4415,7 @@ imageTrace Outline Obrys @msg select a linked image: an embedded one has no file vyberte propojený obrázek: vložený nemá soubor @msg select a repeat vyberte opakování @msg select an Intertwine group vyberte skupinu propletení +@msg select an Objects on Path group vyberte skupinu objektů na cestě @msg select a stroke with a variable width vyberte tah s proměnnou šířkou @msg select a symbol instance vyberte instanci symbolu @msg select an Image Trace object vyberte objekt vektorizace obrazu @@ -4527,6 +4545,7 @@ imageTrace Outline Obrys @msg {_1} files are written by file.saveAsTemplate soubory {_1} zapisuje file.saveAsTemplate @msg {_1} font families available Dostupné rodiny písem: {_1} @msg {_1} is a live effect (Effect › Plug-ins) {_1} je živý efekt (Efekt › Zásuvné moduly) +@msg {_1} is an exporter (File › Export › Export As…) {_1} je exportní zásuvný modul (Soubor › Export › Exportovat jako…) @msg {_1} is already used by {_2} {_1} už používá {_2} @msg {_1} linked file(s) can't be read here: their previews show propojené soubory ({_1}) zde nelze přečíst: zobrazují se jejich náhledy @msg {_1} linked image(s) changed on disk: Update Links shows the new versions propojené obrázky ({_1}) se na disku změnily: nové verze zobrazí Aktualizovat propojení @@ -5157,6 +5176,7 @@ mark-style Japanese Japonské @msg choose a destination folder vyberte cílovou složku @msg choose a source folder vyberte zdrojovou složku @msg open a document with data sets otevřete dokument se sadami dat +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for ze sady dat {name} se nic nepoužilo: žádný objekt není svázán s proměnnou, pro kterou má hodnotu @msg the action has no steps akce nemá žádné kroky # User Interface › Accent Color @@ -5178,6 +5198,27 @@ mark-style Japanese Japonské Movie Clip Filmový klip @msg name is empty název je prázdný @msg no symbol named `{n}` žádný symbol s názvem `{n}` + Smudge Stick… Rozmazávací tyčinka… + Smudge Stick Rozmazávací tyčinka + Sponge… Houba… + Sponge Houba + Watercolor… Akvarel… + Watercolor Akvarel + Brush Size Velikost štětce + Definition Definice + Brush Detail Detail štětce + Shadow Intensity Intenzita stínů + Bas Relief… Basreliéf… + Bas Relief Basreliéf + Charcoal… Uhel… + Charcoal Uhel + Photocopy… Fotokopie… + Photocopy Fotokopie + Stamp… Razítko… + Stamp Razítko + Thickness Tloušťka + Detail Detail + Light/Dark Balance Vyvážení světlé/tmavé # Links and Attributes: files and URLs handed to other apps. @msg Edit Original opens image and document files only; “{name}” is not one Upravit originál otevírá pouze soubory obrázků a dokumentů; „{name}“ mezi ně nepatří @msg only http, https and mailto URLs open in the browser, not “{url}” v prohlížeči se otevírají pouze adresy URL http, https a mailto, ne „{url}“ @@ -5217,3 +5258,21 @@ mark-style Japanese Japonské @msg the file's variables and data sets weren't read (variables: {variables}, data sets: {data_sets}): the Variables panel doesn't list them proměnné a sady dat souboru nebyly načteny (proměnné: {variables}, sady dat: {data_sets}): panel Proměnné je nezobrazuje # Select by Color (select.color) Select by Color Vybrat podle barvy + Move Anchor Point Přesunout kotevní bod +@msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} zachová 1 z {n} pracovních ploch dokumentu: soubor se znovu otevře s jedním. Zapněte Zachovat možnosti úprav, aby zůstala všechna. + Chalk & Charcoal… Křída a uhel… + Chalk & Charcoal Křída a uhel + Graphic Pen… Grafické pero… + Graphic Pen Grafické pero + Reticulation… Síťování… + Reticulation Síťování + Plastic Wrap… Plastová fólie… + Plastic Wrap Plastová fólie + Chrome… Chrom… + Chrome Chrom + Drop here to take it out of its group Pusťte sem, chcete-li ji vyjmout ze skupiny + Move Library Group Přesunout skupinu knihovny + Plaster… Sádra… + Plaster Sádra + Note Paper… Dopisní papír… + Note Paper Dopisní papír diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index a7757d5d4d..667ad8e51e 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -269,6 +269,7 @@ Plug-ins Plug-ins No filter plug-ins installed Ingen filter-plug-ins installeret Install Plug-in… Installér plug-in… + Open this setting's help page Åbn hjælpesiden for denne indstilling Reload Plug-ins Genindlæs plug-ins Type Tekst Font Skrifttype @@ -1489,7 +1490,7 @@ lighting Light Lys This library is empty Dette bibliotek er tomt No results Ingen resultater No items in this library match “{query}”. Ingen elementer i dette bibliotek matcher »{query}«. - Right-click an item to move it into this group. Højreklik på et element for at flytte det til denne gruppe. + Drag an item here, or right-click one, to put it in this group. Træk et element hertil, eller højreklik på et, for at lægge det i denne gruppe. New Group Ny gruppe New Group… Ny gruppe… Move to Group Flyt til gruppe @@ -1607,6 +1608,7 @@ lighting Light Lys Left in Front Venstre forrest No document Intet dokument Open a document to edit its patterns. Åbn et dokument for at redigere dets mønstre. + Overlap Overlap Overlap: Overlap: Pattern options are available in pattern editing mode. Mønsterindstillinger er tilgængelige i mønsterredigeringstilstand. Right in Front Højre forrest @@ -1734,6 +1736,7 @@ lighting Light Lys Right-Justified Tab Højrejusteret tabulator Select a text object to set its tab stops. Markér et tekstobjekt for at angive dets tabulatorstop. Select text Markér tekst + Snap to Unit Fastgør til enhed + Add Scale + Tilføj skala Add Selected Artwork as One Asset Tilføj markeret grafik som ét aktiv Export Settings Eksportindstillinger @@ -1978,6 +1981,7 @@ lighting Light Lys One file per artboard: -.{ext} Én fil pr. tegnebræt: -.{ext} One page per artboard. Én side pr. tegnebræt. The bounds of the visible art. Den synlige grafiks grænser. + The plug-in writes the whole document. Plug-ins eksporterer hele dokumentet. Use Artboards Brug tegnebrætter Choose a folder Vælg en mappe Create Sub-folders Opret undermapper @@ -2063,6 +2067,7 @@ lighting Light Lys Edit selected paths within: Redigér markerede stier inden for: Fidelity: Præcision: Fill new strokes Udfyld nye konturer + Alt key toggles to Smooth Tool Alt-tasten skifter til Udglatningsværktøj The document has no colour swatches. Dokumentet har ingen farveprøver. Style Name: Typografinavn: Crop To Beskær til @@ -2080,6 +2085,7 @@ lighting Light Lys Layers Panel Options Indstillinger for lagpanelet Row Size: Rækkestørrelse: Show Layers Only Vis kun lag + Locate Selected Objects Lokalisér markerede objekter Thumbnails: Miniaturer: Anchor Points Ankerpunkter Brush Affects: Penslen påvirker: @@ -5049,6 +5055,8 @@ swatch Bright Violet Kraftig violet Outline Object Objekt til kontur Update Selection Opdater markering Show Original Path Vis oprindelig kurve + Open this dialog with these settings next time Åbn denne dialogboks med disse indstillinger næste gang + Auto-Simplify Forenkl automatisk @msg check a layer to export markér et lag, der skal eksporteres @msg select the art to export first markér først grafikken, der skal eksporteres @msg no saved selection recalled ingen gemt markering hentet @@ -5074,6 +5082,8 @@ swatch Bright Violet Kraftig violet Chop Design Beskær design Clear Events Ryd hændelser Close Gaps With Paths Luk huller med stier + Select Fills Markér udfyldninger + Select Strokes Markér konturer Column Type: Søjletype: Each Design Represents: Hvert design repræsenterer: Event: Hændelse: @@ -5151,6 +5161,12 @@ swatch Bright Violet Kraftig violet Release Blend Frigør blanding Release Envelope Frigør konvolut Release Intertwine Frigør sammenfletning + Objects on Path Objekter på kurve + Attach Tilknyt + Objects on Path Options Indstillinger for objekter på kurve + Objects on Path Tool Objekter på kurve-værktøj + Attach Objects on Path Tilknyt objekter til kurve + Expand Objects on Path Udvid objekter på kurve Release Live Paint Frigør live-maling Release Repeat Frigør gentagelse Release Slice Frigør udsnit @@ -5197,3 +5213,41 @@ swatch Bright Violet Kraftig violet Justification Justering # Select by Color (select.color) Select by Color Markér efter farve + Smudge Stick… Udtværingsstift… + Smudge Stick Udtværingsstift + Sponge… Svamp… + Sponge Svamp + Watercolor… Akvarel… + Watercolor Akvarel + Brush Size Penselstørrelse + Definition Definition + Brush Detail Penseldetalje + Shadow Intensity Skyggeintensitet + Bas Relief… Basrelief… + Bas Relief Basrelief + Charcoal… Kul… + Charcoal Kul + Photocopy… Fotokopi… + Photocopy Fotokopi + Stamp… Stempel… + Stamp Stempel + Thickness Tykkelse + Detail Detalje + Light/Dark Balance Lys/mørk-balance + Move Anchor Point Flyt ankerpunkt + Chalk & Charcoal… Kridt og kul… + Chalk & Charcoal Kridt og kul + Graphic Pen… Grafisk pen… + Graphic Pen Grafisk pen + Reticulation… Retikulering… + Reticulation Retikulering + Plastic Wrap… Plastfolie… + Plastic Wrap Plastfolie + Chrome… Krom… + Chrome Krom + Drop here to take it out of its group Slip her for at tage det ud af gruppen + Move Library Group Flyt biblioteksgruppe + Plaster… Gips… + Plaster Gips + Note Paper… Notatpapir… + Note Paper Notatpapir diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 261ff13b25..78706a8bfd 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1062,6 +1062,7 @@ Fill (X), double-click for the Color Picker Fläche (X), Doppelklick öffnet den Farbwähler Fill and Stroke Fläche und Kontur Fill new strokes Neue Striche füllen + Alt key toggles to Smooth Tool Alt-Taste schaltet auf Glätten-Werkzeug um Keep selected Ausgewählt lassen Merge only with selection Nur mit Auswahl zusammenfügen Fill Color Flächenfarbe @@ -1192,6 +1193,8 @@ file-filter Templates Vorlagen Large Gaps Große Lücken Gap Preview Color: Vorschaufarbe für Lücken: Close Gaps With Paths Lücken mit Pfaden schließen + Select Fills Flächen auswählen + Select Strokes Konturen auswählen Gaussian Blur… Gaußscher Weichzeichner… General Allgemein General › Placement › X Allgemein › Platzierung › X @@ -1398,6 +1401,12 @@ file-filter Templates Vorlagen Release Envelope Hülle zurückwandeln Release Image Trace Bildnachzeichner zurückwandeln Release Intertwine Verflechtung zurückwandeln + Objects on Path Objekte auf Pfad + Attach Anhängen + Objects on Path Options Optionen für Objekte auf Pfad + Objects on Path Tool Objekte-auf-Pfad-Werkzeug + Attach Objects on Path Objekte an Pfad anhängen + Expand Objects on Path Objekte auf Pfad umwandeln Release Live Paint „Interaktiv malen“ zurückwandeln Release Repeat Wiederholung zurückwandeln Release Slice Slice zurückwandeln @@ -1517,6 +1526,7 @@ file-filter Templates Vorlagen Inspect Object Objekt untersuchen Install Plug-in Plug-in installieren Install Plug-in… Plug-in installieren… + Open this setting's help page Hilfeseite zu dieser Einstellung öffnen Installed plug-in {} Plug-in {} installiert Intensity: Intensität: Intent: Renderpriorität: @@ -1721,6 +1731,7 @@ file-filter Templates Vorlagen Load Text into Clipboard Text in die Zwischenablage laden Local Libraries Lokale Bibliotheken Locate Object Objekt ausfindig machen + Locate Selected Objects Ausgewählte Objekte ausfindig machen Location Speicherort Location: Ort: Lock Sperren @@ -2120,6 +2131,7 @@ file-filter Templates Vorlagen Output White Ausgabe Weiß Output › Mode Ausgabe › Modus Output: Ausgabe: + Overlap Überlappung Overlap: Überlappung: Overlapping Überlappend Overlay Ineinanderkopieren @@ -2897,6 +2909,8 @@ mark-style Japanese Japanisch Show Note Notiz einblenden Show Options Optionen einblenden Show Original Path Originalpfad einblenden + Open this dialog with these settings next time Dieses Dialogfeld nächstes Mal mit diesen Einstellungen öffnen + Auto-Simplify Automatisch vereinfachen Color Panel Options Optionen für das Farbbedienfeld Show Package Paket anzeigen Show Panel Bedienfeld einblenden @@ -2994,6 +3008,7 @@ effect Points Punkte Snap to Pixel An Pixel ausrichten Precise Cursors Präzise Cursor Snap to Point An Punkt ausrichten + Snap to Unit An Einheit ausrichten Snapping Tolerance Einrasttoleranz Social Square Post 1080×1080 Quadratischer Social-Media-Beitrag 1080×1080 Soft Light Weiches Licht @@ -3164,6 +3179,7 @@ effect Points Punkte Text Wrap Options Textumflussoptionen Text Wrap Options… Textumflussoptionen… The bounds of the visible art. Die Begrenzung der sichtbaren Grafik. + The plug-in writes the whole document. Das Plug-in exportiert das ganze Dokument. The cell shows the type object's text as HTML. Die Zelle zeigt den Text des Textobjekts als HTML. The document has no colour swatches. Das Dokument enthält keine Farbfelder. The edge of the paper the printer can't reach: the art goes inside it, and the preview shows it dashed. Der Papierrand, den der Drucker nicht erreicht: Die Grafik liegt innerhalb davon, und die Vorschau zeigt ihn gestrichelt. @@ -3797,6 +3813,7 @@ theme Appearance Erscheinungsbild @msg background {other}: transparent, white, black or a colour such as "#ff8800" background {other}: transparent, white, black oder eine Farbe wie "#ff8800" @msg bad color {v} ungültige Farbe {v} @msg the Color Picker is not open der Farbwähler ist nicht geöffnet +@msg the Simplify slider is not open der Regler „Vereinfachen“ ist nicht geöffnet @msg the screen color sampler is already open die Farbaufnahme vom Bildschirm ist bereits geöffnet @msg this system has no screen color sampler dieses System hat keine Farbaufnahme vom Bildschirm @msg bad colour `{hex}` (#rrggbb) ungültige Farbe `{hex}` (#rrggbb) @@ -4035,6 +4052,7 @@ theme Appearance Erscheinungsbild @msg select a linked image: an embedded one has no file wählen Sie ein verknüpftes Bild aus: Ein eingebettetes hat keine Datei @msg select a repeat wählen Sie eine Wiederholung aus @msg select an Intertwine group wählen Sie eine Verflechtungsgruppe aus +@msg select an Objects on Path group wählen Sie eine Gruppe „Objekte auf Pfad“ aus @msg select a stroke with a variable width wählen Sie eine Kontur mit variabler Breite aus @msg select a symbol instance wählen Sie eine Symbolinstanz aus @msg select an Image Trace object wählen Sie ein Bildnachzeichner-Objekt aus @@ -4164,6 +4182,7 @@ theme Appearance Erscheinungsbild @msg {_1} files are written by file.saveAsTemplate {_1}-Dateien werden von file.saveAsTemplate geschrieben @msg {_1} font families available {_1} Schriftfamilien verfügbar @msg {_1} is a live effect (Effect › Plug-ins) {_1} ist ein Live-Effekt (Effekt › Plug-ins) +@msg {_1} is an exporter (File › Export › Export As…) {_1} ist ein Export-Plug-in (Datei › Exportieren › Exportieren als…) @msg {_1} is already used by {_2} {_1} wird bereits von {_2} verwendet @msg {_1} linked file(s) can't be read here: their previews show {_1} verknüpfte Datei(en) können hier nicht gelesen werden: Ihre Vorschauen werden angezeigt @msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} verknüpfte(s) Bild(er) wurde(n) auf dem Datenträger geändert: „Verknüpfungen aktualisieren“ zeigt die neuen Versionen @@ -4346,7 +4365,7 @@ theme Appearance Erscheinungsbild Move to Group In Gruppe verschieben No results Keine Ergebnisse No items in this library match “{query}”. Keine Elemente in dieser Bibliothek entsprechen „{query}“. - Right-click an item to move it into this group. Klicken Sie mit der rechten Maustaste auf ein Element, um es in diese Gruppe zu verschieben. + Drag an item here, or right-click one, to put it in this group. Ziehen Sie ein Element hierher oder klicken Sie mit der rechten Maustaste darauf, um es in diese Gruppe zu legen. @msg Imported library {name} Bibliothek {name} importiert # Linked files changed on disk. Update Changed Links Geänderte Verknüpfungen aktualisieren @@ -4735,6 +4754,7 @@ effect Soft Weich @msg choose a destination folder wählen Sie einen Zielordner @msg choose a source folder wählen Sie einen Quellordner @msg open a document with data sets öffnen Sie ein Dokument mit Datensätzen +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for aus dem Datensatz {name} wurde nichts angewendet: kein Objekt ist an eine Variable gebunden, für die er einen Wert hat @msg the action has no steps die Aktion hat keine Schritte # User Interface › Accent Color @@ -4757,6 +4777,28 @@ effect Soft Weich Movie Clip Movieclip @msg name is empty Name ist leer @msg no symbol named `{n}` kein Symbol namens `{n}` + Smudge Stick… Wischstift… + Smudge Stick Wischstift + Sponge… Schwamm… + Sponge Schwamm + Watercolor… Aquarell… + Watercolor Aquarell + Brush Size Pinselgröße + Definition Definition + Brush Detail Pinseldetail + Shadow Intensity Schattenintensität + Bas Relief… Basrelief… + Bas Relief Basrelief + Charcoal… Holzkohle… + Charcoal Holzkohle + Photocopy… Fotokopie… + Photocopy Fotokopie + Stamp… Stempel… + Stamp Stempel + Thickness Stärke + Detail Detail + Light/Dark Balance Hell-Dunkel-Balance + Light Direction Lichtrichtung # Links and Attributes: files and URLs handed to other apps. @msg Edit Original opens image and document files only; “{name}” is not one Original bearbeiten öffnet nur Bild- und Dokumentdateien; „{name}“ gehört nicht dazu @msg only http, https and mailto URLs open in the browser, not “{url}” nur http-, https- und mailto-URLs werden im Browser geöffnet, nicht „{url}“ @@ -4797,3 +4839,21 @@ effect Soft Weich @msg the file's variables and data sets weren't read (variables: {variables}, data sets: {data_sets}): the Variables panel doesn't list them die Variablen und Datensätze der Datei wurden nicht gelesen (Variablen: {variables}, Datensätze: {data_sets}): Das Bedienfeld „Variablen“ listet sie nicht auf # Select by Color (select.color) Select by Color Nach Farbe auswählen + Move Anchor Point Ankerpunkt verschieben +@msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} behält 1 der {n} Zeichenflächen des Dokuments: Die Datei wird mit einer wieder geöffnet. Aktivieren Sie „Bearbeitungsfunktionen beibehalten“, um alle zu behalten. + Chalk & Charcoal… Kreide & Kohle… + Chalk & Charcoal Kreide & Kohle + Graphic Pen… Grafikstift… + Graphic Pen Grafikstift + Reticulation… Retikulation… + Reticulation Retikulation + Plastic Wrap… Kunststofffolie… + Plastic Wrap Kunststofffolie + Chrome… Chrom… + Chrome Chrom + Drop here to take it out of its group Hier ablegen, um es aus seiner Gruppe zu nehmen + Move Library Group Bibliotheksgruppe verschieben + Plaster… Gipsabdruck… + Plaster Gipsabdruck + Note Paper… Prägepapier… + Note Paper Prägepapier diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 6f337b4ad0..d0ed5a87c5 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1024,6 +1024,7 @@ Fill (X), double-click for the Color Picker Γέμισμα (X), διπλό κλικ για τον επιλογέα χρώματος Fill and Stroke Γέμισμα και περίγραμμα Fill new strokes Γέμισμα νέων περιγραμμάτων + Alt key toggles to Smooth Tool Το πλήκτρο Alt αλλάζει στο εργαλείο Εξομάλυνση (Smooth Tool) Fill Color Χρώμα γεμίσματος Fill New Type Objects With Placeholder Text Συμπλήρωση νέων αντικειμένων κειμένου με κείμενο υπόδειξης Fill Rule Κανόνας γεμίσματος @@ -1139,6 +1140,8 @@ Large Gaps Μεγάλα διάκενα Gap Preview Color: Χρώμα προεπισκόπησης διακένων: Close Gaps With Paths Κλείσιμο διακένων με διαδρομές + Select Fills Επιλογή γεμισμάτων + Select Strokes Επιλογή περιγραμμάτων Gaussian Blur… Θόλωση Γκάους… General Γενικά General › Placement › X Γενικά › Τοποθέτηση › X @@ -1333,6 +1336,12 @@ Release Blend Αποδέσμευση ανάμειξης Release Envelope Αποδέσμευση περιβλήματος Release Intertwine Αποδέσμευση διαπλοκής + Objects on Path Αντικείμενα σε διαδρομή + Attach Προσάρτηση + Objects on Path Options Επιλογές αντικειμένων σε διαδρομή + Objects on Path Tool Αντικείμενα σε διαδρομή (Objects on Path Tool) + Attach Objects on Path Προσάρτηση αντικειμένων σε διαδρομή + Expand Objects on Path Επέκταση αντικειμένων σε διαδρομή Release Live Paint Αποδέσμευση δυναμικής βαφής Release Repeat Αποδέσμευση επανάληψης Release Slice Αποδέσμευση τομής @@ -1447,6 +1456,7 @@ Inspect Object Επιθεώρηση αντικειμένου Install Plug-in Εγκατάσταση προσθέτου Install Plug-in… Εγκατάσταση προσθέτου… + Open this setting's help page Άνοιγμα της σελίδας βοήθειας αυτής της ρύθμισης Installed plug-in {} Εγκαταστάθηκε επέκταση {} Intensity: Ένταση: Intent: Σκοπός μετατροπής: @@ -1833,6 +1843,7 @@ Snap to Grid Προσκόλληση στο πλέγμα Snap to Pixel Προσκόλληση σε εικονοστοιχείο Snap to Point Προσκόλληση σε σημείο + Snap to Unit Προσκόλληση σε μονάδα Soft Light Απαλό φως Solid Συνεχές Spacing: Απόσταση: @@ -2457,6 +2468,7 @@ theme Appearance Εμφάνιση Load Text into Clipboard Φόρτωση κειμένου στο πρόχειρο Local Libraries Τοπικές βιβλιοθήκες Locate Object Εντοπισμός αντικειμένου + Locate Selected Objects Εντοπισμός επιλεγμένων αντικειμένων Lock (⌘2) Κλείδωμα (⌘2) Lock Grid Κλείδωμα πλέγματος Lock Others Κλείδωμα υπόλοιπων @@ -2760,6 +2772,7 @@ theme Appearance Εμφάνιση Output intent profile: Προφίλ προορισμού εξόδου: Output White Λευκό εξόδου Output › Mode Έξοδος › Λειτουργία + Overlap Επικάλυψη Overlap: Επικάλυψη: Overlapping Επικαλυπτόμενα Overprint Υπερεκτύπωση @@ -3314,6 +3327,8 @@ theme Appearance Εμφάνιση Show Note Εμφάνιση σημείωσης Show Options Εμφάνιση επιλογών Show Original Path Εμφάνιση αρχικής διαδρομής + Open this dialog with these settings next time Άνοιγμα αυτού του παραθύρου με αυτές τις ρυθμίσεις την επόμενη φορά + Auto-Simplify Αυτόματη απλοποίηση Show Package Εμφάνιση συσκευασίας Show Panel Εμφάνιση πίνακα Show Pattern Swatches Εμφάνιση δειγμάτων μοτίβου @@ -3478,7 +3493,7 @@ theme Appearance Εμφάνιση Delete Library Item Διαγραφή στοιχείου βιβλιοθήκης No results Δεν βρέθηκαν αποτελέσματα No items in this library match “{query}”. Κανένα στοιχείο αυτής της βιβλιοθήκης δεν αντιστοιχεί στο «{query}». - Right-click an item to move it into this group. Κάντε δεξί κλικ σε στοιχείο για να το μετακινήσετε σε αυτήν την ομάδα. + Drag an item here, or right-click one, to put it in this group. Σύρετε εδώ ένα στοιχείο ή κάντε δεξί κλικ σε ένα για να το βάλετε σε αυτήν την ομάδα. Move to Group Μετακίνηση σε ομάδα No Group Χωρίς ομάδα Import Library… Εισαγωγή βιβλιοθήκης… @@ -3527,6 +3542,7 @@ theme Appearance Εμφάνιση Text Wrap Options Επιλογές αναδίπλωσης κειμένου Text Wrap Options… Επιλογές αναδίπλωσης κειμένου… The bounds of the visible art. Τα όρια του ορατού σχεδίου. + The plug-in writes the whole document. Το πρόσθετο εξάγει ολόκληρο το έγγραφο. The cell shows the type object's text as HTML. Το κελί εμφανίζει το κείμενο του αντικειμένου ως HTML. The document has no colour swatches. Το έγγραφο δεν περιέχει δείγματα χρωμάτων. The edge of the paper the printer can't reach: the art goes inside it, and the preview shows it dashed. Το περιθώριο του χαρτιού όπου δεν μπορεί να εκτυπώσει ο εκτυπωτής: το σχέδιο βρίσκεται εντός του και η προεπισκόπηση το δείχνει διακεκομμένο. @@ -4202,6 +4218,7 @@ theme Appearance Εμφάνιση @msg {_1} files are written by file.saveAsTemplate τα αρχεία {_1} αποθηκεύονται με το file.saveAsTemplate @msg {_1} font families available {_1} διαθέσιμες οικογένειες γραμματοσειρών @msg {_1} is a live effect (Effect › Plug-ins) το {_1} είναι δυναμικό εφέ (Εφέ › Πρόσθετα) +@msg {_1} is an exporter (File › Export › Export As…) το {_1} είναι πρόσθετο εξαγωγής (Αρχείο › Εξαγωγή › Εξαγωγή ως…) @msg {_1} is already used by {_2} το {_1} χρησιμοποιείται ήδη από το {_2} @msg {_1} linked file(s) can't be read here: their previews show {_1} συνδεδεμένα αρχεία δεν μπορούν να διαβαστούν εδώ: εμφανίζονται οι προεπισκοπήσεις τους @msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} συνδεδεμένες εικόνες άλλαξαν στον δίσκο: η Ενημέρωση συνδέσμων εμφανίζει τις νέες εκδόσεις @@ -5096,13 +5113,16 @@ effect Points Σημεία @msg choose a destination folder επιλέξτε φάκελο προορισμού @msg choose a source folder επιλέξτε φάκελο προέλευσης @msg open a document with data sets ανοίξτε ένα έγγραφο με σύνολα δεδομένων +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for δεν εφαρμόστηκε τίποτα από το σύνολο δεδομένων {name}: κανένα αντικείμενο δεν είναι συνδεδεμένο με μεταβλητή για την οποία έχει τιμή @msg select an Intertwine group επιλέξτε μια ομάδα διαπλοκής +@msg select an Objects on Path group επιλέξτε μια ομάδα αντικειμένων σε διαδρομή @msg span must be "object" or "selection", got {v} το span πρέπει να είναι "object" ή "selection", δόθηκε {v} @msg span: "selection" places a `gradient`, not a swatch span: το "selection" τοποθετεί ένα `gradient`, όχι δείγμα χρώματος @msg span: "selection" places a gradient: give `gradient` span: το "selection" τοποθετεί ντεγκραντέ: δώστε `gradient` @msg span: "selection" places a linear or radial gradient, not a freeform one span: το "selection" τοποθετεί γραμμικό ή ακτινικό ντεγκραντέ, όχι ελεύθερης μορφής @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: το "selection" τοποθετεί το ίδιο το ντεγκραντέ: παραλείψτε τα `start` και `end` (το τοποθετούν ήδη σε συντεταγμένες εγγράφου) @msg the Color Picker is not open ο επιλογέας χρώματος δεν είναι ανοιχτός +@msg the Simplify slider is not open ο ρυθμιστής Απλοποίησης δεν είναι ανοιχτός @msg the action has no steps η ενέργεια δεν έχει βήματα @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer τα επίπεδα του αρχείου δεν διαβάστηκαν ({_1}): εισάγεται ως η σελίδα του, σε ένα επίπεδο @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part τα επίπεδα του αρχείου δεν διαβάστηκαν από τα δεδομένα επεξεργασίας του ({_1}): προέρχονται από το τμήμα PDF του @@ -5130,6 +5150,27 @@ effect Points Σημεία Movie Clip Κλιπ ταινίας @msg name is empty το όνομα είναι κενό @msg no symbol named `{n}` κανένα σύμβολο με όνομα `{n}` + Smudge Stick… Μουτζούρα… + Smudge Stick Μουτζούρα + Sponge… Σφουγγάρι… + Sponge Σφουγγάρι + Watercolor… Υδατογραφία… + Watercolor Υδατογραφία + Brush Size Μέγεθος πινέλου + Definition Ευκρίνεια + Brush Detail Λεπτομέρεια πινέλου + Shadow Intensity Ένταση σκιών + Bas Relief… Ανάγλυφο… + Bas Relief Ανάγλυφο + Charcoal… Κάρβουνο… + Charcoal Κάρβουνο + Photocopy… Φωτοαντίγραφο… + Photocopy Φωτοαντίγραφο + Stamp… Σφραγίδα… + Stamp Σφραγίδα + Thickness Πάχος + Detail Λεπτομέρεια + Light/Dark Balance Ισορροπία φωτεινού/σκούρου # Links and Attributes: files and URLs handed to other apps. @msg Edit Original opens image and document files only; “{name}” is not one η Επεξεργασία πρωτοτύπου ανοίγει μόνο αρχεία εικόνων και εγγράφων· το «{name}» δεν είναι τέτοιο αρχείο @msg only http, https and mailto URLs open in the browser, not “{url}” στο πρόγραμμα περιήγησης ανοίγουν μόνο URL http, https και mailto, όχι το «{url}» @@ -5169,3 +5210,21 @@ effect Points Σημεία @msg the file's variables and data sets weren't read (variables: {variables}, data sets: {data_sets}): the Variables panel doesn't list them οι μεταβλητές και τα σύνολα δεδομένων του αρχείου δεν διαβάστηκαν (μεταβλητές: {variables}, σύνολα δεδομένων: {data_sets}): ο πίνακας Μεταβλητές δεν τα εμφανίζει # Select by Color (select.color) Select by Color Επιλογή βάσει χρώματος + Move Anchor Point Μετακίνηση σημείου αγκύρωσης +@msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. Το {label} διατηρεί 1 από τους {n} πίνακες σχεδίασης του εγγράφου: το αρχείο ανοίγει ξανά με μία. Ενεργοποιήστε τη Διατήρηση δυνατοτήτων επεξεργασίας για να τους κρατήσετε όλους. + Chalk & Charcoal… Κιμωλία και κάρβουνο… + Chalk & Charcoal Κιμωλία και κάρβουνο + Graphic Pen… Γραφική πένα… + Graphic Pen Γραφική πένα + Reticulation… Δικτύωση… + Reticulation Δικτύωση + Plastic Wrap… Πλαστική μεμβράνη… + Plastic Wrap Πλαστική μεμβράνη + Chrome… Χρώμιο… + Chrome Χρώμιο + Drop here to take it out of its group Αφήστε εδώ για να το βγάλετε από την ομάδα του + Move Library Group Μετακίνηση ομάδας βιβλιοθήκης + Plaster… Γύψος… + Plaster Γύψος + Note Paper… Χαρτί σημειώσεων… + Note Paper Χαρτί σημειώσεων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 5864487c0f..52fe1fbf1f 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1078,6 +1078,7 @@ Fill (X), double-click for the Color Picker Relleno (X), doble clic para el selector de color Fill and Stroke Relleno y trazo Fill new strokes Rellenar trazos nuevos + Alt key toggles to Smooth Tool La tecla Alt cambia a la herramienta Suavizar Keep selected Mantener seleccionado Merge only with selection Combinar solo con la selección Fill Color Color de relleno @@ -1199,6 +1200,8 @@ Large Gaps Huecos grandes Gap Preview Color: Color de previsualización de huecos: Close Gaps With Paths Cerrar huecos con trazados + Select Fills Seleccionar rellenos + Select Strokes Seleccionar trazos Gaussian Blur… Desenfoque gaussiano… General General General › Placement › X General › Colocación › X @@ -1396,6 +1399,12 @@ Release Blend Soltar fusión Release Envelope Soltar envolvente Release Intertwine Soltar entrelazado + Objects on Path Objetos en trazado + Attach Adjuntar + Objects on Path Options Opciones de objetos en trazado + Objects on Path Tool Herramienta Objetos en trazado + Attach Objects on Path Adjuntar objetos al trazado + Expand Objects on Path Expandir objetos en trazado Release Live Paint Soltar pintura interactiva Release Repeat Soltar repetición Release Slice Soltar sector @@ -1511,6 +1520,7 @@ Inspect Object Inspeccionar objeto Install Plug-in Instalar plugin Install Plug-in… Instalar plugin… + Open this setting's help page Abrir la página de ayuda de este ajuste Installed plug-in {} Se instaló el plugin {} Intensity: Intensidad: Intent: Propósito: @@ -1713,6 +1723,7 @@ Load Text into Clipboard Cargar texto en el portapapeles Local Libraries Bibliotecas locales Locate Object Localizar objeto + Locate Selected Objects Localizar objetos seleccionados Location Ubicación Location: Ubicación: Lock Bloquear @@ -2145,6 +2156,7 @@ Output White Blanco de salida Output › Mode Salida › Modo Output: Salida: + Overlap Superposición Overlap: Superposición: Overlapping Superpuesto Overlay Superponer @@ -2915,6 +2927,8 @@ Show Note Mostrar nota Show Options Mostrar opciones Show Original Path Mostrar trazado original + Open this dialog with these settings next time Abrir este cuadro de diálogo con estos ajustes la próxima vez + Auto-Simplify Simplificar automáticamente Color Panel Options Opciones del panel Color Show Package Mostrar paquete Show Panel Mostrar panel @@ -3011,6 +3025,7 @@ Snap to Pixel Ajustar a píxel Precise Cursors Cursores precisos Snap to Point Ajustar a punto + Snap to Unit Ajustar a unidad Snapping Tolerance Tolerancia de ajuste Social Square Post 1080×1080 Publicación cuadrada para redes 1080×1080 Soft Light Luz suave @@ -3138,7 +3153,7 @@ Delete Library Item Eliminar elemento de la biblioteca No results Sin resultados No items in this library match “{query}”. Ningún elemento de esta biblioteca coincide con “{query}”. - Right-click an item to move it into this group. Haz clic con el botón derecho en un elemento para moverlo a este grupo. + Drag an item here, or right-click one, to put it in this group. Arrastra aquí un elemento, o haz clic con el botón derecho en uno, para ponerlo en este grupo. New Group Nuevo grupo New Group… Nuevo grupo… Move to Group Mover al grupo @@ -3198,6 +3213,7 @@ Text Wrap Options Opciones de ceñir texto Text Wrap Options… Opciones de ceñir texto… The bounds of the visible art. Los límites de la ilustración visible. + The plug-in writes the whole document. El plugin exporta el documento completo. The cell shows the type object's text as HTML. La celda muestra el texto del objeto de texto como HTML. The document has no colour swatches. El documento no tiene muestras de color. The edge of the paper the printer can't reach: the art goes inside it, and the preview shows it dashed. El borde del papel al que no llega la impresora: la ilustración queda dentro y la vista previa lo muestra discontinuo. @@ -3860,6 +3876,7 @@ axis Both Ambos @msg background {other}: transparent, white, black or a colour such as "#ff8800" fondo {other}: transparent, white, black o un color como "#ff8800" @msg bad color {v} color no válido {v} @msg the Color Picker is not open el Selector de color no está abierto +@msg the Simplify slider is not open el regulador de Simplificar no está abierto @msg the screen color sampler is already open el muestreador de color de la pantalla ya está abierto @msg this system has no screen color sampler este sistema no tiene muestreador de color de la pantalla @msg bad colour `{hex}` (#rrggbb) color no válido `{hex}` (#rrggbb) @@ -4097,6 +4114,7 @@ axis Both Ambos @msg select a linked image: an embedded one has no file selecciona una imagen vinculada: una incrustada no tiene archivo @msg select a repeat selecciona una repetición @msg select an Intertwine group selecciona un grupo entrelazado +@msg select an Objects on Path group selecciona un grupo de objetos en trazado @msg select a stroke with a variable width selecciona un trazo con anchura variable @msg select a symbol instance selecciona una instancia de símbolo @msg select an Image Trace object selecciona un objeto de calco de imagen @@ -4226,6 +4244,7 @@ axis Both Ambos @msg {_1} files are written by file.saveAsTemplate los archivos {_1} se escriben con file.saveAsTemplate @msg {_1} font families available {_1} familias de fuentes disponibles @msg {_1} is a live effect (Effect › Plug-ins) {_1} es un efecto interactivo (Efecto › Plugins) +@msg {_1} is an exporter (File › Export › Export As…) {_1} es un plugin de exportación (Archivo › Exportar › Exportar como…) @msg {_1} is already used by {_2} {_1} ya lo usa {_2} @msg {_1} linked file(s) can't be read here: their previews show aquí no se pueden leer {_1} archivo(s) vinculado(s): se muestran sus previsualizaciones @msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} imagen(es) vinculada(s) cambiaron en el disco: Actualizar vínculos muestra las versiones nuevas @@ -5099,6 +5118,7 @@ mark-style Japanese Japonesas @msg choose a destination folder elija una carpeta de destino @msg choose a source folder elija una carpeta de origen @msg open a document with data sets abra un documento con conjuntos de datos +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for no se aplicó nada del conjunto de datos {name}: ningún objeto está vinculado a una variable para la que tenga un valor @msg the action has no steps la acción no tiene pasos # User Interface › Accent Color @@ -5120,6 +5140,27 @@ mark-style Japanese Japonesas Movie Clip Clip de película @msg name is empty el nombre está vacío @msg no symbol named `{n}` no hay ningún símbolo llamado `{n}` + Smudge Stick… Difuminar con barra… + Smudge Stick Difuminar con barra + Sponge… Esponja… + Sponge Esponja + Watercolor… Acuarela… + Watercolor Acuarela + Brush Size Tamaño del pincel + Definition Definición + Brush Detail Detalle del pincel + Shadow Intensity Intensidad de sombras + Bas Relief… Bajorrelieve… + Bas Relief Bajorrelieve + Charcoal… Carboncillo… + Charcoal Carboncillo + Photocopy… Fotocopia… + Photocopy Fotocopia + Stamp… Sello… + Stamp Sello + Thickness Grosor + Detail Detalle + Light/Dark Balance Equilibrio claro/oscuro # Links and Attributes: files and URLs handed to other apps. @msg Edit Original opens image and document files only; “{name}” is not one Editar original solo abre archivos de imagen y de documento; “{name}” no lo es @msg only http, https and mailto URLs open in the browser, not “{url}” solo se abren en el navegador las URL http, https y mailto, no “{url}” @@ -5159,3 +5200,21 @@ mark-style Japanese Japonesas @msg the file's variables and data sets weren't read (variables: {variables}, data sets: {data_sets}): the Variables panel doesn't list them no se leyeron las variables ni los conjuntos de datos del archivo (variables: {variables}, conjuntos de datos: {data_sets}): el panel Variables no los muestra # Select by Color (select.color) Select by Color Seleccionar por color + Move Anchor Point Mover punto de ancla +@msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} conserva 1 de las {n} mesas de trabajo del documento: el archivo se vuelve a abrir con una. Active Conservar capacidades de edición para conservarlas todas. + Chalk & Charcoal… Tiza y carboncillo… + Chalk & Charcoal Tiza y carboncillo + Graphic Pen… Pluma gráfica… + Graphic Pen Pluma gráfica + Reticulation… Reticulación… + Reticulation Reticulación + Plastic Wrap… Envoltura plástica… + Plastic Wrap Envoltura plástica + Chrome… Cromo… + Chrome Cromo + Drop here to take it out of its group Suelta aquí para sacarlo de su grupo + Move Library Group Mover grupo de biblioteca + Plaster… Yeso… + Plaster Yeso + Note Paper… Papel con relieve… + Note Paper Papel con relieve diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index f9dbae414c..7cb564fafc 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -271,6 +271,8 @@ Large Gaps Suuret aukot Gap Preview Color: Aukkojen esikatseluväri: Close Gaps With Paths Sulje aukot poluilla + Select Fills Valitse täytöt + Select Strokes Valitse viivat Image Trace Kuvan jäljitys Image Trace (Make and Expand) Kuvan jäljitys (luo ja laajenna) Release Image Trace Vapauta kuvan jäljitys @@ -300,6 +302,7 @@ Plug-ins Laajennukset No filter plug-ins installed Suodinlaajennuksia ei ole asennettu Install Plug-in… Asenna laajennus… + Open this setting's help page Avaa tämän asetuksen ohjesivu Reload Plug-ins Lataa laajennukset uudelleen Type Teksti Font Fontti @@ -1539,6 +1542,12 @@ lighting Light Valo Release Blend Vapauta sulautus Release Envelope Vapauta kuori Release Intertwine Vapauta lomitus + Objects on Path Objektit polulla + Attach Kiinnitä + Objects on Path Options Objektit polulla -asetukset + Objects on Path Tool Objektit polulla -työkalu + Attach Objects on Path Kiinnitä objektit polulle + Expand Objects on Path Laajenna objektit polulla Release Live Paint Vapauta elävä maalaus Release Repeat Vapauta toisto Release Slice Vapauta siivu @@ -1612,7 +1621,7 @@ lighting Light Valo This library is empty Tämä kirjasto on tyhjä No results Ei tuloksia No items in this library match “{query}”. Mikään tämän kirjaston kohde ei vastaa hakua ”{query}”. - Right-click an item to move it into this group. Siirrä kohde tähän ryhmään napsauttamalla sitä hiiren kakkospainikkeella. + Drag an item here, or right-click one, to put it in this group. Vedä kohde tähän tai napsauta sitä hiiren kakkospainikkeella lisätäksesi sen tähän ryhmään. New Group Uusi ryhmä New Group… Uusi ryhmä… Move to Group Siirrä ryhmään @@ -1667,6 +1676,8 @@ lighting Light Valo Corner Point Angle Threshold: Kulmapisteiden kulmakynnys: Convert to Straight Lines Muunna suoriksi viivoiksi Show Original Path Näytä alkuperäinen polku + Open this dialog with these settings next time Avaa tämä valintaikkuna näillä asetuksilla ensi kerralla + Auto-Simplify Yksinkertaista automaattisesti Transparency Options Läpinäkyvyysasetukset Color Mixer (Shift-click the chip) Värisekoitin (Vaihto-napsauta värilaattaa) Fill: click for swatches, Shift-click for the color mixer Täyttö: napsauta avataksesi värimallit, Vaihto-napsauta avataksesi värisekoittimen @@ -1741,6 +1752,7 @@ lighting Light Valo Left in Front Vasen edessä No document Ei asiakirjaa Open a document to edit its patterns. Avaa asiakirja, niin voit muokata sen kuvioita. + Overlap Limitys Overlap: Limitys: Pattern options are available in pattern editing mode. Kuvioasetukset ovat käytettävissä kuvion muokkaustilassa. Right in Front Oikea edessä @@ -1868,6 +1880,7 @@ lighting Light Valo Right-Justified Tab Oikealle tasattu sarkain Select a text object to set its tab stops. Valitse tekstiobjekti, jonka sarkainkohdat haluat asettaa. Select text Valitse teksti + Snap to Unit Kohdista yksikköön + Add Scale + Lisää skaalaus Add Selected Artwork as One Asset Lisää valittu kuvitus yhtenä resurssina Export Settings Vientiasetukset @@ -2113,6 +2126,7 @@ lighting Light Valo One file per artboard: -.{ext} Yksi tiedosto piirtoalustaa kohden: -.{ext} One page per artboard. Yksi sivu piirtoalustaa kohden. The bounds of the visible art. Näkyvän kuvituksen rajat. + The plug-in writes the whole document. Laajennus vie koko asiakirjan. Use Artboards Käytä piirtoalustoja Choose a folder Valitse kansio Create Sub-folders Luo alikansiot @@ -2198,6 +2212,7 @@ lighting Light Valo Edit selected paths within: Muokkaa valittuja polkuja etäisyydellä: Fidelity: Tarkkuus: Fill new strokes Täytä uudet viivat + Alt key toggles to Smooth Tool Alt-näppäin vaihtaa Tasoitustyökaluun The document has no colour swatches. Asiakirjassa ei ole värimalleja. Style Name: Tyylin nimi: Crop To Rajaa kohteeseen @@ -2215,6 +2230,7 @@ lighting Light Valo Layers Panel Options Tasot-paneelin asetukset Row Size: Rivin koko: Show Layers Only Näytä vain tasot + Locate Selected Objects Paikanna valitut objektit Thumbnails: Pikkukuvat: Anchor Points Ankkuripisteet Brush Affects: Sivellin vaikuttaa: @@ -4449,6 +4465,7 @@ imageTrace Outline Ääriviiva @msg {_1} files are written by file.saveAsTemplate {_1}-tiedostot kirjoitetaan komennolla file.saveAsTemplate @msg {_1} font families available {_1} fonttiperhettä käytettävissä @msg {_1} is a live effect (Effect › Plug-ins) {_1} on live-tehoste (Tehoste › Laajennukset) +@msg {_1} is an exporter (File › Export › Export As…) {_1} on vientilaajennus (Tiedosto › Vie › Vie muodossa…) @msg {_1} is already used by {_2} {_1} on jo käytössä kohteella {_2} @msg {_1} linked file(s) can't be read here: their previews show {_1} linkitettyä tiedostoa ei voi lukea täällä: niiden esikatselut näytetään @msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} linkitettyä kuvaa muuttui levyllä: Päivitä linkit näyttää uudet versiot @@ -5108,13 +5125,16 @@ mark-style Japanese Japanilainen @msg choose a destination folder valitse kohdekansio @msg choose a source folder valitse lähdekansio @msg open a document with data sets avaa asiakirja, jossa on tietojoukkoja +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for tietojoukosta {name} ei käytetty mitään: mitään objektia ei ole sidottu muuttujaan, jolle siinä on arvo @msg select an Intertwine group valitse lomitusryhmä +@msg select an Objects on Path group valitse Objektit polulla -ryhmä @msg span must be "object" or "selection", got {v} span-arvon on oltava "object" tai "selection", saatiin {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" sijoittaa `gradient`-liukuvärin, ei värimallia @msg span: "selection" places a gradient: give `gradient` span: "selection" sijoittaa liukuvärin: anna `gradient` @msg span: "selection" places a linear or radial gradient, not a freeform one span: "selection" sijoittaa lineaarisen tai säteittäisen liukuvärin, ei vapaamuotoista @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" sijoittaa itse liukuvärin: jätä pois `start` ja `end` (ne sijoittavat sen jo asiakirjan koordinaatteihin) @msg the Color Picker is not open värinvalitsin ei ole auki +@msg the Simplify slider is not open Yksinkertaista-liukusäädin ei ole auki @msg the action has no steps toiminnossa ei ole vaiheita @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer tiedoston tasoja ei luettu ({_1}): se tuodaan sivunaan yhdelle tasolle @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part tiedoston tasoja ei luettu sen muokkaustiedoista ({_1}): ne tulevat sen PDF-osasta @@ -5142,6 +5162,27 @@ mark-style Japanese Japanilainen Movie Clip Elokuvaleike @msg name is empty nimi on tyhjä @msg no symbol named `{n}` symbolia nimeltä `{n}` ei ole + Smudge Stick… Sumennuskynä… + Smudge Stick Sumennuskynä + Sponge… Sieni… + Sponge Sieni + Watercolor… Vesiväri… + Watercolor Vesiväri + Brush Size Siveltimen koko + Definition Terävyys + Brush Detail Siveltimen yksityiskohta + Shadow Intensity Varjojen voimakkuus + Bas Relief… Matala korkokuva… + Bas Relief Matala korkokuva + Charcoal… Hiili… + Charcoal Hiili + Photocopy… Valokopio… + Photocopy Valokopio + Stamp… Leima… + Stamp Leima + Thickness Paksuus + Detail Yksityiskohta + Light/Dark Balance Vaalean ja tumman tasapaino # Links and Attributes: files and URLs handed to other apps. @msg Edit Original opens image and document files only; “{name}” is not one Muokkaa alkuperäistä avaa vain kuva- ja asiakirjatiedostoja; “{name}” ei ole sellainen @msg only http, https and mailto URLs open in the browser, not “{url}” selaimessa avataan vain http-, https- ja mailto-URL-osoitteet, ei “{url}” @@ -5181,3 +5222,88 @@ mark-style Japanese Japanilainen @msg the file's variables and data sets weren't read (variables: {variables}, data sets: {data_sets}): the Variables panel doesn't list them tiedoston muuttujia ja tietojoukkoja ei luettu (muuttujia: {variables}, tietojoukkoja: {data_sets}): Muuttujat-paneeli ei näytä niitä # Select by Color (select.color) Select by Color Valitse värin mukaan + Angular Kulma + Away from the Line Irti viivasta + Between Line and Object Viivan ja objektin väliin + Drag out from a segment, or click two points, then click to place. Vedä segmentistä tai napsauta kahta pistettä ja sijoita napsauttamalla. + Drag out from a corner, or click two straight lines, then click to place. Vedä kulmasta tai napsauta kahta suoraa viivaa ja sijoita napsauttamalla. + Drag out from a circle or arc for its radius, inwards for its diameter. Vedä ympyrästä tai kaaresta ulospäin säteelle, sisäänpäin halkaisijalle. + Display Näyttö +@msg Unknown dimension style Tuntematon mittatyyli +@msg Unknown unit Tuntematon yksikkö + Mode Tila + Blur Mode Sumennustila + Edge Only Vain reunat + Overlay Edge Reunat päällä + Path Length Polun pituus +swatch [None] [Ei mitään] +swatch [Registration] [Kohdistus] +swatch White Valkoinen +swatch Black Musta +swatch Red Punainen +swatch Orange Red Oranssinpunainen +swatch Orange Oranssi +swatch Amber Meripihka +swatch Yellow Keltainen +swatch Yellow Green Kellanvihreä +swatch Lime Limetti +swatch Green Vihreä +swatch Emerald Smaragdi +swatch Teal Sinivihreä +swatch Aqua Vedensininen +swatch Cyan Green Syaaninvihreä +swatch Cyan Syaani +swatch Azure Taivaansininen +swatch Blue Sininen +swatch Indigo Indigo +swatch Violet Violetti +swatch Purple Purppura +swatch Magenta Magenta +swatch Rose Ruusunpunainen +swatch Pink Vaaleanpunainen +swatch Brown Ruskea +swatch Tan Kellanruskea +swatch Coffee Kahvi +swatch Chocolate Suklaa +swatch Sand Hiekka +swatch Copper Kupari +swatch Rust Ruoste +swatch Walnut Pähkinä +swatch Espresso Espresso +swatch White, Black Valkoinen, musta +swatch Radial White, Black Säteittäinen valkoinen, musta +swatch Sunset Auringonlasku +swatch Ocean Valtameri +swatch Grays Harmaat +swatch Brights Kirkkaat +swatch Bright Red Kirkas punainen +swatch Bright Yellow Kirkas keltainen +swatch Bright Green Kirkas vihreä +swatch Bright Blue Kirkas sininen +swatch Bright Violet Kirkas violetti + Automate Automatisoi + Include All Subdirectories Sisällytä kaikki alikansiot + Override Action "Open" Commands Ohita toiminnon "Avaa"-komennot + Override Action "Save" Commands Ohita toiminnon "Tallenna"-komennot + Override Action "Export" Commands Ohita toiminnon "Vie"-komennot + Stop on Errors Pysäytä virheisiin + Save and Close Tallenna ja sulje + Play: Toista: + Move Anchor Point Siirrä ankkuripistettä +@msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} säilyttää asiakirjan {n} piirtoalustasta 1: tiedosto avautuu uudelleen yhdellä. Ota Säilytä muokkausominaisuudet käyttöön, jotta kaikki säilyvät. + Chalk & Charcoal… Liitu ja hiili… + Chalk & Charcoal Liitu ja hiili + Graphic Pen… Grafiikkakynä… + Graphic Pen Grafiikkakynä + Reticulation… Retikulaatio… + Reticulation Retikulaatio + Plastic Wrap… Muovikalvo… + Plastic Wrap Muovikalvo + Chrome… Kromi… + Chrome Kromi + Drop here to take it out of its group Pudota tähän poistaaksesi sen ryhmästään + Move Library Group Siirrä kirjastoryhmä + Plaster… Kipsi… + Plaster Kipsi + Note Paper… Kirjepaperi… + Note Paper Kirjepaperi diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index e8b3e71e7d..795ccf478a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1078,6 +1078,7 @@ Fill (X), double-click for the Color Picker Fond (X), double-cliquez pour ouvrir le Sélecteur de couleurs Fill and Stroke Fond et contour Fill new strokes Remplir les nouveaux contours + Alt key toggles to Smooth Tool La touche Alt bascule sur l’outil Arrondi Keep selected Garder sélectionné Merge only with selection Fusionner uniquement avec la sélection Fill Color Couleur de fond @@ -1198,6 +1199,8 @@ Large Gaps Grands espaces Gap Preview Color: Couleur d’aperçu des espaces : Close Gaps With Paths Fermer les espaces avec des tracés + Select Fills Sélectionner les fonds + Select Strokes Sélectionner les contours Gaussian Blur… Flou gaussien… General Général General › Placement › X Général › Placement › X @@ -1395,6 +1398,12 @@ Release Blend Annuler le dégradé de formes Release Envelope Annuler l’enveloppe Release Intertwine Annuler l’entrelacement + Objects on Path Objets sur tracé + Attach Attacher + Objects on Path Options Options d’objets sur tracé + Objects on Path Tool Outil Objets sur tracé + Attach Objects on Path Attacher des objets au tracé + Expand Objects on Path Décomposer les objets sur tracé Release Live Paint Annuler la peinture dynamique Release Repeat Annuler la répétition Release Slice Annuler la tranche @@ -1510,6 +1519,7 @@ Inspect Object Inspecter l’objet Install Plug-in Installer un module externe Install Plug-in… Installer un module externe… + Open this setting's help page Ouvrir la page d’aide de ce réglage Installed plug-in {} Module externe {} installé Intensity: Intensité : Intent: Mode de rendu : @@ -1712,6 +1722,7 @@ Load Text into Clipboard Charger du texte dans le presse-papiers Local Libraries Bibliothèques locales Locate Object Localiser l’objet + Locate Selected Objects Localiser les objets sélectionnés Location Emplacement Location: Emplacement : Lock Verrouiller @@ -2142,6 +2153,7 @@ Output White Blanc de sortie Output › Mode Sortie › Mode Output: Sortie : + Overlap Chevauchement Overlap: Chevauchement : Overlapping Superposés Overlay Incrustation @@ -2912,6 +2924,8 @@ Show Note Afficher la note Show Options Afficher les options Show Original Path Afficher le tracé d’origine + Open this dialog with these settings next time Ouvrir cette boîte de dialogue avec ces réglages la prochaine fois + Auto-Simplify Simplifier automatiquement Color Panel Options Options du panneau Couleur Show Package Afficher le dossier d’assemblage Show Panel Afficher le panneau @@ -3008,6 +3022,7 @@ Snap to Pixel Magnétisme du pixel Precise Cursors Pointeurs précis Snap to Point Magnétisme du point + Snap to Unit Magnétisme de l’unité Snapping Tolerance Tolérance du magnétisme Social Square Post 1080×1080 Publication carrée pour réseaux sociaux 1080×1080 Soft Light Lumière tamisée @@ -3135,7 +3150,7 @@ Delete Library Item Supprimer l’élément de la bibliothèque No results Aucun résultat No items in this library match “{query}”. Aucun élément de cette bibliothèque ne correspond à « {query} ». - Right-click an item to move it into this group. Cliquez avec le bouton droit sur un élément pour le placer dans ce groupe. + Drag an item here, or right-click one, to put it in this group. Faites glisser un élément ici, ou cliquez dessus avec le bouton droit, pour le placer dans ce groupe. New Group Nouveau groupe New Group… Nouveau groupe… Move to Group Déplacer vers le groupe @@ -3195,6 +3210,7 @@ Text Wrap Options Options d’habillage de texte Text Wrap Options… Options d’habillage de texte… The bounds of the visible art. Les limites de l’illustration visible. + The plug-in writes the whole document. Le module externe exporte le document entier. The cell shows the type object's text as HTML. La cellule affiche le texte de l’objet texte au format HTML. The document has no colour swatches. Le document ne contient aucune nuance de couleur. The edge of the paper the printer can't reach: the art goes inside it, and the preview shows it dashed. Le bord du papier que l’imprimante ne peut pas atteindre : l’illustration reste à l’intérieur, et l’aperçu l’affiche en pointillés. @@ -3857,6 +3873,7 @@ axis Both Les deux @msg background {other}: transparent, white, black or a colour such as "#ff8800" arrière-plan {other} : transparent, white, black ou une couleur comme "#ff8800" @msg bad color {v} couleur non valide {v} @msg the Color Picker is not open le Sélecteur de couleurs n’est pas ouvert +@msg the Simplify slider is not open le curseur Simplifier n’est pas ouvert @msg the screen color sampler is already open l’outil de prélèvement de couleur à l’écran est déjà ouvert @msg this system has no screen color sampler ce système n’a pas d’outil de prélèvement de couleur à l’écran @msg bad colour `{hex}` (#rrggbb) couleur non valide `{hex}` (#rrggbb) @@ -4094,6 +4111,7 @@ axis Both Les deux @msg select a linked image: an embedded one has no file sélectionnez une image liée : une image incorporée n’a pas de fichier @msg select a repeat sélectionnez une répétition @msg select an Intertwine group sélectionnez un groupe entrelacé +@msg select an Objects on Path group sélectionnez un groupe d’objets sur tracé @msg select a stroke with a variable width sélectionnez un contour de largeur variable @msg select a symbol instance sélectionnez une instance de symbole @msg select an Image Trace object sélectionnez un objet de vectorisation de l’image @@ -4223,6 +4241,7 @@ axis Both Les deux @msg {_1} files are written by file.saveAsTemplate les fichiers {_1} sont écrits par file.saveAsTemplate @msg {_1} font families available {_1} familles de polices disponibles @msg {_1} is a live effect (Effect › Plug-ins) {_1} est un effet dynamique (Effet › Plug-ins) +@msg {_1} is an exporter (File › Export › Export As…) {_1} est un module externe d’exportation (Fichier › Exporter › Exporter sous…) @msg {_1} is already used by {_2} {_1} est déjà utilisé par {_2} @msg {_1} linked file(s) can't be read here: their previews show {_1} fichier(s) lié(s) illisible(s) ici : leurs aperçus sont affichés @msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} image(s) liée(s) modifiée(s) sur le disque : Mettre à jour les liens affiche les nouvelles versions @@ -5156,6 +5175,7 @@ theme Appearance Apparence @msg choose a destination folder choisissez un dossier de destination @msg choose a source folder choisissez un dossier source @msg open a document with data sets ouvrez un document avec des jeux de données +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for rien du jeu de données {name} n’a été appliqué, car aucun objet n’est lié à une variable pour laquelle il a une valeur @msg the action has no steps l'action n'a aucune étape # User Interface › Accent Color @@ -5177,6 +5197,27 @@ theme Appearance Apparence Movie Clip Clip @msg name is empty le nom est vide @msg no symbol named `{n}` aucun symbole nommé `{n}` + Smudge Stick… Estompe… + Smudge Stick Estompe + Sponge… Éponge… + Sponge Éponge + Watercolor… Aquarelle… + Watercolor Aquarelle + Brush Size Taille du pinceau + Definition Définition + Brush Detail Détail du pinceau + Shadow Intensity Intensité des ombres + Bas Relief… Bas-relief… + Bas Relief Bas-relief + Charcoal… Fusain… + Charcoal Fusain + Photocopy… Photocopie… + Photocopy Photocopie + Stamp… Tampon… + Stamp Tampon + Thickness Épaisseur + Detail Détail + Light/Dark Balance Équilibre clair/foncé # Links and Attributes: files and URLs handed to other apps. @msg Edit Original opens image and document files only; “{name}” is not one Modifier l’original n’ouvre que les fichiers d’image et de document ; « {name} » n’en est pas un @msg only http, https and mailto URLs open in the browser, not “{url}” seules les URL http, https et mailto s’ouvrent dans le navigateur, pas « {url} » @@ -5216,3 +5257,21 @@ theme Appearance Apparence @msg the file's variables and data sets weren't read (variables: {variables}, data sets: {data_sets}): the Variables panel doesn't list them les variables et jeux de données du fichier n’ont pas été lus (variables : {variables}, jeux de données : {data_sets}) : le panneau Variables ne les affiche pas # Select by Color (select.color) Select by Color Sélectionner par couleur + Move Anchor Point Déplacer le point d’ancrage +@msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} conserve 1 des {n} plans de travail du document : le fichier se rouvre avec un seul. Activez Conserver les fonctions d’édition pour les conserver tous. + Chalk & Charcoal… Craie et fusain… + Chalk & Charcoal Craie et fusain + Graphic Pen… Plume graphique… + Graphic Pen Plume graphique + Reticulation… Réticulation… + Reticulation Réticulation + Plastic Wrap… Emballage plastique… + Plastic Wrap Emballage plastique + Chrome… Chrome… + Chrome Chrome + Drop here to take it out of its group Déposez ici pour le sortir de son groupe + Move Library Group Déplacer le groupe de bibliothèque + Plaster… Plâtre… + Plaster Plâtre + Note Paper… Papier gaufré… + Note Paper Papier gaufré diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 4a179e3645..10f3692901 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1365,6 +1365,7 @@ Fill and Stroke Kitöltés és körvonal Fill Color Kitöltőszín Fill new strokes Új vonások kitöltése + Alt key toggles to Smooth Tool Az Alt billentyű a Simítás eszközre vált Keep selected Kijelölés megtartása Merge only with selection Összeolvasztás csak a kijelöléssel Fill New Type Objects With Placeholder Text Új szövegobjektumok kitöltése helykitöltő szöveggel @@ -1504,6 +1505,8 @@ file-filter Templates Sablonok Large Gaps Nagy hézagok Gap Preview Color: Hézagok előnézeti színe: Close Gaps With Paths Hézagok lezárása útvonalakkal + Select Fills Kitöltések kijelölése + Select Strokes Körvonalak kijelölése Gaussian Blur Gauss-elmosás Gaussian Blur… Gauss-elmosás… General Általános @@ -1769,6 +1772,12 @@ file-filter Templates Sablonok Release Blend Összemosás megszüntetése Release Envelope Burkoló megszüntetése Release Intertwine Összefonás megszüntetése + Objects on Path Objektumok útvonalon + Attach Csatolás + Objects on Path Options Objektumok útvonalon beállításai + Objects on Path Tool Objektumok útvonalon + Attach Objects on Path Objektumok csatolása útvonalhoz + Expand Objects on Path Objektumok útvonalon kibontása Release Live Paint Élő festés megszüntetése Release Repeat Ismétlés megszüntetése Release Slice Szelet megszüntetése @@ -1902,6 +1911,7 @@ file-filter Templates Sablonok Inspect Object Objektum vizsgálata Install Plug-in Bővítmény telepítése Install Plug-in… Bővítmény telepítése… + Open this setting's help page A beállítás súgóoldalának megnyitása Installed plug-in {} Telepített bővítmény: {} Intensity Erősség Intensity: Erősség: @@ -2162,6 +2172,7 @@ file-filter Templates Sablonok Loaded Texture Betöltött textúra Local Libraries Helyi könyvtárak Locate Object Objektum megkeresése + Locate Selected Objects Kijelölt objektumok megkeresése Location Hely Location: Hely: Lock Zárolás @@ -2630,6 +2641,7 @@ file-filter Templates Sablonok Output › Mode Kimenet › Mód Output: Kimenet: Oval Ovális + Overlap Átfedés Overlap: Átfedés: Overlapping Átfedő Overlay Átfedés @@ -3160,7 +3172,7 @@ mark-style Japanese Japán Right Indent Jobb behúzás Right Plane Jobb sík Right to Left Jobbról balra - Right-click an item to move it into this group. Egy elemet jobb gombbal kattintva helyezhetsz át ebbe a csoportba. + Drag an item here, or right-click one, to put it in this group. Húzz ide egy elemet, vagy kattints rá jobb gombbal, hogy ebbe a csoportba kerüljön. Right-Justified Tab Jobbra igazító tabulátor Right-to-Left Paragraph Direction Jobbról balra haladó bekezdés Right: Jobb: @@ -3533,6 +3545,8 @@ mark-style Japanese Japán Show Note Megjegyzés megjelenítése Show Options Beállítások megjelenítése Show Original Path Eredeti útvonal megjelenítése + Open this dialog with these settings next time Legközelebb ez a párbeszédablak nyíljon meg ezekkel a beállításokkal + Auto-Simplify Automatikus egyszerűsítés Color Panel Options Szín panel beállításai Show Package Csomag megjelenítése Show Panel Panel megjelenítése @@ -3631,6 +3645,7 @@ mark-style Japanese Japán Snap to Pixel Illesztés pixelhez Precise Cursors Pontos kurzorok Snap to Point Illesztés pontra + Snap to Unit Illesztés mértékegységhez Snapping Tolerance Illesztési tűrés Social Közösségi média Social Landscape Post 1200×630 Fekvő közösségimédia-bejegyzés 1200×630 @@ -3855,6 +3870,7 @@ mark-style Japanese Japán Texturizer… Textúrázó… Thai Thai The bounds of the visible art. A látható grafika határai. + The plug-in writes the whole document. A bővítmény a teljes dokumentumot exportálja. The cell shows the type object's text as HTML. A cella a szövegobjektum szövegét HTML-ként mutatja. The dialog was closed before its file dialog answered A párbeszédablak bezárult, mielőtt a fájlválasztó válaszolt volna The document has no colour swatches. A dokumentumban nincs színminta. @@ -4403,6 +4419,7 @@ imageTrace Outline Körvonal @msg background {other}: transparent, white, black or a colour such as "#ff8800" background {other}: transparent, white, black vagy egy szín, például "#ff8800" @msg bad color {v} hibás szín: {v} @msg the Color Picker is not open a Színválasztó nincs megnyitva +@msg the Simplify slider is not open az Egyszerűsítés csúszka nincs megnyitva @msg the screen color sampler is already open a képernyős színmintavevő már nyitva van @msg this system has no screen color sampler ezen a rendszeren nincs képernyős színmintavevő @msg bad colour `{hex}` (#rrggbb) hibás szín: `{hex}` (#rrggbb) @@ -4786,6 +4803,7 @@ imageTrace Outline Körvonal @msg select a Live Paint group jelölj ki egy élőfestés-csoportot @msg select a repeat jelölj ki egy ismétlést @msg select an Intertwine group jelölj ki egy összefonási csoportot +@msg select an Objects on Path group jelölj ki egy Objektumok útvonalon csoportot @msg select a stroke with a variable width jelölj ki egy változó szélességű körvonalat @msg select a symbol instance jelölj ki egy szimbólumpéldányt @msg select an envelope jelölj ki egy burkolót @@ -4965,6 +4983,7 @@ imageTrace Outline Körvonal @msg {_1} font families available Elérhető betűcsaládok: {_1} @msg {_1} has no {_2} style ennek nincs ilyen stílusa: {_1} ({_2}) @msg {_1} is a live effect (Effect › Plug-ins) élő effektus: {_1} (Effektus › Bővítmények) +@msg {_1} is an exporter (File › Export › Export As…) exportáló bővítmény: {_1} (Fájl › Exportálás › Exportálás másként…) @msg {_1} is already used by {_2} már foglalt: {_1} (használja: {_2}) @msg {_1} linked file(s) can't be read here: their previews show Itt nem olvasható csatolt fájlok: {_1}; az előnézetük látszik @msg {_1} linked image(s) changed on disk: Update Links shows the new versions A lemezen módosult csatolt képek: {_1}; a Csatolások frissítése az új változatokat mutatja @@ -5143,6 +5162,7 @@ imageTrace Outline Körvonal @msg choose a destination folder válasszon célmappát @msg choose a source folder válasszon forrásmappát @msg open a document with data sets nyisson meg egy adatkészleteket tartalmazó dokumentumot +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for ebből az adatkészletből semmi sem lett alkalmazva: {name}; egyetlen objektum sincs olyan változóhoz kötve, amelynek értéke van benne @msg the action has no steps a műveletnek nincsenek lépései # User Interface › Accent Color @@ -5164,6 +5184,27 @@ imageTrace Outline Körvonal Movie Clip Mozgóklip @msg name is empty a név üres @msg no symbol named `{n}` nincs `{n}` nevű szimbólum + Smudge Stick… Elmosó rúd… + Smudge Stick Elmosó rúd + Sponge… Szivacs… + Sponge Szivacs + Watercolor… Akvarell… + Watercolor Akvarell + Brush Size Ecsetméret + Definition Kidolgozottság + Brush Detail Ecsetrészletesség + Shadow Intensity Árnyék intenzitása + Bas Relief… Dombormű… + Bas Relief Dombormű + Charcoal… Szén… + Charcoal Szén + Photocopy… Fénymásolat… + Photocopy Fénymásolat + Stamp… Bélyegző… + Stamp Bélyegző + Thickness Vastagság + Detail Részletesség + Light/Dark Balance Világos/sötét egyensúly # Links and Attributes: files and URLs handed to other apps. @msg Edit Original opens image and document files only; “{name}” is not one az Eredeti szerkesztése csak kép- és dokumentumfájlokat nyit meg; ez nem ilyen: „{name}” @msg only http, https and mailto URLs open in the browser, not “{url}” a böngészőben csak a http-, https- és mailto-URL-ek nyílnak meg; ez nem ilyen: „{url}” @@ -5203,3 +5244,21 @@ imageTrace Outline Körvonal @msg the file's variables and data sets weren't read (variables: {variables}, data sets: {data_sets}): the Variables panel doesn't list them a fájl változói és adatkészletei nem lettek beolvasva (változók: {variables}, adatkészletek: {data_sets}): a Változók panel nem listázza őket # Select by Color (select.color) Select by Color Kijelölés szín szerint + Move Anchor Point Horgonypont áthelyezése +@msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. A(z) {label} a dokumentum {n} rajztáblájából 1-et tart meg: a fájl eggyel nyílik meg újra. Kapcsolja be a Szerkeszthetőség megtartása beállítást, hogy mind megmaradjon. + Chalk & Charcoal… Kréta és szén… + Chalk & Charcoal Kréta és szén + Graphic Pen… Grafikus toll… + Graphic Pen Grafikus toll + Reticulation… Recézés… + Reticulation Recézés + Plastic Wrap… Fóliázás… + Plastic Wrap Fóliázás + Chrome… Króm… + Chrome Króm + Drop here to take it out of its group Engedd el itt, hogy kikerüljön a csoportjából + Move Library Group Könyvtárcsoport áthelyezése + Plaster… Gipsz… + Plaster Gipsz + Note Paper… Jegyzetpapír… + Note Paper Jegyzetpapír diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 4001b3d776..4f36c001c1 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -269,6 +269,7 @@ Plug-ins Plug-in No filter plug-ins installed Tidak ada plug-in filter yang terinstal Install Plug-in… Instal plug-in… + Open this setting's help page Buka halaman bantuan pengaturan ini Reload Plug-ins Muat ulang plug-in Type Teks Font Font @@ -1489,7 +1490,7 @@ lighting Light Cahaya This library is empty Pustaka ini kosong No results Tidak ada hasil No items in this library match “{query}”. Tidak ada item di pustaka ini yang cocok dengan “{query}”. - Right-click an item to move it into this group. Klik kanan item untuk memindahkannya ke grup ini. + Drag an item here, or right-click one, to put it in this group. Seret item ke sini, atau klik kanan item, untuk memasukkannya ke grup ini. New Group Grup baru New Group… Grup baru… Move to Group Pindahkan ke grup @@ -1607,6 +1608,7 @@ lighting Light Cahaya Left in Front Kiri di depan No document Tidak ada dokumen Open a document to edit its patterns. Buka dokumen untuk mengedit polanya. + Overlap Tumpang tindih Overlap: Tumpang tindih: Pattern options are available in pattern editing mode. Opsi pola tersedia dalam mode pengeditan pola. Right in Front Kanan di depan @@ -1734,6 +1736,7 @@ lighting Light Cahaya Right-Justified Tab Tab rata kanan Select a text object to set its tab stops. Pilih objek teks untuk mengatur tab stop-nya. Select text Pilih teks + Snap to Unit Snap ke satuan + Add Scale + Tambah skala Add Selected Artwork as One Asset Tambahkan karya seni terpilih sebagai satu aset Export Settings Pengaturan ekspor @@ -1978,6 +1981,7 @@ lighting Light Cahaya One file per artboard: -.{ext} Satu file per artboard: -.{ext} One page per artboard. Satu halaman per artboard. The bounds of the visible art. Batas karya seni yang terlihat. + The plug-in writes the whole document. Plug-in mengekspor seluruh dokumen. Use Artboards Gunakan artboard Choose a folder Pilih folder Create Sub-folders Buat subfolder @@ -2063,6 +2067,7 @@ lighting Light Cahaya Edit selected paths within: Edit jalur terpilih dalam jarak: Fidelity: Fidelitas: Fill new strokes Isi stroke baru + Alt key toggles to Smooth Tool Tombol Alt beralih ke Alat penghalus The document has no colour swatches. Dokumen tidak memiliki swatch warna. Style Name: Nama gaya: Crop To Pangkas ke @@ -2080,6 +2085,7 @@ lighting Light Cahaya Layers Panel Options Opsi panel lapisan Row Size: Ukuran baris: Show Layers Only Tampilkan lapisan saja + Locate Selected Objects Temukan objek terpilih Thumbnails: Miniatur: Anchor Points Titik jangkar Brush Affects: Kuas memengaruhi: @@ -5049,6 +5055,8 @@ swatch Bright Violet Violet cerah Outline Object Kerangka objek Update Selection Perbarui seleksi Show Original Path Tampilkan jalur asli + Open this dialog with these settings next time Buka dialog ini dengan pengaturan ini lain kali + Auto-Simplify Sederhanakan otomatis @msg check a layer to export centang lapisan yang akan diekspor @msg select the art to export first pilih dulu karya yang akan diekspor @msg no saved selection recalled tidak ada seleksi tersimpan yang dipanggil @@ -5074,6 +5082,8 @@ swatch Bright Violet Violet cerah Chop Design Potong desain Clear Events Hapus peristiwa Close Gaps With Paths Tutup celah dengan jalur + Select Fills Pilih isian + Select Strokes Pilih stroke Column Type: Jenis kolom: Each Design Represents: Setiap desain mewakili: Event: Peristiwa: @@ -5151,6 +5161,12 @@ swatch Bright Violet Violet cerah Release Blend Lepaskan blend Release Envelope Lepaskan amplop Release Intertwine Lepaskan jalinan + Objects on Path Objek pada jalur + Attach Tempelkan + Objects on Path Options Opsi objek pada jalur + Objects on Path Tool Alat objek pada jalur + Attach Objects on Path Tempelkan objek pada jalur + Expand Objects on Path Perluas objek pada jalur Release Live Paint Lepaskan Live Paint Release Repeat Lepaskan perulangan Release Slice Lepaskan slice @@ -5197,3 +5213,41 @@ swatch Bright Violet Violet cerah Justification Justifikasi # Select by Color (select.color) Select by Color Pilih berdasarkan warna + Smudge Stick… Tongkat olesan… + Smudge Stick Tongkat olesan + Sponge… Spons… + Sponge Spons + Watercolor… Cat air… + Watercolor Cat air + Brush Size Ukuran kuas + Definition Definisi + Brush Detail Detail kuas + Shadow Intensity Intensitas bayangan + Bas Relief… Relief dangkal… + Bas Relief Relief dangkal + Charcoal… Arang… + Charcoal Arang + Photocopy… Fotokopi… + Photocopy Fotokopi + Stamp… Stempel… + Stamp Stempel + Thickness Ketebalan + Detail Detail + Light/Dark Balance Keseimbangan terang/gelap + Move Anchor Point Pindahkan titik jangkar + Chalk & Charcoal… Kapur dan arang… + Chalk & Charcoal Kapur dan arang + Graphic Pen… Pena grafis… + Graphic Pen Pena grafis + Reticulation… Retikulasi… + Reticulation Retikulasi + Plastic Wrap… Pembungkus plastik… + Plastic Wrap Pembungkus plastik + Chrome… Krom… + Chrome Krom + Drop here to take it out of its group Lepaskan di sini untuk mengeluarkannya dari grupnya + Move Library Group Pindahkan grup pustaka + Plaster… Plester… + Plaster Plester + Note Paper… Kertas Catatan… + Note Paper Kertas Catatan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index dcc5e91c0b..eb0f295c37 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1078,6 +1078,7 @@ Fill (X), double-click for the Color Picker Riempimento (X), fai doppio clic per il selettore colore Fill and Stroke Riempimento e traccia Fill new strokes Riempi nuove tracce + Alt key toggles to Smooth Tool Il tasto Alt attiva lo strumento Smussa Keep selected Mantieni selezionato Merge only with selection Unisci solo con la selezione Fill Color Colore riempimento @@ -1208,6 +1209,8 @@ file-filter Templates Modelli Large Gaps Spazi vuoti grandi Gap Preview Color: Colore anteprima spazi vuoti: Close Gaps With Paths Chiudi spazi vuoti con tracciati + Select Fills Seleziona riempimenti + Select Strokes Seleziona tracce Gaussian Blur… Sfocatura gaussiana… General Generale General › Placement › X Generale › Posizionamento › X @@ -1415,6 +1418,12 @@ file-filter Templates Modelli Release Envelope Rilascia involucro Release Image Trace Rilascia ricalco immagine Release Intertwine Rilascia intreccio + Objects on Path Oggetti su tracciato + Attach Aggancia + Objects on Path Options Opzioni oggetti su tracciato + Objects on Path Tool Strumento Oggetti su tracciato + Attach Objects on Path Aggancia oggetti al tracciato + Expand Objects on Path Espandi oggetti su tracciato Release Live Paint Rilascia pittura dinamica Release Repeat Rilascia ripetizione Release Slice Rilascia sezione @@ -1535,6 +1544,7 @@ file-filter Templates Modelli Inspect Object Ispeziona oggetto Install Plug-in Installa plug-in Install Plug-in… Installa plug-in… + Open this setting's help page Apri la pagina della guida di questa impostazione Installed plug-in {} Plug-in {} installato Intensity: Intensità: Intent: Intento: @@ -1739,6 +1749,7 @@ file-filter Templates Modelli Load Text into Clipboard Carica testo negli appunti Local Libraries Librerie locali Locate Object Individua oggetto + Locate Selected Objects Individua oggetti selezionati Location Posizione Location: Posizione: Lock Blocca @@ -2171,6 +2182,7 @@ file-filter Templates Modelli Output White Bianco di output Output › Mode Output › Modalità Output: Output: + Overlap Sovrapposizione Overlap: Sovrapposizione: Overlapping Sovrapposti Overlay Sovrapponi @@ -2948,6 +2960,8 @@ mark-style Japanese Giapponese Show Note Mostra nota Show Options Mostra opzioni Show Original Path Mostra tracciato originale + Open this dialog with these settings next time Apri questa finestra di dialogo con queste impostazioni la prossima volta + Auto-Simplify Semplifica automaticamente Color Panel Options Opzioni pannello Colore Show Package Mostra pacchetto Show Panel Mostra pannello @@ -3044,6 +3058,7 @@ mark-style Japanese Giapponese Snap to Pixel Aggancia ai pixel Precise Cursors Cursori di precisione Snap to Point Aggancia al punto + Snap to Unit Aggancia all'unità Snapping Tolerance Tolleranza di aggancio Social Square Post 1080×1080 Post quadrato per social 1080×1080 Soft Light Luce soffusa @@ -3171,7 +3186,7 @@ mark-style Japanese Giapponese Delete Library Item Elimina elemento della libreria No results Nessun risultato No items in this library match “{query}”. Nessun elemento di questa libreria corrisponde a “{query}”. - Right-click an item to move it into this group. Fai clic con il pulsante destro su un elemento per spostarlo in questo gruppo. + Drag an item here, or right-click one, to put it in this group. Trascina qui un elemento, o fai clic con il pulsante destro su uno, per metterlo in questo gruppo. New Group Nuovo gruppo New Group… Nuovo gruppo… Move to Group Sposta nel gruppo @@ -3231,6 +3246,7 @@ mark-style Japanese Giapponese Text Wrap Options Opzioni testo attorno Text Wrap Options… Opzioni testo attorno… The bounds of the visible art. I limiti della grafica visibile. + The plug-in writes the whole document. Il plug-in esporta l'intero documento. The cell shows the type object's text as HTML. La cella mostra il testo dell'oggetto testo come HTML. The document has no colour swatches. Il documento non ha campioni di colore. The edge of the paper the printer can't reach: the art goes inside it, and the preview shows it dashed. Il bordo del foglio che la stampante non riesce a raggiungere: la grafica resta al suo interno e l'anteprima lo mostra tratteggiato. @@ -3899,6 +3915,7 @@ axis Both Entrambi @msg background {other}: transparent, white, black or a colour such as "#ff8800" sfondo {other}: transparent, white, black o un colore come "#ff8800" @msg bad color {v} colore non valido {v} @msg the Color Picker is not open il Selettore colore non è aperto +@msg the Simplify slider is not open il cursore Semplifica non è aperto @msg the screen color sampler is already open il campionatore di colore dello schermo è già aperto @msg this system has no screen color sampler questo sistema non ha un campionatore di colore dello schermo @msg bad colour `{hex}` (#rrggbb) colore non valido `{hex}` (#rrggbb) @@ -4136,6 +4153,7 @@ axis Both Entrambi @msg select a linked image: an embedded one has no file seleziona un'immagine collegata: un'immagine incorporata non ha un file @msg select a repeat seleziona una ripetizione @msg select an Intertwine group seleziona un gruppo intrecciato +@msg select an Objects on Path group seleziona un gruppo di oggetti su tracciato @msg select a stroke with a variable width seleziona una traccia con larghezza variabile @msg select a symbol instance seleziona un'istanza di simbolo @msg select an Image Trace object seleziona un oggetto di ricalco immagine @@ -4265,6 +4283,7 @@ axis Both Entrambi @msg {_1} files are written by file.saveAsTemplate i file {_1} vengono scritti da file.saveAsTemplate @msg {_1} font families available {_1} famiglie di font disponibili @msg {_1} is a live effect (Effect › Plug-ins) {_1} è un effetto dinamico (Effetto › Plug-in) +@msg {_1} is an exporter (File › Export › Export As…) {_1} è un plug-in di esportazione (File › Esporta › Esporta come…) @msg {_1} is already used by {_2} {_1} è già usato da {_2} @msg {_1} linked file(s) can't be read here: their previews show file collegati non leggibili qui: {_1}; vengono mostrate le loro anteprime @msg {_1} linked image(s) changed on disk: Update Links shows the new versions immagini collegate modificate su disco: {_1}; Aggiorna collegamenti mostra le nuove versioni @@ -4769,6 +4788,7 @@ lighting Light Luce @msg choose a destination folder scegli una cartella di destinazione @msg choose a source folder scegli una cartella di origine @msg open a document with data sets apri un documento con set di dati +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for non è stato applicato nulla del set di dati {name}: nessun oggetto è associato a una variabile per cui ha un valore @msg the action has no steps l'azione non ha passaggi # User Interface › Accent Color @@ -4791,6 +4811,27 @@ lighting Light Luce Movie Clip Clip filmato @msg name is empty il nome è vuoto @msg no symbol named `{n}` nessun simbolo denominato `{n}` + Smudge Stick… Sfumino… + Smudge Stick Sfumino + Sponge… Spugna… + Sponge Spugna + Watercolor… Acquerello… + Watercolor Acquerello + Brush Size Dimensione pennello + Definition Definizione + Brush Detail Dettaglio pennello + Shadow Intensity Intensità ombre + Bas Relief… Bassorilievo… + Bas Relief Bassorilievo + Charcoal… Carboncino… + Charcoal Carboncino + Photocopy… Fotocopia… + Photocopy Fotocopia + Stamp… Timbro… + Stamp Timbro + Thickness Spessore + Detail Dettaglio + Light/Dark Balance Equilibrio chiaro/scuro # Links and Attributes: files and URLs handed to other apps. @msg Edit Original opens image and document files only; “{name}” is not one Modifica originale apre solo file di immagini e documenti; “{name}” non lo è @msg only http, https and mailto URLs open in the browser, not “{url}” nel browser si aprono solo URL http, https e mailto, non “{url}” @@ -4831,3 +4872,21 @@ lighting Light Luce @msg the file's variables and data sets weren't read (variables: {variables}, data sets: {data_sets}): the Variables panel doesn't list them le variabili e i set di dati del file non sono stati letti (variabili: {variables}, set di dati: {data_sets}): il pannello Variabili non li elenca # Select by Color (select.color) Select by Color Seleziona per colore + Move Anchor Point Sposta punto di ancoraggio +@msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} mantiene 1 delle {n} tavole da disegno del documento: il file si riapre con una sola. Attiva Mantieni possibilità di modifica per mantenerle tutte. + Chalk & Charcoal… Gesso e carboncino… + Chalk & Charcoal Gesso e carboncino + Graphic Pen… Penna grafica… + Graphic Pen Penna grafica + Reticulation… Reticolo… + Reticulation Reticolo + Plastic Wrap… Pellicola plastica… + Plastic Wrap Pellicola plastica + Chrome… Cromo… + Chrome Cromo + Drop here to take it out of its group Rilascia qui per toglierlo dal suo gruppo + Move Library Group Sposta gruppo di libreria + Plaster… Gesso… + Plaster Gesso + Note Paper… Carta da lettere… + Note Paper Carta da lettere diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 80c98c37be..dfa24312cd 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -262,6 +262,8 @@ Large Gaps 大きい間隔 Gap Preview Color: 間隔のプレビューカラー: Close Gaps With Paths パスで間隔を閉じる + Select Fills 塗りを選択 + Select Strokes 線を選択 Image Trace 画像トレース Image Tracing 画像トレースオブジェクト Tracing Presets トレースプリセット @@ -287,6 +289,7 @@ Plug-ins プラグイン No filter plug-ins installed フィルタープラグインはインストールされていません Install Plug-in… プラグインをインストール… + Open this setting's help page この設定のヘルプページを開く Reload Plug-ins プラグインを再読み込み Type 書式 Font フォント @@ -1478,6 +1481,7 @@ Fill Rule 塗りのルール Fill and Stroke 塗りと線 Fill new strokes 新しいストロークに塗りを適用 + Alt key toggles to Smooth Tool Alt キーでスムーズツールに切り替え Keep selected 選択を保持 Merge only with selection 選択範囲とのみ結合 Fill: 塗り: @@ -1660,6 +1664,12 @@ Release Envelope エンベロープを解除 Release Image Trace 画像トレースを解除 Release Intertwine 織り交ぜを解除 + Objects on Path パス上のオブジェクト + Attach アタッチ + Objects on Path Options パス上のオブジェクトオプション + Objects on Path Tool パス上のオブジェクトツール + Attach Objects on Path パス上のオブジェクトをアタッチ + Expand Objects on Path パス上のオブジェクトを拡張 Release Live Paint ライブペイントを解除 Release Repeat リピートを解除 Release Slice スライスを解除 @@ -1911,6 +1921,7 @@ Load Text into Clipboard テキストをクリップボードに読み込む Local Libraries ローカルライブラリ Locate Object オブジェクトを検索 + Locate Selected Objects 選択したオブジェクトを検索 Location 場所 Location: 位置: Lock (⌘2) ロック (⌘2) @@ -2235,6 +2246,7 @@ Output condition: 出力条件: Output intent profile: 出力インテントプロファイル: Output: 出力: + Overlap 重なり Overlap: 重なり: Overlapping 重なり Overlay オーバーレイ @@ -2756,6 +2768,8 @@ mark-style Japanese 日本式 Show Note メモを表示 Show Options オプションを表示 Show Original Path 元のパスを表示 + Open this dialog with these settings next time 次回はこの設定でこのダイアログを開く + Auto-Simplify 自動単純化 Color Panel Options カラーパネルオプション Show Package パッケージを表示 Show Panel パネルを表示 @@ -2821,6 +2835,7 @@ mark-style Japanese 日本式 Source Image 元画像 Image Trace View 画像トレースの表示 Snap Options スナップオプション + Snap to Unit 単位にスナップ Snapping Tolerance スナップ許容値 Soft Light ソフトライト Solid 実線 @@ -2903,7 +2918,7 @@ mark-style Japanese 日本式 Delete Library Item ライブラリ項目を削除 No results 結果はありません No items in this library match “{query}”. このライブラリには「{query}」に一致する項目がありません。 - Right-click an item to move it into this group. 項目を右クリックすると、このグループに移動できます。 + Drag an item here, or right-click one, to put it in this group. 項目をここにドラッグするか、項目を右クリックすると、このグループに入れられます。 New Group 新規グループ New Group… 新規グループ… Move to Group グループに移動 @@ -2946,6 +2961,7 @@ mark-style Japanese 日本式 Text Import Options テキスト読み込みオプション The Print Tiling tool placed the pages. プリント分割ツールでページが配置されています。 The bounds of the visible art. 表示されているアートの範囲。 + The plug-in writes the whole document. プラグインがドキュメント全体を書き出します。 The cell shows the type object's text as HTML. セルには文字オブジェクトのテキストが HTML として表示されます。 The document has no colour swatches. ドキュメントにカラースウォッチがありません。 The edge of the paper the printer can't reach: the art goes inside it, and the preview shows it dashed. プリンターが印刷できない用紙の端の部分です。アートはこの内側に配置され、プレビューでは破線で表示されます。 @@ -4019,6 +4035,7 @@ swatch Bright Violet ビビッドバイオレット @msg pattern missing パターンが見つかりません @msg select a repeat リピートを選択してください @msg select an Intertwine group 織り交ぜグループを選択してください +@msg select an Objects on Path group パス上のオブジェクトグループを選択してください @msg select the art to repeat リピートするアートを選択してください @msg the document has no patterns ドキュメントにパターンがありません @msg no artboard アートボードがありません @@ -4213,6 +4230,7 @@ swatch Bright Violet ビビッドバイオレット @msg no blend options ブレンドオプションがありません @msg bad color {v} カラー {v} が正しくありません @msg the Color Picker is not open カラーピッカーが開いていません +@msg the Simplify slider is not open 単純化スライダーが開いていません @msg the screen color sampler is already open 画面のカラーサンプラーはすでに開いています @msg this system has no screen color sampler このシステムには画面のカラーサンプラーがありません @msg Corners edits the corners of a path 「コーナー」で編集できるのはパスの角だけです @@ -4255,6 +4273,7 @@ swatch Bright Violet ビビッドバイオレット @msg missing `id` (see plugin.list) `id` が指定されていません (plugin.list を参照) @msg no plug-in {id} is installed プラグイン {id} はインストールされていません @msg {_1} is a live effect (Effect › Plug-ins) {_1} はライブ効果です (「効果 › プラグイン」から使用してください) +@msg {_1} is an exporter (File › Export › Export As…) {_1} は書き出しプラグインです (「ファイル › 書き出し › 形式を指定して書き出し…」から使用してください) @msg a preset named `{_1}` exists `{_1}` という名前のプリセットはすでに存在します @msg a swatch or color group named `{n}` exists `{n}` という名前のスウォッチまたはカラーグループはすでに存在します @msg no print preset named `{base}` `{base}` という名前のプリントプリセットが見つかりません @@ -4809,6 +4828,7 @@ lighting Light ライト @msg choose a destination folder 出力先フォルダーを選択してください @msg choose a source folder ソースフォルダーを選択してください @msg open a document with data sets データセットのあるドキュメントを開いてください +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for データセット {name} から何も適用されませんでした: 値のある変数にバインドされたオブジェクトがありません @msg the action has no steps アクションにステップがありません # User Interface › Accent Color @@ -4831,6 +4851,27 @@ lighting Light ライト Movie Clip ムービークリップ @msg name is empty 名前が空です @msg no symbol named `{n}` `{n}` という名前のシンボルはありません + Smudge Stick… スマッジスティック… + Smudge Stick スマッジスティック + Sponge… スポンジ… + Sponge スポンジ + Watercolor… 水彩… + Watercolor 水彩 + Brush Size ブラシサイズ + Definition 精細度 + Brush Detail ブラシの細かさ + Shadow Intensity シャドウの強さ + Bas Relief… レリーフ… + Bas Relief レリーフ + Charcoal… 木炭… + Charcoal 木炭 + Photocopy… コピー… + Photocopy コピー + Stamp… スタンプ… + Stamp スタンプ + Thickness 太さ + Detail ディテール + Light/Dark Balance 明暗のバランス # Links and Attributes: files and URLs handed to other apps. @msg Edit Original opens image and document files only; “{name}” is not one 「オリジナルを編集」で開けるのは画像ファイルとドキュメントファイルだけです: 「{name}」はどちらでもありません @msg only http, https and mailto URLs open in the browser, not “{url}” ブラウザーで開けるのは http、https、mailto の URL だけです: 「{url}」は開けません @@ -4871,3 +4912,21 @@ lighting Light ライト @msg the file's variables and data sets weren't read (variables: {variables}, data sets: {data_sets}): the Variables panel doesn't list them ファイルの変数とデータセットは読み込まれませんでした (変数: {variables}、データセット: {data_sets})。変数パネルには表示されません # Select by Color (select.color) Select by Color カラーで選択 + Move Anchor Point アンカーポイントを移動 +@msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} ではドキュメントの {n} 個のアートボードのうち 1 個だけが保持され、ファイルは 1 個で開き直されます。すべて保持するには「編集機能を保持」をオンにしてください。 + Chalk & Charcoal… チョーク・木炭画… + Chalk & Charcoal チョーク・木炭画 + Graphic Pen… グラフィックペン… + Graphic Pen グラフィックペン + Reticulation… 網目… + Reticulation 網目 + Plastic Wrap… ラップ… + Plastic Wrap ラップ + Chrome… クロム… + Chrome クロム + Drop here to take it out of its group ここにドロップするとグループから外れます + Move Library Group ライブラリグループを移動 + Plaster… 石膏… + Plaster 石膏 + Note Paper… ノート用紙… + Note Paper ノート用紙 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 0bc503c1b8..76f92020d8 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -228,6 +228,7 @@ Plug-ins პლაგინები No filter plug-ins installed ფილტრის პლაგინები არ არის დაყენებული Install Plug-in… პლაგინის დაყენება… + Open this setting's help page ამ პარამეტრის დახმარების გვერდის გახსნა Reload Plug-ins პლაგინების ხელახლა ჩატვირთვა Type ტექსტი Font შრიფტი @@ -1398,7 +1399,7 @@ lighting Light სინათლე This library is empty ეს ბიბლიოთეკა ცარიელია No results შედეგები არ არის No items in this library match “{query}”. ამ ბიბლიოთეკაში „{query}“-ს შესაბამისი ელემენტი არ არის. - Right-click an item to move it into this group. ამ ჯგუფში გადასატანად დაწკაპეთ ელემენტზე მარჯვენა ღილაკით. + Drag an item here, or right-click one, to put it in this group. ამ ჯგუფში ჩასასმელად ჩაავლეთ ელემენტი აქ ან დაწკაპეთ მასზე მარჯვენა ღილაკით. New Group ახალი ჯგუფი New Group… ახალი ჯგუფი… Move to Group ჯგუფში გადატანა @@ -1509,6 +1510,7 @@ lighting Light სინათლე Left in Front მარცხენა წინ No document დოკუმენტი არ არის Open a document to edit its patterns. გახსენით დოკუმენტი მისი პატერნების რედაქტირებისთვის. + Overlap გადაფარვა Overlap: გადაფარვა: Pattern options are available in pattern editing mode. პატერნის პარამეტრები ხელმისაწვდომია პატერნის რედაქტირების რეჟიმში. Right in Front მარჯვენა წინ @@ -1635,6 +1637,7 @@ lighting Light სინათლე Right-Justified Tab მარჯვნივ სწორებული ტაბულაცია Select a text object to set its tab stops. ტაბულაციის გაჩერებების დასაყენებლად მონიშნეთ ტექსტური ობიექტი. Select text მონიშნეთ ტექსტი + Snap to Unit ერთეულზე მიბმა + Add Scale + მასშტაბის დამატება Add Selected Artwork as One Asset მონიშნული ნახატის დამატება ერთ რესურსად Export Settings ექსპორტის პარამეტრები @@ -1877,6 +1880,7 @@ lighting Light სინათლე One file per artboard: -.{ext} ერთი ფაილი თითო სამუშაო დაფაზე: -.{ext} One page per artboard. ერთი გვერდი თითო სამუშაო დაფაზე. The bounds of the visible art. ხილული ნახატის საზღვრები. + The plug-in writes the whole document. პლაგინი მთელ დოკუმენტს ჩაწერს. Use Artboards სამუშაო დაფების გამოყენება Choose a folder საქაღალდის არჩევა Create Sub-folders ქვესაქაღალდეების შექმნა @@ -1978,6 +1982,7 @@ lighting Light სინათლე Layers Panel Options შრეების პანელის პარამეტრები Row Size: სტრიქონის ზომა: Show Layers Only მხოლოდ შრეების ჩვენება + Locate Selected Objects მონიშნული ობიექტების მოძებნა Thumbnails: ესკიზები: Anchor Points საყრდენი წერტილები Brush Affects: ფუნჯი მოქმედებს: @@ -4012,6 +4017,7 @@ effect Regular ჩვეულებრივი @msg {_1} files can be opened but not written (see document.formats) {_1} ფაილების გახსნა შესაძლებელია, ჩაწერა — არა (იხ. document.formats) @msg {_1} font families available ხელმისაწვდომი შრიფტების ოჯახები: {_1} @msg {_1} is a live effect (Effect › Plug-ins) {_1} ცოცხალი ეფექტია (ეფექტი › პლაგინები) +@msg {_1} is an exporter (File › Export › Export As…) {_1} ექსპორტის პლაგინია (ფაილი › ექსპორტირება › ექსპორტირება ფორმატში…) @msg {_1} is already used by {_2} {_1} უკვე გამოიყენება აქ: {_2} @msg {_1} linked file(s) can't be read here: their previews show მიბმული ფაილების წაკითხვა აქ ვერ ხერხდება ({_1}): ჩანს მათი გადახედვა @msg {_1} linked image(s) changed on disk: Update Links shows the new versions მიბმული გამოსახულებები შეიცვალა დისკზე ({_1}): ბმულების განახლება აჩვენებს ახალ ვერსიებს @@ -4757,6 +4763,7 @@ imageTrace Outline კონტური @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer ფაილის შრეები ვერ წაიკითხა ({_1}): ის გაიხსნება როგორც მისი გვერდი, ერთ შრეში @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part ფაილის შრეები რედაქტირების მონაცემებიდან ვერ წაიკითხა ({_1}): ისინი მისი PDF ნაწილიდან აიღება @msg the Color Picker is not open ფერის ამრჩევი გახსნილი არ არის +@msg the Simplify slider is not open გამარტივების სლაიდერი გახსნილი არ არის @msg the screen color sampler is already open ეკრანიდან ფერის აღება უკვე გახსნილია @msg this system has no screen color sampler ამ სისტემას ეკრანიდან ფერის აღების საშუალება არ აქვს # Dimension tool and Object › Dimensions. A drafting dimension is ზომა (ზომის დასმა), like a dimension on a technical drawing. @@ -4831,6 +4838,7 @@ imageTrace Outline კონტური Intertwine გადახლართვა Arrange Intertwine Area გადახლართვის არის დალაგება @msg select an Intertwine group მონიშნეთ გადახლართვის ჯგუფი +@msg select an Objects on Path group მონიშნეთ ტრაექტორიაზე ობიექტების ჯგუფი Registration: საბაზისო წერტილი: @msg span must be "object" or "selection", got {v} span უნდა იყოს "object" ან "selection", მიღებულია {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" ათავსებს `gradient`-ს და არა ფერის ნიმუშს @@ -4851,6 +4859,7 @@ imageTrace Outline კონტური @msg choose a destination folder აირჩიეთ დანიშნულების საქაღალდე @msg choose a source folder აირჩიეთ წყარო საქაღალდე @msg open a document with data sets გახსენით დოკუმენტი მონაცემთა ნაკრებებით +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for მონაცემთა ნაკრები {name}: არაფერი გამოყენებულა; არცერთი ობიექტი არ არის მიბმული ცვლადზე, რომელსაც მასში მნიშვნელობა აქვს @msg the action has no steps მოქმედებას ნაბიჯები არ აქვს Convert to Straight Lines სწორ ხაზებად გარდაქმნა Corner Point Angle Threshold: კუთხოვანი წერტილის კუთხის ზღვარი: @@ -4898,6 +4907,8 @@ imageTrace Outline კონტური Rotate View to Selection ხედის შემობრუნება მონიშნულის მიხედვით Update Selection მონიშნულის განახლება Show Original Path საწყისი ტრაექტორიის ჩვენება + Open this dialog with these settings next time შემდეგ ჯერზე ამ დიალოგის ამ პარამეტრებით გახსნა + Auto-Simplify ავტომატური გამარტივება Texture Image ტექსტურის გამოსახულება @msg check a layer to export მონიშნეთ საექსპორტო შრე @msg select the art to export first ჯერ მონიშნეთ საექსპორტო ნახატი @@ -5015,6 +5026,12 @@ imageTrace Outline კონტური Release Blend გადასვლის მოხსნა Release Envelope გარსის მოხსნა Release Intertwine გადახლართვის მოხსნა + Objects on Path ობიექტები ტრაექტორიაზე + Attach მიმაგრება + Objects on Path Options ტრაექტორიაზე ობიექტების პარამეტრები + Objects on Path Tool ტრაექტორიაზე ობიექტების ხელსაწყო + Attach Objects on Path ობიექტების ტრაექტორიაზე მიმაგრება + Expand Objects on Path ტრაექტორიაზე ობიექტების გაშლა Release Live Paint ცოცხალი შეღებვის მოხსნა Release Repeat გამეორების მოხსნა Release Slice ნაჭრის მოხსნა @@ -5035,6 +5052,8 @@ imageTrace Outline კონტური Resize Type Area ტექსტის არის ზომის შეცვლა Scale Design დიზაინის მასშტაბირება Scale in Perspective პერსპექტივაში მასშტაბირება + Select Fills შევსებების მონიშვნა + Select Strokes კონტურების მონიშვნა Set History Limit… ისტორიის ლიმიტის დაყენება… Shape Builder Delete ფიგურების კონსტრუქტორით წაშლა Sliding სრიალა @@ -5124,3 +5143,43 @@ imageTrace Outline კონტური # Select by Color (select.color) Select by Color მონიშვნა ფერის მიხედვით @msg thumbnail: no page {n} (the file has 1) thumbnail: გვერდი {n} არ არსებობს (ფაილს 1 გვერდი აქვს) + Smudge Stick… დასაზელი ჯოხი… + Smudge Stick დასაზელი ჯოხი + Sponge… ღრუბელი… + Sponge ღრუბელი + Watercolor… აკვარელი… + Watercolor აკვარელი + Brush Size ფუნჯის ზომა + Definition განსაზღვრულობა + Brush Detail ფუნჯის დეტალი + Shadow Intensity ჩრდილის ინტენსივობა + Bas Relief… დაბალი რელიეფი… + Bas Relief დაბალი რელიეფი + Charcoal… ნახშირი… + Charcoal ნახშირი + Photocopy… ფოტოასლი… + Photocopy ფოტოასლი + Stamp… ბეჭედი… + Stamp ბეჭედი + Thickness სისქე + Detail დეტალი + Light/Dark Balance ნათელი/მუქი ბალანსი + Move Anchor Point საყრდენი წერტილის გადაადგილება + Alt key toggles to Smooth Tool Alt კლავიში ჩართავს გაგლუვების ხელსაწყოს +@msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} ინახავს დოკუმენტის {n} სამუშაო დაფიდან 1-ს: ფაილი ხელახლა ერთით გაიხსნება. ყველას შესანარჩუნებლად ჩართეთ „რედაქტირების შესაძლებლობების შენარჩუნება“. + Chalk & Charcoal… ცარცი და ნახშირი… + Chalk & Charcoal ცარცი და ნახშირი + Graphic Pen… გრაფიკული კალამი… + Graphic Pen გრაფიკული კალამი + Reticulation… რეტიკულაცია… + Reticulation რეტიკულაცია + Plastic Wrap… პლასტიკური აფსკი… + Plastic Wrap პლასტიკური აფსკი + Chrome… ქრომი… + Chrome ქრომი + Drop here to take it out of its group ჯგუფიდან ამოსაღებად ჩააგდეთ აქ + Move Library Group ბიბლიოთეკის ჯგუფის გადატანა + Plaster… თაბაშირი… + Plaster თაბაშირი + Note Paper… ჩანაწერების ქაღალდი… + Note Paper ჩანაწერების ქაღალდი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 5df5f55758..23d9803199 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -258,6 +258,8 @@ Large Gaps 큰 간격 Gap Preview Color: 간격 미리 보기 색상: Close Gaps With Paths 패스로 간격 닫기 + Select Fills 칠 선택 + Select Strokes 선 선택 Image Trace 이미지 추적 Image Tracing 이미지 추적 Tracing Presets 추적 프리셋 @@ -283,6 +285,7 @@ Plug-ins 플러그인 No filter plug-ins installed 설치된 필터 플러그인 없음 Install Plug-in… 플러그인 설치… + Open this setting's help page 이 설정의 도움말 페이지 열기 Reload Plug-ins 플러그인 다시 불러오기 Type 문자 Font 글꼴 @@ -1473,6 +1476,7 @@ Fill Rule 칠 규칙 Fill and Stroke 칠과 선 Fill new strokes 새 선 칠하기 + Alt key toggles to Smooth Tool Alt 키로 매끄럽게 도구로 전환 Keep selected 선택 유지 Merge only with selection 선택 영역과만 병합 Fill: 칠: @@ -1655,6 +1659,12 @@ Release Envelope 엔벨로프 해제 Release Image Trace 이미지 추적 해제 Release Intertwine 교차 해제 + Objects on Path 패스 위 개체 + Attach 부착 + Objects on Path Options 패스 위 개체 옵션 + Objects on Path Tool 패스 위 개체 도구 + Attach Objects on Path 패스 위 개체 부착 + Expand Objects on Path 패스 위 개체 확장 Release Live Paint 라이브 페인트 해제 Release Repeat 반복 해제 Release Slice 분할 해제 @@ -1906,6 +1916,7 @@ Load Text into Clipboard 텍스트를 클립보드로 불러오기 Local Libraries 로컬 라이브러리 Locate Object 개체 찾기 + Locate Selected Objects 선택한 개체 찾기 Location 위치 Location: 위치: Lock (⌘2) 잠금 (⌘2) @@ -2230,6 +2241,7 @@ Output condition: 출력 조건: Output intent profile: 출력 의도 프로파일: Output: 출력: + Overlap 겹침 Overlap: 겹침: Overlapping 겹침 Overlay 오버레이 @@ -2750,6 +2762,8 @@ mark-style Japanese 일본식 Show Note 메모 표시 Show Options 옵션 표시 Show Original Path 원래 패스 표시 + Open this dialog with these settings next time 다음에 이 설정으로 이 대화상자 열기 + Auto-Simplify 자동 단순화 Color Panel Options 색상 패널 옵션 Show Package 패키지 표시 Show Panel 패널 표시 @@ -2815,6 +2829,7 @@ mark-style Japanese 일본식 Source Image 원본 이미지 Image Trace View 이미지 추적 보기 Snap Options 스냅 옵션 + Snap to Unit 단위에 스냅 Snapping Tolerance 스냅 허용 오차 Soft Light 소프트 라이트 Solid 단색 @@ -2897,7 +2912,7 @@ mark-style Japanese 일본식 Delete Library Item 라이브러리 항목 삭제 No results 결과 없음 No items in this library match “{query}”. 이 라이브러리에 “{query}”와(과) 일치하는 항목이 없습니다. - Right-click an item to move it into this group. 항목을 마우스 오른쪽 버튼으로 클릭해 이 그룹으로 이동하세요. + Drag an item here, or right-click one, to put it in this group. 항목을 여기로 끌어 놓거나 마우스 오른쪽 버튼으로 클릭해 이 그룹에 넣으세요. New Group 새 그룹 New Group… 새 그룹… Move to Group 그룹으로 이동 @@ -2940,6 +2955,7 @@ mark-style Japanese 일본식 Text Import Options 텍스트 가져오기 옵션 The Print Tiling tool placed the pages. 인쇄 타일링 도구가 페이지를 배치했습니다. The bounds of the visible art. 보이는 아트워크의 경계입니다. + The plug-in writes the whole document. 플러그인이 문서 전체를 내보냅니다. The cell shows the type object's text as HTML. 셀에 문자 개체의 텍스트가 HTML로 표시됩니다. The document has no colour swatches. 문서에 색상 견본이 없습니다. The edge of the paper the printer can't reach: the art goes inside it, and the preview shows it dashed. 프린터가 닿지 않는 용지 가장자리입니다. 아트워크는 이 안쪽에 놓이며, 미리 보기에는 점선으로 표시됩니다. @@ -3951,6 +3967,7 @@ theme Appearance 외관 @msg pattern missing 패턴이 없습니다 @msg select a repeat 반복을 선택하세요 @msg select an Intertwine group 교차 그룹을 선택하세요 +@msg select an Objects on Path group 패스 위 개체 그룹을 선택하세요 @msg select the art to repeat 반복할 아트웍을 선택하세요 @msg the document has no patterns 문서에 패턴이 없습니다 @msg no artboard 아트보드가 없습니다 @@ -4145,6 +4162,7 @@ theme Appearance 외관 @msg no blend options 혼합 옵션이 없습니다 @msg bad color {v} 잘못된 색상 {v} @msg the Color Picker is not open 색상 피커가 열려 있지 않습니다 +@msg the Simplify slider is not open 단순화 슬라이더가 열려 있지 않습니다 @msg the screen color sampler is already open 화면 색상 추출기가 이미 열려 있습니다 @msg this system has no screen color sampler 이 시스템에는 화면 색상 추출기가 없습니다 @msg Corners edits the corners of a path 모퉁이는 패스의 모퉁이를 편집합니다 @@ -4187,6 +4205,7 @@ theme Appearance 외관 @msg missing `id` (see plugin.list) `id`가 없습니다(plugin.list 참조) @msg no plug-in {id} is installed 플러그인 {id}이(가) 설치되어 있지 않습니다 @msg {_1} is a live effect (Effect › Plug-ins) {_1}은(는) 라이브 효과입니다(효과 › 플러그인) +@msg {_1} is an exporter (File › Export › Export As…) {_1}은(는) 내보내기 플러그인입니다(파일 › 내보내기 › 다른 이름으로 내보내기…) @msg a preset named `{_1}` exists `{_1}`이라는 프리셋이 이미 있습니다 @msg a swatch or color group named `{n}` exists `{n}`이라는 견본 또는 색상 그룹이 이미 있습니다 @msg no print preset named `{base}` `{base}`라는 인쇄 프리셋이 없습니다 @@ -4732,6 +4751,7 @@ lighting Light 광원 @msg choose a destination folder 대상 폴더를 선택하세요 @msg choose a source folder 소스 폴더를 선택하세요 @msg open a document with data sets 데이터 세트가 있는 문서를 여세요 +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for 데이터 세트 {name}에서 적용된 항목이 없습니다: 값이 있는 변수에 연결된 개체가 없습니다 @msg the action has no steps 액션에 단계가 없습니다 # User Interface › Accent Color @@ -4754,6 +4774,27 @@ lighting Light 광원 Movie Clip 무비 클립 @msg name is empty 이름이 비어 있습니다 @msg no symbol named `{n}` 이름이 `{n}`인 심볼이 없습니다 + Smudge Stick… 문지르기 막대… + Smudge Stick 문지르기 막대 + Sponge… 스펀지… + Sponge 스펀지 + Watercolor… 수채화… + Watercolor 수채화 + Brush Size 브러시 크기 + Definition 선명도 + Brush Detail 브러시 세부 묘사 + Shadow Intensity 그림자 강도 + Bas Relief… 부조… + Bas Relief 부조 + Charcoal… 목탄… + Charcoal 목탄 + Photocopy… 복사… + Photocopy 복사 + Stamp… 스탬프… + Stamp 스탬프 + Thickness 두께 + Detail 세부 + Light/Dark Balance 밝음/어두움 균형 # Links and Attributes: files and URLs handed to other apps. @msg Edit Original opens image and document files only; “{name}” is not one 원본 편집은 이미지 및 문서 파일만 엽니다. “{name}”은(는) 해당하지 않습니다 @msg only http, https and mailto URLs open in the browser, not “{url}” 브라우저에서는 http, https, mailto URL만 열립니다. “{url}”은(는) 열 수 없습니다 @@ -4794,3 +4835,21 @@ lighting Light 광원 @msg the file's variables and data sets weren't read (variables: {variables}, data sets: {data_sets}): the Variables panel doesn't list them 파일의 변수와 데이터 세트를 읽지 않았습니다(변수: {variables}, 데이터 세트: {data_sets}). 변수 패널에 표시되지 않습니다 # Select by Color (select.color) Select by Color 색상별 선택 + Move Anchor Point 앵커 포인트 이동 +@msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label}은(는) 문서의 아트보드 {n}개 중 1개만 유지하며 파일은 아트보드 하나로 다시 열립니다. 모두 유지하려면 편집 기능 보존을 켜십시오. + Chalk & Charcoal… 분필과 목탄… + Chalk & Charcoal 분필과 목탄 + Graphic Pen… 그래픽 펜… + Graphic Pen 그래픽 펜 + Reticulation… 망사 효과… + Reticulation 망사 효과 + Plastic Wrap… 비닐 랩… + Plastic Wrap 비닐 랩 + Chrome… 크롬… + Chrome 크롬 + Drop here to take it out of its group 그룹에서 빼려면 여기에 놓으세요 + Move Library Group 라이브러리 그룹 이동 + Plaster… 석고… + Plaster 석고 + Note Paper… 메모지… + Note Paper 메모지 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 62ad89dfc9..ae5956f35b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -283,6 +283,7 @@ Plug-ins Plug-ins No filter plug-ins installed Geen filterplug-ins geïnstalleerd Install Plug-in… Plug-in installeren… + Open this setting's help page Helppagina van deze instelling openen Reload Plug-ins Plug-ins opnieuw laden Type Type Font Lettertype @@ -1503,7 +1504,7 @@ lighting Light Licht This library is empty Deze bibliotheek is leeg No results Geen resultaten No items in this library match “{query}”. Geen items in deze bibliotheek komen overeen met „{query}”. - Right-click an item to move it into this group. Klik met de rechtermuisknop op een item om het naar deze groep te verplaatsen. + Drag an item here, or right-click one, to put it in this group. Sleep een item hierheen, of klik er met de rechtermuisknop op, om het in deze groep te zetten. New Group Nieuwe groep New Group… Nieuwe groep… Move to Group Verplaatsen naar groep @@ -1621,6 +1622,7 @@ lighting Light Licht Left in Front Linkerkant vooraan No document Geen document Open a document to edit its patterns. Open een document om de patronen te bewerken. + Overlap Overlap Overlap: Overlap: Pattern options are available in pattern editing mode. Patroonopties zijn beschikbaar in de patroonbewerkingsmodus. Right in Front Rechterkant vooraan @@ -1748,6 +1750,7 @@ lighting Light Licht Right-Justified Tab Rechts uitgelijnde tabstop Select a text object to set its tab stops. Selecteer een tekstobject om de tabstops in te stellen. Select text Selecteer tekst + Snap to Unit Uitlijnen op eenheid + Add Scale + Schaal toevoegen Add Selected Artwork as One Asset Geselecteerde artwork als één asset toevoegen Export Settings Exportinstellingen @@ -1992,6 +1995,7 @@ lighting Light Licht One file per artboard: -.{ext} Eén bestand per tekenbord: -.{ext} One page per artboard. Eén pagina per tekenbord. The bounds of the visible art. De grenzen van de zichtbare artwork. + The plug-in writes the whole document. De plug-in exporteert het hele document. Use Artboards Tekenborden gebruiken Choose a folder Kies een map Create Sub-folders Submappen maken @@ -2077,6 +2081,7 @@ lighting Light Licht Edit selected paths within: Geselecteerde paden bewerken binnen: Fidelity: Nauwkeurigheid: Fill new strokes Nieuwe lijnen vullen + Alt key toggles to Smooth Tool Alt-toets schakelt over naar Gladmaken-gereedschap The document has no colour swatches. Het document heeft geen kleurstalen. Style Name: Stijlnaam: Crop To Bijsnijden tot @@ -2094,6 +2099,7 @@ lighting Light Licht Layers Panel Options Opties voor het paneel Lagen Row Size: Rijgrootte: Show Layers Only Alleen lagen weergeven + Locate Selected Objects Geselecteerde objecten lokaliseren Thumbnails: Miniaturen: Anchor Points Ankerpunten Brush Affects: Penseel beïnvloedt: @@ -5061,6 +5067,8 @@ swatch Bright Violet Felviolet Outline Object Object omtrekken Update Selection Selectie bijwerken Show Original Path Oorspronkelijk pad tonen + Open this dialog with these settings next time Dit dialoogvenster de volgende keer met deze instellingen openen + Auto-Simplify Automatisch vereenvoudigen @msg check a layer to export vink een laag aan om te exporteren @msg select the art to export first selecteer eerst de illustratie die je wilt exporteren @msg no saved selection recalled geen opgeslagen selectie opgeroepen @@ -5086,6 +5094,8 @@ swatch Bright Violet Felviolet Chop Design Ontwerp afknippen Clear Events Gebeurtenissen wissen Close Gaps With Paths Openingen sluiten met paden + Select Fills Vullingen selecteren + Select Strokes Lijnen selecteren Column Type: Kolomtype: Each Design Represents: Elk ontwerp staat voor: Event: Gebeurtenis: @@ -5163,6 +5173,12 @@ swatch Bright Violet Felviolet Release Blend Vermenging vrijgeven Release Envelope Omvorming vrijgeven Release Intertwine Verstrengeling vrijgeven + Objects on Path Objecten op pad + Attach Koppelen + Objects on Path Options Opties voor objecten op pad + Objects on Path Tool Objecten-op-pad-gereedschap + Attach Objects on Path Objecten aan pad koppelen + Expand Objects on Path Objecten op pad uitbreiden Release Live Paint Live Paint vrijgeven Release Repeat Herhaling vrijgeven Release Slice Slice vrijgeven @@ -5239,3 +5255,41 @@ swatch Bright Violet Felviolet Justification Uitvullen # Select by Color (select.color) Select by Color Selecteren op kleur + Smudge Stick… Uitsmeerstift… + Smudge Stick Uitsmeerstift + Sponge… Spons… + Sponge Spons + Watercolor… Aquarel… + Watercolor Aquarel + Brush Size Penseelgrootte + Definition Definitie + Brush Detail Penseeldetail + Shadow Intensity Schaduwintensiteit + Bas Relief… Basreliëf… + Bas Relief Basreliëf + Charcoal… Houtskool… + Charcoal Houtskool + Photocopy… Fotokopie… + Photocopy Fotokopie + Stamp… Stempel… + Stamp Stempel + Thickness Dikte + Detail Detail + Light/Dark Balance Licht/donker-balans + Move Anchor Point Ankerpunt verplaatsen + Chalk & Charcoal… Krijt en houtskool… + Chalk & Charcoal Krijt en houtskool + Graphic Pen… Grafische pen… + Graphic Pen Grafische pen + Reticulation… Reticulatie… + Reticulation Reticulatie + Plastic Wrap… Plasticfolie… + Plastic Wrap Plasticfolie + Chrome… Chroom… + Chrome Chroom + Drop here to take it out of its group Zet het hier neer om het uit de groep te halen + Move Library Group Bibliotheekgroep verplaatsen + Plaster… Gips… + Plaster Gips + Note Paper… Notitiepapier… + Note Paper Notitiepapier diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 1d5616455a..34514c6263 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -229,6 +229,8 @@ Large Gaps Duże przerwy Gap Preview Color: Kolor podglądu przerw: Close Gaps With Paths Zamknij przerwy ścieżkami + Select Fills Zaznaczaj wypełnienia + Select Strokes Zaznaczaj obrysy Image Trace Obrys obrazu Text Wrap Oblewanie tekstem Text Wrap Options… Opcje oblewania tekstem… @@ -264,6 +266,7 @@ Plug-ins Wtyczki No filter plug-ins installed Brak zainstalowanych wtyczek filtrów Install Plug-in… Zainstaluj wtyczkę… + Open this setting's help page Otwórz stronę pomocy dla tego ustawienia Reload Plug-ins Wczytaj ponownie wtyczki Type Tekst Font Czcionka @@ -1484,6 +1487,12 @@ lighting Light Światło Release Envelope Uwolnij kopertę Release Image Trace Uwolnij obrys obrazu Release Intertwine Uwolnij przeplatanie + Objects on Path Obiekty na ścieżce + Attach Dołącz + Objects on Path Options Opcje obiektów na ścieżce + Objects on Path Tool Narzędzie Obiekty na ścieżce + Attach Objects on Path Dołącz obiekty do ścieżki + Expand Objects on Path Rozszerz obiekty na ścieżce Release Live Paint Uwolnij aktywne malowanie Release Repeat Uwolnij powtórzenie Release Slice Uwolnij plasterek @@ -1569,7 +1578,7 @@ lighting Light Światło This library is empty Ta biblioteka jest pusta No results Brak wyników No items in this library match “{query}”. Żaden element tej biblioteki nie pasuje do „{query}”. - Right-click an item to move it into this group. Kliknij element prawym przyciskiem, aby przenieść go do tej grupy. + Drag an item here, or right-click one, to put it in this group. Przeciągnij tu element albo kliknij go prawym przyciskiem, aby umieścić go w tej grupie. New Group Nowa grupa New Group… Nowa grupa… Move to Group Przenieś do grupy @@ -1624,6 +1633,8 @@ lighting Light Światło Corner Point Angle Threshold: Próg kąta punktów narożnych: Convert to Straight Lines Konwertuj na linie proste Show Original Path Pokaż oryginalną ścieżkę + Open this dialog with these settings next time Następnym razem otwórz to okno dialogowe z tymi ustawieniami + Auto-Simplify Uprość automatycznie Transparency Options Opcje przezroczystości Color Mixer (Shift-click the chip) Mikser kolorów (kliknij próbkę z Shift) Fill: click for swatches, Shift-click for the color mixer Wypełnienie: kliknij, aby wybrać próbkę, z Shift — mikser kolorów @@ -1698,6 +1709,7 @@ lighting Light Światło Left in Front Lewy na wierzchu No document Brak dokumentu Open a document to edit its patterns. Otwórz dokument, aby edytować jego wzorki. + Overlap Nakładanie Overlap: Nakładanie: Pattern options are available in pattern editing mode. Opcje wzorka są dostępne w trybie edycji wzorka. Right in Front Prawy na wierzchu @@ -1824,6 +1836,7 @@ lighting Light Światło Right-Justified Tab Tabulator prawy Select a text object to set its tab stops. Zaznacz obiekt tekstowy, aby ustawić jego tabulatory. Select text Zaznacz tekst + Snap to Unit Przyciągaj do jednostek + Add Scale + Dodaj skalę Add Selected Artwork as One Asset Dodaj zaznaczoną kompozycję jako jeden zasób Export Settings Ustawienia eksportu @@ -2071,6 +2084,7 @@ lighting Light Światło One file per artboard: -.{ext} Jeden plik na obszar kompozycji: -.{ext} One page per artboard. Jedna strona na obszar kompozycji. The bounds of the visible art. Granice widocznej kompozycji. + The plug-in writes the whole document. Wtyczka eksportuje cały dokument. Use Artboards Użyj obszarów kompozycji Choose a folder Wybierz folder Create Sub-folders Utwórz podfoldery @@ -2156,6 +2170,7 @@ lighting Light Światło Edit selected paths within: Edytuj zaznaczone ścieżki w odległości: Fidelity: Wierność: Fill new strokes Wypełniaj nowe pociągnięcia + Alt key toggles to Smooth Tool Klawisz Alt przełącza na narzędzie Wygładzanie Keep selected Zachowaj zaznaczenie Merge only with selection Scalaj tylko z zaznaczeniem The document has no colour swatches. Dokument nie zawiera próbek kolorów. @@ -2174,6 +2189,7 @@ lighting Light Światło Layers Panel Options Opcje panelu Warstwy Row Size: Rozmiar wiersza: Show Layers Only Pokaż tylko warstwy + Locate Selected Objects Znajdź zaznaczone obiekty Thumbnails: Miniatury: Anchor Points Punkty kontrolne Brush Affects: Pędzel wpływa na: @@ -3984,6 +4000,7 @@ imageTrace Outline Kontur @msg background {other}: transparent, white, black or a colour such as "#ff8800" tło {other}: transparent, white, black lub kolor, np. "#ff8800" @msg bad color {v} nieprawidłowy kolor {v} @msg the Color Picker is not open Próbnik kolorów nie jest otwarty +@msg the Simplify slider is not open Suwak Uprość nie jest otwarty @msg the screen color sampler is already open narzędzie do pobierania koloru z ekranu jest już otwarte @msg this system has no screen color sampler ten system nie ma narzędzia do pobierania koloru z ekranu @msg bad colour `{hex}` (#rrggbb) nieprawidłowy kolor `{hex}` (#rrggbb) @@ -4222,6 +4239,7 @@ imageTrace Outline Kontur @msg select a linked image: an embedded one has no file zaznacz obraz połączony: osadzony nie ma pliku @msg select a repeat zaznacz powtórzenie @msg select an Intertwine group zaznacz grupę przeplotu +@msg select an Objects on Path group zaznacz grupę obiektów na ścieżce @msg select a stroke with a variable width zaznacz obrys o zmiennej szerokości @msg select a symbol instance zaznacz wystąpienie symbolu @msg select an Image Trace object zaznacz obiekt obrysu obrazu @@ -4352,6 +4370,7 @@ imageTrace Outline Kontur @msg {_1} files are written by file.saveAsTemplate pliki {_1} zapisuje file.saveAsTemplate @msg {_1} font families available dostępne rodziny czcionek: {_1} @msg {_1} is a live effect (Effect › Plug-ins) {_1} to efekt na żywo (Efekt › Wtyczki) +@msg {_1} is an exporter (File › Export › Export As…) {_1} to wtyczka eksportu (Plik › Eksportuj › Eksportuj jako…) @msg {_1} is already used by {_2} {_1} jest już używany przez {_2} @msg {_1} linked file(s) can't be read here: their previews show połączonych plików nie można tu odczytać ({_1}): wyświetlane są ich podglądy @msg {_1} linked image(s) changed on disk: Update Links shows the new versions połączone obrazy zmienione na dysku: {_1} — Aktualizuj łącza pokaże nowe wersje @@ -5008,6 +5027,7 @@ mark-style Japanese Japońskie @msg choose a destination folder wybierz folder docelowy @msg choose a source folder wybierz folder źródłowy @msg open a document with data sets otwórz dokument z zestawami danych +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for z zestawu danych {name} nic nie zastosowano: żaden obiekt nie jest powiązany ze zmienną, dla której ma on wartość @msg the action has no steps operacja nie ma kroków # User Interface › Accent Color @@ -5030,6 +5050,27 @@ mark-style Japanese Japońskie Movie Clip Klip filmowy @msg name is empty nazwa jest pusta @msg no symbol named `{n}` brak symbolu o nazwie `{n}` + Smudge Stick… Rozmazywacz… + Smudge Stick Rozmazywacz + Sponge… Gąbka… + Sponge Gąbka + Watercolor… Akwarela… + Watercolor Akwarela + Brush Size Rozmiar pędzla + Definition Wyrazistość + Brush Detail Szczegółowość pędzla + Shadow Intensity Intensywność cieni + Bas Relief… Płaskorzeźba… + Bas Relief Płaskorzeźba + Charcoal… Węgiel… + Charcoal Węgiel + Photocopy… Fotokopia… + Photocopy Fotokopia + Stamp… Stempel… + Stamp Stempel + Thickness Grubość + Detail Szczegóły + Light/Dark Balance Równowaga jasne/ciemne # Links and Attributes: files and URLs handed to other apps. @msg Edit Original opens image and document files only; “{name}” is not one Edytuj oryginał otwiera tylko pliki obrazów i dokumentów; „{name}” do nich nie należy @msg only http, https and mailto URLs open in the browser, not “{url}” w przeglądarce otwierają się tylko adresy URL http, https i mailto, a nie „{url}” @@ -5069,3 +5110,21 @@ mark-style Japanese Japońskie @msg the file's variables and data sets weren't read (variables: {variables}, data sets: {data_sets}): the Variables panel doesn't list them zmienne i zestawy danych pliku nie zostały wczytane (zmienne: {variables}, zestawy danych: {data_sets}): panel Zmienne ich nie wyświetla # Select by Color (select.color) Select by Color Zaznacz według koloru + Move Anchor Point Przesuń punkt kontrolny +@msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} zachowuje 1 z {n} obszarów kompozycji dokumentu: plik otworzy się ponownie z jednym. Włącz Zachowaj możliwości edycji, aby zachować wszystkie. + Chalk & Charcoal… Kreda i węgiel… + Chalk & Charcoal Kreda i węgiel + Graphic Pen… Pióro graficzne… + Graphic Pen Pióro graficzne + Reticulation… Siateczkowanie… + Reticulation Siateczkowanie + Plastic Wrap… Folia plastikowa… + Plastic Wrap Folia plastikowa + Chrome… Chrom… + Chrome Chrom + Drop here to take it out of its group Upuść tutaj, aby wyjąć go z grupy + Move Library Group Przenieś grupę biblioteki + Plaster… Gips… + Plaster Gips + Note Paper… Papier listowy… + Note Paper Papier listowy diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index eba0db01c6..59eadcf4b5 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -963,6 +963,7 @@ Fill Rule Regra de Preenchimento Fill and Stroke Preenchimento e Traçado Fill new strokes Preencher novos traçados + Alt key toggles to Smooth Tool A tecla Alt alterna para a ferramenta Suavizar Keep selected Manter selecionado Merge only with selection Mesclar somente com a seleção Fill with Placeholder Text Preencher com Texto de Placeholder @@ -1056,6 +1057,8 @@ Large Gaps Lacunas Grandes Gap Preview Color: Cor de Visualização das Lacunas: Close Gaps With Paths Fechar Lacunas com Caminhos + Select Fills Selecionar Preenchimentos + Select Strokes Selecionar Traçados Gaussian Blur… Desfoque Gaussiano… General Geral Generate CSS Gerar CSS @@ -1210,6 +1213,12 @@ Release Blend Liberar Mesclagem Release Envelope Liberar Envelope Release Intertwine Liberar Entrelaçamento + Objects on Path Objetos no Caminho + Attach Anexar + Objects on Path Options Opções de Objetos no Caminho + Objects on Path Tool Ferramenta Objetos no Caminho + Attach Objects on Path Anexar Objetos ao Caminho + Expand Objects on Path Expandir Objetos no Caminho Release Live Paint Liberar Pintura ao Vivo Release Repeat Liberar Repetição Release Slice Liberar Fatia @@ -1306,6 +1315,7 @@ Inspect Object Inspecionar Objeto Install Plug-in Instalar Plug-in Install Plug-in… Instalar Plug-in… + Open this setting's help page Abrir a página de ajuda desta configuração Intensity: Intensidade: Intent: Intenção: Interface Language Idioma da Interface @@ -1761,6 +1771,7 @@ Output condition: Condição de saída: Output intent profile: Perfil de intenção de saída: Output: Saída: + Overlap Sobreposição Overlap: Sobreposição: Overlapping Sobreposto Overlay Sobrepor @@ -2421,6 +2432,8 @@ Show Note Mostrar Nota Show Options Mostrar Opções Show Original Path Mostrar Caminho Original + Open this dialog with these settings next time Abrir este diálogo com estas configurações na próxima vez + Auto-Simplify Simplificar Automaticamente Show Package Mostrar Pacote Show Panel Mostrar Painel Show Perspective Grid Mostrar Grade de Perspectiva @@ -2501,6 +2514,7 @@ Snap to Pixel Ajustar ao Pixel Precise Cursors Cursores Precisos Snap to Point Ajustar ao Ponto + Snap to Unit Ajustar à Unidade Snapping Tolerance Tolerância de Ajuste Soft Light Luz Suave Solid Sólido @@ -2612,6 +2626,7 @@ Text Wrap Options… Opções de Quebra de Texto… The Print Tiling tool placed the pages. A ferramenta Tesselação de Impressão colocou as páginas. The bounds of the visible art. Os limites da arte visível. + The plug-in writes the whole document. O plug-in exporta o documento inteiro. The cell shows the type object's text as HTML. A célula mostra o texto do objeto de tipo como HTML. The document has no colour swatches. O documento não tem amostras de cor. The edge of the paper the printer can't reach: the art goes inside it, and the preview shows it dashed. A borda do papel que a impressora não alcança: a arte fica dentro dela, e a visualização a mostra tracejada. @@ -3114,6 +3129,7 @@ lighting Light Luz Layers Panel Options Opções do painel Camadas Left-to-Right Paragraph Direction Direção do parágrafo da esquerda para a direita Line-end Punctuation Half Width Pontuação de fim de linha em meia largura + Locate Selected Objects Localizar objetos selecionados Lock Others Bloquear outros Merge Selected Mesclar selecionados Model Modelo @@ -3228,7 +3244,7 @@ lighting Light Luz Delete Library Item Excluir item da biblioteca No results Nenhum resultado No items in this library match “{query}”. Nenhum item desta biblioteca corresponde a “{query}”. - Right-click an item to move it into this group. Clique com o botão direito em um item para movê-lo para este grupo. + Drag an item here, or right-click one, to put it in this group. Arraste um item para cá, ou clique com o botão direito em um, para colocá-lo neste grupo. New Group Novo grupo Move to Group Mover para o grupo Import Library Importar biblioteca @@ -3678,6 +3694,7 @@ axis Both Ambos @msg select a linked image: an embedded one has no file selecione uma imagem vinculada: uma incorporada não tem arquivo @msg select a repeat selecione uma repetição @msg select an Intertwine group selecione um grupo entrelaçado +@msg select an Objects on Path group selecione um grupo de objetos no caminho @msg select a stroke with a variable width selecione um traço com largura variável @msg select a symbol instance selecione uma instância de símbolo @msg select an Image Trace object selecione um objeto de Vetorização de imagem @@ -3807,6 +3824,7 @@ axis Both Ambos @msg {_1} files are written by file.saveAsTemplate arquivos {_1} são gravados por file.saveAsTemplate @msg {_1} font families available {_1} famílias de fontes disponíveis @msg {_1} is a live effect (Effect › Plug-ins) {_1} é um efeito dinâmico (Efeito › Plug-ins) +@msg {_1} is an exporter (File › Export › Export As…) {_1} é um plug-in de exportação (Arquivo › Exportar › Exportar Como…) @msg {_1} is already used by {_2} {_1} já é usado por {_2} @msg {_1} linked file(s) can't be read here: their previews show {_1} arquivo(s) vinculado(s) não podem ser lidos aqui: suas visualizações são exibidas @msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} imagem(ns) vinculada(s) mudou(aram) no disco: Atualizar links mostra as novas versões @@ -5035,6 +5053,7 @@ mark-style Japanese Japonesas @msg choose a destination folder escolha uma pasta de destino @msg choose a source folder escolha uma pasta de origem @msg open a document with data sets abra um documento com conjuntos de dados +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for nada do conjunto de dados {name} foi aplicado: nenhum objeto está vinculado a uma variável para a qual ele tem um valor @msg the action has no steps a ação não tem etapas @msg Angles require two straight segments Ângulos exigem dois segmentos retos @msg Choose a circle or a perfect arc Escolha um círculo ou um arco perfeito @@ -5058,6 +5077,7 @@ mark-style Japanese Japonesas @msg Unknown dimension mode Modo de cota desconhecido @msg Unknown dimension option {k} Opção de cota desconhecida {k} @msg the Color Picker is not open o Seletor de Cores não está aberto +@msg the Simplify slider is not open o controle deslizante Simplificar não está aberto @msg the screen color sampler is already open o coletor de cores da tela já está aberto @msg this system has no screen color sampler este sistema não tem coletor de cores da tela Darkness Escuridão @@ -5095,6 +5115,27 @@ mark-style Japanese Japonesas # Symbol Options › Export Type @msg name is empty o nome está vazio @msg no symbol named `{n}` nenhum símbolo chamado `{n}` + Smudge Stick… Esfuminho… + Smudge Stick Esfuminho + Sponge… Esponja… + Sponge Esponja + Watercolor… Aquarela… + Watercolor Aquarela + Brush Size Tamanho do pincel + Definition Definição + Brush Detail Detalhe do pincel + Shadow Intensity Intensidade da sombra + Bas Relief… Baixo-relevo… + Bas Relief Baixo-relevo + Charcoal… Carvão… + Charcoal Carvão + Photocopy… Fotocópia… + Photocopy Fotocópia + Stamp… Carimbo… + Stamp Carimbo + Thickness Espessura + Detail Detalhe + Light/Dark Balance Equilíbrio claro/escuro # Links and Attributes: files and URLs handed to other apps. @msg Edit Original opens image and document files only; “{name}” is not one Editar Original abre apenas arquivos de imagem e de documento; “{name}” não é um deles @msg only http, https and mailto URLs open in the browser, not “{url}” apenas URLs http, https e mailto abrem no navegador, não “{url}” @@ -5134,3 +5175,21 @@ mark-style Japanese Japonesas @msg the file's variables and data sets weren't read (variables: {variables}, data sets: {data_sets}): the Variables panel doesn't list them as variáveis e os conjuntos de dados do arquivo não foram lidos (variáveis: {variables}, conjuntos de dados: {data_sets}): o painel Variáveis não os lista # Select by Color (select.color) Select by Color Selecionar por Cor + Move Anchor Point Mover Ponto de Ancoragem +@msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} mantém 1 das {n} mesas de trabalho do documento: o arquivo reabre com uma. Ative Preservar Capacidades de Edição para manter todas. + Chalk & Charcoal… Giz e carvão… + Chalk & Charcoal Giz e carvão + Graphic Pen… Caneta gráfica… + Graphic Pen Caneta gráfica + Reticulation… Reticulação… + Reticulation Reticulação + Plastic Wrap… Envoltório plástico… + Plastic Wrap Envoltório plástico + Chrome… Cromo… + Chrome Cromo + Drop here to take it out of its group Solte aqui para tirá-lo do grupo + Move Library Group Mover grupo de biblioteca + Plaster… Gesso… + Plaster Gesso + Note Paper… Papel de carta… + Note Paper Papel de carta diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 1772f1195b..c87172a0e0 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1076,6 +1076,7 @@ Fill (X), double-click for the Color Picker Заливка (X), дважды щёлкните для палитры цветов Fill and Stroke Заливка и обводка Fill new strokes Заполнять новые обводки + Alt key toggles to Smooth Tool Клавиша Alt переключает на инструмент «Сглаживание» Keep selected Оставлять выбранным Merge only with selection Объединять только с выделенным Fill Color Цвет заливки @@ -1206,6 +1207,8 @@ file-filter Templates Шаблоны Large Gaps Большие зазоры Gap Preview Color: Цвет просмотра зазоров: Close Gaps With Paths Закрыть зазоры контурами + Select Fills Выделять заливки + Select Strokes Выделять обводки Gaussian Blur… Размытие по Гауссу… General Общие General › Placement › X Общие › Размещение › X @@ -1413,6 +1416,12 @@ file-filter Templates Шаблоны Release Envelope Освободить оболочку Release Image Trace Освободить трассировку изображения Release Intertwine Освободить переплетение + Objects on Path Объекты на контуре + Attach Прикрепить + Objects on Path Options Параметры объектов на контуре + Objects on Path Tool Инструмент «Объекты на контуре» + Attach Objects on Path Прикрепить объекты к контуру + Expand Objects on Path Разобрать объекты на контуре Release Live Paint Освободить быструю заливку Release Repeat Освободить повтор Release Slice Освободить фрагмент @@ -1533,6 +1542,7 @@ file-filter Templates Шаблоны Inspect Object Проверить объект Install Plug-in Установить модуль Install Plug-in… Установить модуль… + Open this setting's help page Открыть страницу справки по этому параметру Installed plug-in {} Установлен модуль {} Intensity: Интенсивность: Intent: Назначение: @@ -1737,6 +1747,7 @@ file-filter Templates Шаблоны Load Text into Clipboard Загрузить текст в буфер обмена Local Libraries Локальные библиотеки Locate Object Найти объект + Locate Selected Objects Находить выделенные объекты Location Расположение Location: Расположение: Lock Заблокировать @@ -2167,6 +2178,7 @@ file-filter Templates Шаблоны Output White Выходной белый Output › Mode Вывод › Режим Output: Вывод: + Overlap Перекрытие Overlap: Перекрытие: Overlapping Перекрывающийся Overlay Перекрытие @@ -2944,6 +2956,8 @@ mark-style Japanese Японский Show Note Показать примечание Show Options Показать параметры Show Original Path Показать исходный контур + Open this dialog with these settings next time Открывать это диалоговое окно с этими параметрами в следующий раз + Auto-Simplify Автоматическое упрощение Color Panel Options Параметры панели «Цвет» Show Package Показать пакет Show Panel Показать панель @@ -3040,6 +3054,7 @@ mark-style Japanese Японский Snap to Pixel Привязать к пикселю Precise Cursors Точные курсоры Snap to Point Привязать к точке + Snap to Unit Привязать к единицам Snapping Tolerance Допуск привязки Social Square Post 1080×1080 Квадратный пост для соцсетей 1080×1080 Soft Light Мягкий свет @@ -3167,7 +3182,7 @@ mark-style Japanese Японский Delete Library Item Удалить элемент библиотеки No results Ничего не найдено No items in this library match “{query}”. В этой библиотеке нет элементов, соответствующих «{query}». - Right-click an item to move it into this group. Щёлкните элемент правой кнопкой мыши, чтобы переместить его в эту группу. + Drag an item here, or right-click one, to put it in this group. Перетащите сюда элемент или щёлкните его правой кнопкой мыши, чтобы поместить его в эту группу. New Group Новая группа New Group… Новая группа… Move to Group Переместить в группу @@ -3227,6 +3242,7 @@ mark-style Japanese Японский Text Wrap Options Параметры обтекания текстом Text Wrap Options… Параметры обтекания текстом… The bounds of the visible art. Границы видимого рисунка. + The plug-in writes the whole document. Модуль экспортирует весь документ. The cell shows the type object's text as HTML. Ячейка показывает текст текстового объекта как HTML. The document has no colour swatches. В документе нет цветовых образцов. The edge of the paper the printer can't reach: the art goes inside it, and the preview shows it dashed. Край бумаги, до которого не доходит принтер: рисунок остаётся внутри него, а просмотр показывает его пунктиром. @@ -3895,6 +3911,7 @@ axis Both Оба @msg background {other}: transparent, white, black or a colour such as "#ff8800" фон {other}: transparent, white, black или цвет, например "#ff8800" @msg bad color {v} недопустимый цвет {v} @msg the Color Picker is not open палитра цветов не открыта +@msg the Simplify slider is not open ползунок «Упростить» не открыт @msg the screen color sampler is already open средство выбора цвета с экрана уже открыто @msg this system has no screen color sampler в этой системе нет средства выбора цвета с экрана @msg bad colour `{hex}` (#rrggbb) недопустимый цвет `{hex}` (#rrggbb) @@ -4132,6 +4149,7 @@ axis Both Оба @msg select a linked image: an embedded one has no file выделите связанное изображение: у внедрённого нет файла @msg select a repeat выделите повтор @msg select an Intertwine group выделите группу переплетения +@msg select an Objects on Path group выделите группу объектов на контуре @msg select a stroke with a variable width выделите обводку с переменной шириной @msg select a symbol instance выделите экземпляр символа @msg select an Image Trace object выделите объект трассировки изображения @@ -4261,6 +4279,7 @@ axis Both Оба @msg {_1} files are written by file.saveAsTemplate файлы {_1} записывает file.saveAsTemplate @msg {_1} font families available доступно семейств шрифтов: {_1} @msg {_1} is a live effect (Effect › Plug-ins) {_1} — динамический эффект (Эффект › Модули) +@msg {_1} is an exporter (File › Export › Export As…) {_1} — модуль экспорта (Файл › Экспорт › Экспортировать как…) @msg {_1} is already used by {_2} {_1} уже используется {_2} @msg {_1} linked file(s) can't be read here: their previews show здесь невозможно прочитать связанных файлов: {_1}: отображаются их предварительные просмотры @msg {_1} linked image(s) changed on disk: Update Links shows the new versions связанных изображений ({_1}) изменились на диске: «Обновить связи» покажет новые версии @@ -4765,6 +4784,7 @@ lighting Light Свет @msg choose a destination folder выберите папку назначения @msg choose a source folder выберите исходную папку @msg open a document with data sets откройте документ с наборами данных +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for из набора данных {name} ничего не применено: ни один объект не привязан к переменной, для которой в нём есть значение @msg the action has no steps в действии нет шагов # User Interface › Accent Color @@ -4787,6 +4807,27 @@ lighting Light Свет Movie Clip Видеоклип @msg name is empty имя пустое @msg no symbol named `{n}` нет символа с именем `{n}` + Smudge Stick… Растушёвка… + Smudge Stick Растушёвка + Sponge… Губка… + Sponge Губка + Watercolor… Акварель… + Watercolor Акварель + Brush Size Размер кисти + Definition Чёткость + Brush Detail Детализация кисти + Shadow Intensity Интенсивность теней + Bas Relief… Барельеф… + Bas Relief Барельеф + Charcoal… Уголь… + Charcoal Уголь + Photocopy… Фотокопия… + Photocopy Фотокопия + Stamp… Штамп… + Stamp Штамп + Thickness Толщина + Detail Детали + Light/Dark Balance Баланс светлого и тёмного # Links and Attributes: files and URLs handed to other apps. @msg Edit Original opens image and document files only; “{name}” is not one «Редактировать оригинал» открывает только файлы изображений и документов; «{name}» к ним не относится @msg only http, https and mailto URLs open in the browser, not “{url}” в браузере открываются только URL с http, https и mailto, а не «{url}» @@ -4827,3 +4868,21 @@ lighting Light Свет @msg the file's variables and data sets weren't read (variables: {variables}, data sets: {data_sets}): the Variables panel doesn't list them переменные и наборы данных файла не прочитаны (переменных: {variables}, наборов данных: {data_sets}): панель «Переменные» их не показывает # Select by Color (select.color) Select by Color Выделить по цвету + Move Anchor Point Переместить опорную точку +@msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} сохраняет 1 из {n} монтажных областей документа: файл откроется снова с одной. Включите «Сохранять возможности редактирования», чтобы сохранить все. + Chalk & Charcoal… Мел и уголь… + Chalk & Charcoal Мел и уголь + Graphic Pen… Графическое перо… + Graphic Pen Графическое перо + Reticulation… Ретикуляция… + Reticulation Ретикуляция + Plastic Wrap… Целлофановая упаковка… + Plastic Wrap Целлофановая упаковка + Chrome… Хром… + Chrome Хром + Drop here to take it out of its group Отпустите здесь, чтобы вынуть его из группы + Move Library Group Переместить группу библиотеки + Plaster… Гипс… + Plaster Гипс + Note Paper… Почтовая бумага… + Note Paper Почтовая бумага diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index fcbc8f273c..353fc461ea 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1060,6 +1060,7 @@ Fill (X), double-click for the Color Picker Fyllning (X), dubbelklicka för färgväljaren Fill and Stroke Fyllning och kontur Fill new strokes Fyll nya konturer + Alt key toggles to Smooth Tool Alt-tangenten växlar till Utjämningsverktyg Fill Color Fyllnadsfärg Fill New Type Objects With Placeholder Text Fyll nya textobjekt med platshållartext Fill Rule Fyllningsregel @@ -1176,6 +1177,8 @@ Large Gaps Stora mellanrum Gap Preview Color: Förhandsgranskningsfärg för mellanrum: Close Gaps With Paths Stäng mellanrum med banor + Select Fills Markera fyllningar + Select Strokes Markera konturer Gaussian Blur… Gaussisk oskärpa… General Allmänt General › Placement › X Allmänt › Placering › X @@ -1372,6 +1375,12 @@ Release Blend Släpp blandning Release Envelope Släpp kuvert Release Intertwine Släpp sammanflätning + Objects on Path Objekt på bana + Attach Fäst + Objects on Path Options Alternativ för objekt på bana + Objects on Path Tool Verktyg för objekt på bana + Attach Objects on Path Fäst objekt på bana + Expand Objects on Path Expandera objekt på bana Release Live Paint Släpp direktmålning Release Repeat Släpp upprepning Release Slice Släpp skiva @@ -1487,6 +1496,7 @@ Inspect Object Inspektera objekt Install Plug-in Installera plugin Install Plug-in… Installera plugin… + Open this setting's help page Öppna hjälpsidan för den här inställningen Installed plug-in {} Installerade plugin {} Intensity: Intensitet: Intent: Återgivningsmetod: @@ -1672,6 +1682,7 @@ Load Text into Clipboard Läs in text till urklipp Local Libraries Lokala bibliotek Locate Object Hitta objekt + Locate Selected Objects Hitta markerade objekt Location Plats Location: Plats: Lock Lås @@ -2102,6 +2113,7 @@ Output White Vitt i utgång Output › Mode Utgång › Läge Output: Utgång: + Overlap Överlappning Overlap: Överlappning: Overlapping Överlappande Overlay Överlägg @@ -2858,6 +2870,8 @@ Show Note Visa anteckning Show Options Visa alternativ Show Original Path Visa ursprunglig bana + Open this dialog with these settings next time Öppna den här dialogrutan med de här inställningarna nästa gång + Auto-Simplify Förenkla automatiskt Show Package Visa paket Show Panel Visa panel Show Pattern Swatches Visa mönsterprover @@ -2952,6 +2966,7 @@ Snap to Pixel Fäst mot pixel Precise Cursors Exakta markörer Snap to Point Fäst mot punkt + Snap to Unit Fäst mot enhet Snapping Tolerance Fästtolerans Social Square Post 1080×1080 Kvadratiskt inlägg för sociala medier 1080×1080 Soft Light Mjukt ljus @@ -3079,7 +3094,7 @@ Delete Library Item Radera biblioteksobjekt No results Inga resultat No items in this library match “{query}”. Inga objekt i det här biblioteket matchar ”{query}”. - Right-click an item to move it into this group. Högerklicka på ett objekt för att flytta det till den här gruppen. + Drag an item here, or right-click one, to put it in this group. Dra hit ett objekt, eller högerklicka på ett, för att lägga det i den här gruppen. New Group Ny grupp New Group… Ny grupp… Move to Group Flytta till grupp @@ -3139,6 +3154,7 @@ Text Wrap Options Alternativ för textombrytning Text Wrap Options… Alternativ för textombrytning… The bounds of the visible art. Gränserna för den synliga grafiken. + The plug-in writes the whole document. Insticksprogrammet exporterar hela dokumentet. The cell shows the type object's text as HTML. Cellen visar textobjektets text som HTML. The document has no colour swatches. Dokumentet har inga färgrutor. The edge of the paper the printer can't reach: the art goes inside it, and the preview shows it dashed. Den kant av papperet som skrivaren inte når: grafiken placeras innanför den, och förhandsgranskningen visar den streckad. @@ -4150,6 +4166,7 @@ axis Both Båda @msg {_1} files are written by file.saveAsTemplate {_1}-filer skrivs av file.saveAsTemplate @msg {_1} font families available {_1} teckensnittsfamiljer tillgängliga @msg {_1} is a live effect (Effect › Plug-ins) {_1} är en live-effekt (Effekt › Insticksprogram) +@msg {_1} is an exporter (File › Export › Export As…) {_1} är ett exportinsticksprogram (Fil › Exportera › Exportera som…) @msg {_1} is already used by {_2} {_1} används redan av {_2} @msg {_1} linked file(s) can't be read here: their previews show {_1} länkade fil(er) kan inte läsas här: deras förhandsgranskningar visas @msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} länkade bild(er) har ändrats på disken: Uppdatera länkar visar de nya versionerna @@ -5100,13 +5117,16 @@ theme Appearance Utseende @msg choose a destination folder välj en målmapp @msg choose a source folder välj en källmapp @msg open a document with data sets öppna ett dokument med datauppsättningar +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for inget i datauppsättningen {name} användes: inget objekt är bundet till en variabel som den har ett värde för @msg select an Intertwine group markera en sammanflätningsgrupp +@msg select an Objects on Path group markera en grupp med objekt på bana @msg span must be "object" or "selection", got {v} span måste vara "object" eller "selection", fick {v} @msg span: "selection" places a `gradient`, not a swatch span: "selection" placerar en `gradient`, inte en färgruta @msg span: "selection" places a gradient: give `gradient` span: "selection" placerar en övertoning: ange `gradient` @msg span: "selection" places a linear or radial gradient, not a freeform one span: "selection" placerar en linjär eller radiell övertoning, inte en fri @msg span: "selection" places the gradient itself: leave out `start` and `end` (they already place it in document coordinates) span: "selection" placerar själva övertoningen: utelämna `start` och `end` (de placerar den redan i dokumentkoordinater) @msg the Color Picker is not open färgväljaren är inte öppen +@msg the Simplify slider is not open Förenkla-reglaget är inte öppet @msg the action has no steps åtgärden har inga steg @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer filens lager lästes inte ({_1}): den hämtas in som en sida, i ett enda lager @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part filens lager lästes inte från dess redigeringsdata ({_1}): de kommer från dess PDF-del @@ -5134,6 +5154,27 @@ theme Appearance Utseende Movie Clip Filmklipp @msg name is empty namnet är tomt @msg no symbol named `{n}` ingen symbol med namnet `{n}` + Smudge Stick… Utsmetning… + Smudge Stick Utsmetning + Sponge… Svamp… + Sponge Svamp + Watercolor… Akvarell… + Watercolor Akvarell + Brush Size Penselstorlek + Definition Skärpa + Brush Detail Penseldetalj + Shadow Intensity Skuggintensitet + Bas Relief… Basrelief… + Bas Relief Basrelief + Charcoal… Kol… + Charcoal Kol + Photocopy… Fotokopia… + Photocopy Fotokopia + Stamp… Stämpel… + Stamp Stämpel + Thickness Tjocklek + Detail Detalj + Light/Dark Balance Balans ljust/mörkt # Links and Attributes: files and URLs handed to other apps. @msg Edit Original opens image and document files only; “{name}” is not one Redigera original öppnar bara bild- och dokumentfiler; ”{name}” är ingen sådan @msg only http, https and mailto URLs open in the browser, not “{url}” bara http-, https- och mailto-URL:er öppnas i webbläsaren, inte ”{url}” @@ -5173,3 +5214,21 @@ theme Appearance Utseende @msg the file's variables and data sets weren't read (variables: {variables}, data sets: {data_sets}): the Variables panel doesn't list them filens variabler och datauppsättningar lästes inte (variabler: {variables}, datauppsättningar: {data_sets}): panelen Variabler visar dem inte # Select by Color (select.color) Select by Color Markera efter färg + Move Anchor Point Flytta ankarpunkt +@msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} behåller 1 av dokumentets {n} ritytor: filen öppnas igen med en. Slå på Bevara redigeringsmöjligheter för att behålla alla. + Chalk & Charcoal… Krita och kol… + Chalk & Charcoal Krita och kol + Graphic Pen… Grafisk penna… + Graphic Pen Grafisk penna + Reticulation… Retikulering… + Reticulation Retikulering + Plastic Wrap… Plastfolie… + Plastic Wrap Plastfolie + Chrome… Krom… + Chrome Krom + Drop here to take it out of its group Släpp här för att ta ut det ur gruppen + Move Library Group Flytta biblioteksgrupp + Plaster… Gips… + Plaster Gips + Note Paper… Anteckningspapper… + Note Paper Anteckningspapper diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 31ba1f93d5..e6171cc244 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1648,6 +1648,23 @@ fn align_reflect_and_shear_param_errors_are_translated() { } } +/// The warning that a data set with no value for a bound variable gives, which the status bar +/// shows and the scan above doesn't read, is translated in each language of [`COMPLETE_MESSAGES`], +/// with the data set's name kept. +#[test] +fn the_data_set_applied_nothing_warning_is_translated() { + use serde_json::json; + let mut s = vectorcraft_engine::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("dataset.import", &json!({"csv": "name,Name\nRow 7,Ann\n"})).unwrap(); + let v = s.execute("dataset.select", &json!({"name": "Row 7"})).unwrap(); + let warning = v["warning"].as_str().unwrap(); + for code in COMPLETE_MESSAGES { + let shown = message(Lang::from_code(code).unwrap(), warning); + assert!(shown.contains("Row 7") && !shown.contains("was applied"), "{code}: {shown}"); + } +} + /// The parameter errors of the blend spine commands (Move Spine Point, Reshape Spine Segment, Add /// Spine Point and Delete Spine Point, which Direct Selection, the Pen and the Anchor Point tool /// send), whose text the scan above doesn't read, are translated whole in each language of diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 3799af738b..581fd0e802 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1072,6 +1072,7 @@ Fill (X), double-click for the Color Picker Заливка (X), двічі клацніть на палітрі кольорів Fill and Stroke Заливка та обведення Fill new strokes Заповнювати нові обведення + Alt key toggles to Smooth Tool Клавіша Alt перемикає на інструмент «Згладжування» Keep selected Залишати вибраним Merge only with selection Об’єднувати лише з виділеним Fill Color Колір заливки @@ -1202,6 +1203,8 @@ file-filter Templates Шаблони Large Gaps Великі проміжки Gap Preview Color: Колір перегляду проміжків: Close Gaps With Paths Закрити проміжки контурами + Select Fills Виділяти заливки + Select Strokes Виділяти обведення Gaussian Blur… Розмиття за Гауссом… General Загальні General › Placement › X Загальні › Розміщення › X @@ -1409,6 +1412,12 @@ file-filter Templates Шаблони Release Envelope Звільнити оболонку Release Image Trace Звільнити трасування зображення Release Intertwine Звільнити переплетення + Objects on Path Об’єкти на контурі + Attach Прикріпити + Objects on Path Options Параметри об’єктів на контурі + Objects on Path Tool Інструмент «Об’єкти на контурі» + Attach Objects on Path Прикріпити об’єкти до контуру + Expand Objects on Path Розібрати об’єкти на контурі Release Live Paint Звільнити швидку заливку Release Repeat Звільнити повтор Release Slice Звільнити фрагмент @@ -1529,6 +1538,7 @@ file-filter Templates Шаблони Inspect Object Перевірити об’єкт Install Plug-in Встановити модуль Install Plug-in… Встановити модуль… + Open this setting's help page Відкрити сторінку довідки для цього параметра Installed plug-in {} Встановлено модуль {} Intensity: Інтенсивність: Intent: Призначення: @@ -1733,6 +1743,7 @@ file-filter Templates Шаблони Load Text into Clipboard Завантажити текст у буфер обміну Local Libraries Локальні бібліотеки Locate Object Знайти об’єкт + Locate Selected Objects Знаходити виділені об’єкти Location Розташування Location: Розташування: Lock Заблокувати @@ -2163,6 +2174,7 @@ file-filter Templates Шаблони Output White Вихідний білий Output › Mode Виведення › Режим Output: Виведення: + Overlap Перекриття Overlap: Перекриття: Overlapping Перекривається Overlay Накладання @@ -2940,6 +2952,8 @@ mark-style Japanese Японський Show Note Показати примітку Show Options Показати параметри Show Original Path Показати початковий контур + Open this dialog with these settings next time Наступного разу відкривати це діалогове вікно з цими параметрами + Auto-Simplify Автоматичне спрощення Color Panel Options Параметри панелі «Колір» Show Package Показати пакет Show Panel Показати панель @@ -3037,6 +3051,7 @@ effect Points Точки Snap to Pixel Прив’язати до пікселя Precise Cursors Точні курсори Snap to Point Прив’язати до точки + Snap to Unit Прив’язати до одиниць Snapping Tolerance Допуск прив’язки Social Square Post 1080×1080 Квадратний пост для соцмереж 1080×1080 Soft Light М’яке світло @@ -3164,7 +3179,7 @@ effect Points Точки Delete Library Item Видалити елемент бібліотеки No results Нічого не знайдено No items in this library match “{query}”. У цій бібліотеці немає елементів, що відповідають «{query}». - Right-click an item to move it into this group. Клацніть елемент правою кнопкою миші, щоб перемістити його в цю групу. + Drag an item here, or right-click one, to put it in this group. Перетягніть сюди елемент або клацніть його правою кнопкою миші, щоб покласти його в цю групу. New Group Нова група New Group… Нова група… Move to Group Перемістити в групу @@ -3224,6 +3239,7 @@ effect Points Точки Text Wrap Options Параметри обтікання текстом Text Wrap Options… Параметри обтікання текстом… The bounds of the visible art. Кордони видимого малюнка. + The plug-in writes the whole document. Модуль експортує весь документ. The cell shows the type object's text as HTML. Осередок показує текст текстового об’єкта як HTML. The document has no colour swatches. У документі немає кольорових зразків. The edge of the paper the printer can't reach: the art goes inside it, and the preview shows it dashed. Край паперу, до якого не приходить принтер: малюнок залишається всередині нього, а перегляд показує його пунктиром. @@ -3883,6 +3899,7 @@ axis Both Обидві @msg background {other}: transparent, white, black or a colour such as "#ff8800" фон {other}: transparent, white, black або колір, наприклад "#ff8800" @msg bad color {v} неприпустимий колір {v} @msg the Color Picker is not open палітра кольорів не відкрита +@msg the Simplify slider is not open повзунок «Спростити» не відкрито @msg the screen color sampler is already open засіб вибору кольору з екрана вже відкритий @msg this system has no screen color sampler у цій системі немає засобу вибору кольору з екрана @msg bad colour `{hex}` (#rrggbb) неприпустимий колір `{hex}` (#rrggbb) @@ -4120,6 +4137,7 @@ axis Both Обидві @msg select a linked image: an embedded one has no file виділіть пов’язане зображення: у вбудованого немає файлу @msg select a repeat виділіть повтор @msg select an Intertwine group виділіть групу переплетення +@msg select an Objects on Path group виділіть групу об’єктів на контурі @msg select a stroke with a variable width виділіть обведення зі змінною шириною @msg select a symbol instance виділіть екземпляр символу @msg select an Image Trace object виділіть об’єкт трасування зображення @@ -4249,6 +4267,7 @@ axis Both Обидві @msg {_1} files are written by file.saveAsTemplate файли {_1} записує file.saveAsTemplate @msg {_1} font families available доступно сімейства шрифтів: {_1} @msg {_1} is a live effect (Effect › Plug-ins) {_1} - динамічний ефект (Ефект › Модулі) +@msg {_1} is an exporter (File › Export › Export As…) {_1} - модуль експорту (Файл › Експорт › Експортувати як…) @msg {_1} is already used by {_2} {_1} вже використовується {_2} @msg {_1} linked file(s) can't be read here: their previews show тут неможливо прочитати пов’язані файли: {_1}: відображаються їх попередні перегляди @msg {_1} linked image(s) changed on disk: Update Links shows the new versions пов’язаних зображень ({_1}) змінилися на диску: «Оновити зв’язки» покаже нові версії @@ -4749,6 +4768,7 @@ lighting Light Світло @msg choose a destination folder виберіть папку призначення @msg choose a source folder виберіть вихідну папку @msg open a document with data sets відкрийте документ із наборами даних +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for з набору даних {name} нічого не застосовано: жоден об’єкт не прив’язано до змінної, для якої в ньому є значення @msg the action has no steps у дії немає кроків # User Interface › Accent Color @@ -4771,6 +4791,27 @@ lighting Light Світло Movie Clip Кліп @msg name is empty ім’я порожнє @msg no symbol named `{n}` немає символу з назвою `{n}` + Smudge Stick… Розтушовування… + Smudge Stick Розтушовування + Sponge… Губка… + Sponge Губка + Watercolor… Акварель… + Watercolor Акварель + Brush Size Розмір пензля + Definition Чіткість + Brush Detail Деталізація пензля + Shadow Intensity Інтенсивність тіней + Bas Relief… Барельєф… + Bas Relief Барельєф + Charcoal… Вугілля… + Charcoal Вугілля + Photocopy… Фотокопія… + Photocopy Фотокопія + Stamp… Штамп… + Stamp Штамп + Thickness Товщина + Detail Деталі + Light/Dark Balance Баланс світлого й темного # Links and Attributes: files and URLs handed to other apps. @msg Edit Original opens image and document files only; “{name}” is not one «Редагувати оригінал» відкриває лише файли зображень і документів; «{name}» до них не належить @msg only http, https and mailto URLs open in the browser, not “{url}” у браузері відкриваються лише URL з http, https і mailto, а не «{url}» @@ -4811,3 +4852,21 @@ lighting Light Світло @msg the file's variables and data sets weren't read (variables: {variables}, data sets: {data_sets}): the Variables panel doesn't list them змінні та набори даних файлу не прочитано (змінних: {variables}, наборів даних: {data_sets}): панель «Змінні» їх не показує # Select by Color (select.color) Select by Color Виділити за кольором + Move Anchor Point Перемістити опорну точку +@msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} зберігає 1 з {n} монтажних областей документа: файл відкриється знову з однією. Увімкніть «Зберігати можливості редагування», щоб зберегти всі. + Chalk & Charcoal… Крейда і вугілля… + Chalk & Charcoal Крейда і вугілля + Graphic Pen… Графічне перо… + Graphic Pen Графічне перо + Reticulation… Ретикуляція… + Reticulation Ретикуляція + Plastic Wrap… Целофанова плівка… + Plastic Wrap Целофанова плівка + Chrome… Хром… + Chrome Хром + Drop here to take it out of its group Відпустіть тут, щоб вийняти його з групи + Move Library Group Перемістити групу бібліотеки + Plaster… Гіпс… + Plaster Гіпс + Note Paper… Поштовий папір… + Note Paper Поштовий папір diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index b265ad506a..352a6cd985 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1243,6 +1243,7 @@ Fill Color Màu tô Fill Grid Tô lưới Fill new strokes Tô nét mới + Alt key toggles to Smooth Tool Phím Alt chuyển sang công cụ Làm mượt Keep selected Giữ trạng thái đã chọn Merge only with selection Chỉ hợp nhất với vùng chọn Fill New Type Objects With Placeholder Text Tô đối tượng chữ mới bằng văn bản giữ chỗ @@ -1394,6 +1395,8 @@ file-filter Templates Mẫu Large Gaps Khoảng cách lớn Gap Preview Color: Màu xem trước khoảng cách: Close Gaps With Paths Đóng khoảng cách bằng đường dẫn + Select Fills Chọn vùng tô + Select Strokes Chọn nét Gaussian Blur Mờ Gaussian Gaussian Blur… Làm mờ Gaussian… General Chung @@ -1608,6 +1611,12 @@ file-filter Templates Mẫu Release Envelope Giải phóng Envelope Release Image Trace Giải phóng vector hóa ảnh Release Intertwine Giải phóng đan xen + Objects on Path Đối tượng trên đường dẫn + Attach Gắn + Objects on Path Options Tùy chọn đối tượng trên đường dẫn + Objects on Path Tool Công cụ Đối tượng trên đường dẫn + Attach Objects on Path Gắn đối tượng lên đường dẫn + Expand Objects on Path Mở rộng đối tượng trên đường dẫn Release Live Paint Giải phóng tô trực tiếp Release Repeat Giải phóng lặp lại Release Slice Giải phóng lát cắt @@ -1778,6 +1787,7 @@ file-filter Templates Mẫu Inspect Object Kiểm tra đối tượng Install Plug-in Cài đặt plug-in Install Plug-in… Cài đặt plug-in… + Open this setting's help page Mở trang trợ giúp của thiết lập này Installed plug-in {} Đã cài plug-in {} Intensity Cường độ Intensity: Cường độ: @@ -1986,6 +1996,7 @@ file-filter Templates Mẫu Loaded Texture Kết cấu đã tải Local Libraries Thư viện cục bộ Locate Object Xác định vị trí đối tượng + Locate Selected Objects Xác định vị trí đối tượng đã chọn Location Vị trí Location: Vị trí: Lock Khóa @@ -2438,6 +2449,7 @@ file-filter Templates Mẫu Output › Mode Đầu ra › Chế độ Output: Đầu ra: Outside Bên ngoài + Overlap Chồng lấp Overlap: Chồng lấp: Overlapping Chồng lấp Overlay Phủ lên @@ -2915,7 +2927,7 @@ mark-style Japanese Kiểu Nhật Right Indent Thụt lề phải Right Plane Mặt phẳng phải Right to Left Phải sang trái - Right-click an item to move it into this group. Bấm chuột phải vào mục để di chuyển vào nhóm này. + Drag an item here, or right-click one, to put it in this group. Kéo một mục vào đây, hoặc bấm chuột phải vào mục, để đưa vào nhóm này. Right-Justified Tab Tab căn phải Right-to-Left Paragraph Direction Hướng đoạn văn từ phải sang trái Right: Phải: @@ -3273,6 +3285,8 @@ mark-style Japanese Kiểu Nhật Show Note Hiện ghi chú Show Options Hiện tùy chọn Show Original Path Hiện đường dẫn gốc + Open this dialog with these settings next time Lần sau mở hộp thoại này với các cài đặt này + Auto-Simplify Tự động đơn giản hóa Color Panel Options Tùy chọn bảng màu Show Package Hiện gói Show Panel Hiện bảng @@ -3365,6 +3379,7 @@ mark-style Japanese Kiểu Nhật Snap to Pixel Hút vào pixel Precise Cursors Con trỏ chính xác Snap to Point Hút vào điểm + Snap to Unit Hút vào đơn vị Snapping Tolerance Dung sai hút Social Square Post 1080×1080 Bài đăng vuông mạng xã hội 1080×1080 Soft Mềm @@ -3558,6 +3573,7 @@ mark-style Japanese Kiểu Nhật Texturizer… Texturizer… Thai Tiếng Thái The bounds of the visible art. Vùng giới hạn của đối tượng hiển thị. + The plug-in writes the whole document. Plug-in xuất toàn bộ tài liệu. The cell shows the type object's text as HTML. Ô hiển thị văn bản của đối tượng chữ dưới dạng HTML. The dialog was closed before its file dialog answered Hộp thoại đã đóng trước khi hộp thoại tệp phản hồi The document has no colour swatches. Tài liệu không có mẫu màu. @@ -4051,6 +4067,7 @@ theme Appearance Giao diện @msg background {other}: transparent, white, black or a colour such as "#ff8800" background {other}: transparent, white, black hoặc màu như "#ff8800" @msg bad color {v} màu không hợp lệ {v} @msg the Color Picker is not open Bộ chọn màu chưa được mở +@msg the Simplify slider is not open Thanh trượt Đơn giản hóa chưa được mở @msg the screen color sampler is already open công cụ lấy mẫu màu trên màn hình đã được mở @msg this system has no screen color sampler hệ thống này không có công cụ lấy mẫu màu trên màn hình @msg bad colour `{hex}` (#rrggbb) màu không hợp lệ `{hex}` (#rrggbb) @@ -4436,6 +4453,7 @@ theme Appearance Giao diện @msg select a Live Paint group hãy chọn nhóm tô trực tiếp @msg select a repeat hãy chọn một đối tượng lặp @msg select an Intertwine group hãy chọn một nhóm đan xen +@msg select an Objects on Path group hãy chọn một nhóm đối tượng trên đường dẫn @msg select a stroke with a variable width hãy chọn nét có chiều rộng biến đổi @msg select a symbol instance hãy chọn đối tượng ký hiệu @msg select an envelope hãy chọn một Envelope @@ -4623,6 +4641,7 @@ theme Appearance Giao diện @msg {_1} font families available {_1} họ phông chữ khả dụng @msg {_1} has no {_2} style {_1} không có kiểu {_2} @msg {_1} is a live effect (Effect › Plug-ins) {_1} là hiệu ứng trực tiếp (Hiệu ứng › Plug-ins) +@msg {_1} is an exporter (File › Export › Export As…) {_1} là plug-in xuất (Tệp › Xuất › Xuất thành…) @msg {_1} is already used by {_2} {_1} đã được dùng bởi {_2} @msg {_1} linked file(s) can't be read here: their previews show {_1} tệp liên kết không thể đọc ở đây: bản xem trước được hiển thị @msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} ảnh liên kết đã thay đổi trên đĩa: Cập nhật liên kết hiển thị phiên bản mới @@ -4749,6 +4768,7 @@ theme Appearance Giao diện @msg choose a destination folder hãy chọn thư mục đích @msg choose a source folder hãy chọn thư mục nguồn @msg open a document with data sets hãy mở một tài liệu có tập dữ liệu +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for không có gì trong tập dữ liệu {name} được áp dụng: không có đối tượng nào được gắn với biến số mà tập dữ liệu có giá trị @msg the action has no steps hành động không có bước nào # User Interface › Accent Color @@ -4771,6 +4791,27 @@ theme Appearance Giao diện Movie Clip Clip phim @msg name is empty tên trống @msg no symbol named `{n}` không có biểu tượng nào tên `{n}` + Smudge Stick… Bút chì xóa mờ… + Smudge Stick Bút chì xóa mờ + Sponge… Bọt biển… + Sponge Bọt biển + Watercolor… Màu nước… + Watercolor Màu nước + Brush Size Kích thước cọ + Definition Độ nét + Brush Detail Chi tiết cọ + Shadow Intensity Cường độ bóng + Bas Relief… Chạm nổi… + Bas Relief Chạm nổi + Charcoal… Than củi… + Charcoal Than củi + Photocopy… Bản photocopy… + Photocopy Bản photocopy + Stamp… Con dấu… + Stamp Con dấu + Thickness Độ dày + Detail Chi tiết + Light/Dark Balance Cân bằng sáng/tối # Links and Attributes: files and URLs handed to other apps. @msg Edit Original opens image and document files only; “{name}” is not one Chỉnh sửa bản gốc chỉ mở tệp hình ảnh và tài liệu; “{name}” không thuộc loại đó @msg only http, https and mailto URLs open in the browser, not “{url}” chỉ URL http, https và mailto mới được mở trong trình duyệt, không mở “{url}” @@ -4811,3 +4852,21 @@ theme Appearance Giao diện @msg the file's variables and data sets weren't read (variables: {variables}, data sets: {data_sets}): the Variables panel doesn't list them các biến và tập dữ liệu của tệp chưa được đọc (biến: {variables}, tập dữ liệu: {data_sets}): bảng Biến không liệt kê chúng # Select by Color (select.color) Select by Color Chọn theo màu + Move Anchor Point Di chuyển điểm neo +@msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} chỉ giữ 1 trong {n} bảng vẽ của tài liệu: tệp sẽ mở lại với một bảng vẽ. Bật Bảo lưu khả năng chỉnh sửa để giữ tất cả. + Chalk & Charcoal… Phấn và than… + Chalk & Charcoal Phấn và than + Graphic Pen… Bút đồ họa… + Graphic Pen Bút đồ họa + Reticulation… Lưới hạt… + Reticulation Lưới hạt + Plastic Wrap… Màng bọc nhựa… + Plastic Wrap Màng bọc nhựa + Chrome… Crôm… + Chrome Crôm + Drop here to take it out of its group Thả vào đây để đưa ra khỏi nhóm + Move Library Group Di chuyển nhóm thư viện + Plaster… Thạch cao… + Plaster Thạch cao + Note Paper… Giấy ghi chú… + Note Paper Giấy ghi chú diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 3e2daf8b01..e9852ef843 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1026,6 +1026,7 @@ Fill (X), double-click for the Color Picker 填色 (X),双击打开拾色器 Fill and Stroke 填色和描边 Fill new strokes 为新描边应用填色 + Alt key toggles to Smooth Tool Alt 键切换为平滑工具 Keep selected 保持选择状态 Merge only with selection 仅与所选对象合并 Fill Color 填色 @@ -1155,6 +1156,8 @@ file-filter Templates 模板 Large Gaps 大间隙 Gap Preview Color: 间隙预览颜色: Close Gaps With Paths 用路径封闭间隙 + Select Fills 选择填色 + Select Strokes 选择描边 Gaussian Blur… 高斯模糊… General 常规 General › Placement › X 一般 › 位置 › X @@ -1352,6 +1355,12 @@ file-filter Templates 模板 Release Blend 释放混合 Release Envelope 释放封套 Release Intertwine 释放交织 + Objects on Path 路径上的对象 + Attach 附加 + Objects on Path Options 路径上的对象选项 + Objects on Path Tool 路径上的对象工具 + Attach Objects on Path 附加路径上的对象 + Expand Objects on Path 扩展路径上的对象 Release Live Paint 释放实时上色 Release Repeat 释放重复 Release Slice 释放切片 @@ -1470,6 +1479,7 @@ file-filter Templates 模板 Inspect Object 检查对象 Install Plug-in 安装插件 Install Plug-in… 安装增效工具… + Open this setting's help page 打开此设置的帮助页面 Installed plug-in {} 已安装增效工具 {} Intensity: 强度: Intent: 意图: @@ -1630,6 +1640,7 @@ file-filter Templates 模板 Load Text into Clipboard 将文本载入剪贴板 Local Libraries 本地库 Locate Object 查找对象 + Locate Selected Objects 查找所选对象 Location 位置 Location: 位置: Lock 锁定 @@ -2060,6 +2071,7 @@ file-filter Templates 模板 Output White 输出白色 Output › Mode 输出 › 模式 Output: 输出: + Overlap 重叠 Overlap: 重叠: Overlapping 重叠 Overlay 叠加 @@ -2245,6 +2257,7 @@ diagnostics ui 界面 Printer mark type: 打印机标记类型: Roman 西式 mark-style Japanese 日式 +font-script Japanese 汉字 Printer profile: 打印机配置文件: Printer Setup… 打印机设置… Printer: 打印机: @@ -2798,6 +2811,8 @@ mark-style Japanese 日式 Show Note 显示注解 Show Options 显示选项 Show Original Path 显示原始路径 + Open this dialog with these settings next time 下次以这些设置打开此对话框 + Auto-Simplify 自动简化 Color Panel Options 颜色面板选项 Show Package 显示打包 Show Panel 显示面板 @@ -2894,6 +2909,7 @@ mark-style Japanese 日式 Snap to Pixel 对齐像素 Precise Cursors 精确光标 Snap to Point 对齐点 + Snap to Unit 对齐单位 Snapping Tolerance 吸附容差 Social Square Post 1080×1080 社交方形帖子 1080×1080 Soft Light 柔光 @@ -3021,7 +3037,7 @@ mark-style Japanese 日式 Delete Library Item 删除库项目 No results 无结果 No items in this library match “{query}”. 此库中没有与“{query}”匹配的项目。 - Right-click an item to move it into this group. 右键单击项目可将其移到此组。 + Drag an item here, or right-click one, to put it in this group. 将项目拖到此处,或右键单击项目,即可将其放入此组。 New Group 新建组 New Group… 新建组… Move to Group 移到组 @@ -3081,6 +3097,7 @@ mark-style Japanese 日式 Text Wrap Options 文字绕图选项 Text Wrap Options… 文本绕排选项… The bounds of the visible art. 可见图稿的边界。 + The plug-in writes the whole document. 增效工具会导出整个文档。 The cell shows the type object's text as HTML. 该单元格以 HTML 显示文字对象的内容。 The document has no colour swatches. 文档没有颜色色板。 The edge of the paper the printer can't reach: the art goes inside it, and the preview shows it dashed. 打印机无法触及的纸张边缘:图稿会放在其内侧,预览中会以虚线显示。 @@ -3770,6 +3787,7 @@ imageTrace Outline 轮廓 @msg pattern missing 缺少图案 @msg select a repeat 请选择一个重复对象 @msg select an Intertwine group 请选择一个交织组 +@msg select an Objects on Path group 请选择一个路径上的对象组 @msg select the art to repeat 请选择要重复的图稿 @msg the document has no patterns 文档中没有图案 @msg no artboard 没有画板 @@ -3958,6 +3976,7 @@ imageTrace Outline 轮廓 @msg no blend options 没有混合选项 @msg bad color {v} 颜色 {v} 无效 @msg the Color Picker is not open 拾色器未打开 +@msg the Simplify slider is not open 简化滑块未打开 @msg the screen color sampler is already open 屏幕取色器已打开 @msg this system has no screen color sampler 此系统没有屏幕取色器 @msg Corners edits the corners of a path 转角用于编辑路径的转角 @@ -3997,6 +4016,7 @@ imageTrace Outline 轮廓 @msg missing `id` (see plugin.list) 缺少 `id` (请参阅 plugin.list) @msg no plug-in {id} is installed 未安装增效工具 {id} @msg {_1} is a live effect (Effect › Plug-ins) {_1} 是实时效果 (效果 › 增效工具) +@msg {_1} is an exporter (File › Export › Export As…) {_1} 是导出增效工具 (文件 › 导出 › 导出为…) @msg a preset named `{_1}` exists 名为 `{_1}` 的预设已存在 @msg a swatch or color group named `{n}` exists 名为 `{n}` 的色板或颜色组已存在 @msg no print preset named `{base}` 没有名为 `{base}` 的打印预设 @@ -4248,6 +4268,7 @@ imageTrace Outline 轮廓 @msg choose a destination folder 请选择目标文件夹 @msg choose a source folder 请选择源文件夹 @msg open a document with data sets 请打开包含数据集的文档 +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for 数据集 {name} 未应用任何内容:没有对象绑定到该数据集中有值的变量 @msg the action has no steps 该动作没有步骤 # Import Shortcut Set (Keyboard Shortcuts › Import…, File › Open of a .kys file) and its commands. Import Shortcut Set 导入快捷键组 @@ -5010,6 +5031,27 @@ lighting Light 光源 Movie Clip 影片剪辑 @msg name is empty 名称为空 @msg no symbol named `{n}` 没有名为 `{n}` 的符号 + Smudge Stick… 涂抹棒… + Smudge Stick 涂抹棒 + Sponge… 海绵… + Sponge 海绵 + Watercolor… 水彩… + Watercolor 水彩 + Brush Size 画笔大小 + Definition 清晰度 + Brush Detail 画笔细节 + Shadow Intensity 阴影强度 + Bas Relief… 浅浮雕… + Bas Relief 浅浮雕 + Charcoal… 炭笔… + Charcoal 炭笔 + Photocopy… 影印… + Photocopy 影印 + Stamp… 图章… + Stamp 图章 + Thickness 粗细 + Detail 细节 + Light/Dark Balance 明暗平衡 Enable Guides for 9-Slice Scaling 启用 9-slice 缩放参考线 @msg cancelled; nothing was changed 已取消;未做任何更改 @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it 保存会写入 {_1},而不是 {_2}:要写入该格式请使用 file.saveAsTemplate @@ -5053,3 +5095,21 @@ lighting Light 光源 @msg the file's variables and data sets weren't read (variables: {variables}, data sets: {data_sets}): the Variables panel doesn't list them 文件的变量和数据集未被读取(变量:{variables},数据集:{data_sets}):“变量”面板不会列出它们 # Select by Color (select.color) Select by Color 按颜色选择 + Move Anchor Point 移动锚点 +@msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} 只保留文档 {n} 个画板中的 1 个:文件重新打开时只有一个。打开“保留编辑功能”可全部保留。 + Chalk & Charcoal… 粉笔和炭笔… + Chalk & Charcoal 粉笔和炭笔 + Graphic Pen… 绘图笔… + Graphic Pen 绘图笔 + Reticulation… 网状… + Reticulation 网状 + Plastic Wrap… 塑料包装… + Plastic Wrap 塑料包装 + Chrome… 铬黄… + Chrome 铬黄 + Drop here to take it out of its group 放到此处可将其移出所在组 + Move Library Group 移动库组 + Plaster… 塑料效果… + Plaster 塑料效果 + Note Paper… 便条纸… + Note Paper 便条纸 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9c356c2dd2..106ffc9ea3 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1050,6 +1050,7 @@ Fill and Stroke 填色與筆畫 Fill Color 填色顏色 Fill new strokes 為新筆畫套用填色 + Alt key toggles to Smooth Tool Alt 鍵切換為平滑工具 Keep selected 保持選取狀態 Merge only with selection 僅與選取物件合併 Fill New Type Objects With Placeholder Text 以預留位置文字填滿新文字物件 @@ -1179,6 +1180,8 @@ file-filter Templates 範本 Large Gaps 大間隙 Gap Preview Color: 間隙預覽顏色: Close Gaps With Paths 以路徑封閉間隙 + Select Fills 選取填色 + Select Strokes 選取筆畫 Gaussian Blur… 高斯模糊… General 一般 General › Placement › X 一般 › 位置 › X @@ -1387,6 +1390,12 @@ file-filter Templates 範本 Release Envelope 釋放封套 Release Image Trace 釋放影像描圖 Release Intertwine 釋放交織 + Objects on Path 路徑上的物件 + Attach 附加 + Objects on Path Options 路徑上的物件選項 + Objects on Path Tool 路徑上的物件工具 + Attach Objects on Path 附加路徑上的物件 + Expand Objects on Path 展開路徑上的物件 Release Live Paint 釋放即時上色 Release Repeat 釋放重複 Release Slice 釋放切片 @@ -1506,6 +1515,7 @@ file-filter Templates 範本 Inspect Object 檢查物件 Install Plug-in 安裝增效模組 Install Plug-in… 安裝增效模組… + Open this setting's help page 開啟此設定的說明頁面 Installed plug-in {} 已安裝增效模組 {} Intensity: 強度: Intent: 目的: @@ -1781,6 +1791,7 @@ file-filter Templates 範本 @msg pattern missing 找不到圖樣 @msg select a repeat 請選取重複物件 @msg select an Intertwine group 請選取交織群組 +@msg select an Objects on Path group 請選取路徑上的物件群組 @msg select the art to repeat 請選取要重複的圖稿 @msg the document has no patterns 文件中沒有圖樣 @msg no artboard 沒有工作區域 @@ -1969,6 +1980,7 @@ file-filter Templates 範本 @msg no blend options 沒有漸變選項 @msg bad color {v} 顏色 {v} 無效 @msg the Color Picker is not open 「顏色選擇器」未開啟 +@msg the Simplify slider is not open 「簡化」滑桿未開啟 @msg the screen color sampler is already open 螢幕取色器已開啟 @msg this system has no screen color sampler 此系統沒有螢幕取色器 @msg Corners edits the corners of a path 「轉角」用於編輯路徑的轉角 @@ -2008,6 +2020,7 @@ file-filter Templates 範本 @msg missing `id` (see plugin.list) 未提供 `id` (請參閱 plugin.list) @msg no plug-in {id} is installed 未安裝增效模組 {id} @msg {_1} is a live effect (Effect › Plug-ins) {_1} 是即時效果 (效果 › 增效模組) +@msg {_1} is an exporter (File › Export › Export As…) {_1} 是匯出增效模組 (檔案 › 匯出 › 匯出為…) @msg a preset named `{_1}` exists 名為 `{_1}` 的預設集已存在 @msg a swatch or color group named `{n}` exists 名為 `{n}` 的色票或顏色群組已存在 @msg no print preset named `{base}` 沒有名為 `{base}` 的列印預設集 @@ -2259,6 +2272,7 @@ file-filter Templates 範本 @msg choose a destination folder 請選擇目的地資料夾 @msg choose a source folder 請選擇來源資料夾 @msg open a document with data sets 請開啟含有資料集的文件 +@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for 資料集 {name} 未套用任何內容:沒有物件綁定到該資料集中有值的變數 @msg the action has no steps 動作沒有步驟 @msg cancelled; nothing was changed 已取消;未做任何變更 @msg Save writes {_1}, not {_2}: use file.saveAsTemplate to write it 「儲存」會寫入 {_1},而非 {_2}:若要寫入該格式,請使用 file.saveAsTemplate @@ -2443,6 +2457,7 @@ file-filter Templates 範本 Load Text into Clipboard 將文字載入剪貼簿 Local Libraries 本機資料庫 Locate Object 尋找物件 + Locate Selected Objects 尋找選取的物件 Location 位置 Location: 位置: Lock 鎖定 @@ -2888,6 +2903,7 @@ file-filter Templates 範本 Output White 輸出白色 Output › Mode 輸出 › 模式 Output: 輸出: + Overlap 重疊 Overlap: 重疊: Overlapping 重疊 Overlay 覆蓋 @@ -3075,6 +3091,7 @@ diagnostics ui 介面 Printer mark type: 印表機標記類型: Roman 西式 mark-style Japanese 日式 +font-script Japanese 漢字 Printer profile: 印表機描述檔: Printer Setup… 印表機設定… Printer: 印表機: @@ -3666,6 +3683,8 @@ mark-style Japanese 日式 Show Note 顯示註解 Show Options 顯示選項 Show Original Path 顯示原始路徑 + Open this dialog with these settings next time 下次以這些設定開啟此對話方塊 + Auto-Simplify 自動簡化 Color Panel Options 顏色面板選項 Show Package 顯示封裝 Show Panel 顯示面板 @@ -3762,6 +3781,7 @@ mark-style Japanese 日式 Snap to Pixel 靠齊像素 Precise Cursors 精確游標 Snap to Point 靠齊控制點 + Snap to Unit 靠齊單位 Snapping Tolerance 靠齊容許度 Social Square Post 1080×1080 社群正方形貼文 1080×1080 Soft Light 柔光 @@ -3889,7 +3909,7 @@ mark-style Japanese 日式 Delete Library Item 刪除資料庫項目 No results 沒有結果 No items in this library match “{query}”. 此資料庫中沒有符合「{query}」的項目。 - Right-click an item to move it into this group. 在項目上按一下右鍵,即可將其移至此群組。 + Drag an item here, or right-click one, to put it in this group. 將項目拖到此處,或在項目上按一下右鍵,即可將其放入此群組。 New Group 新增群組 New Group… 新增群組… Move to Group 移至群組 @@ -3949,6 +3969,7 @@ mark-style Japanese 日式 Text Wrap Options 文字繞圖選項 Text Wrap Options… 文字繞圖選項… The bounds of the visible art. 可見圖稿的邊界。 + The plug-in writes the whole document. 增效模組會匯出整份文件。 The cell shows the type object's text as HTML. 儲存格以 HTML 顯示文字物件的文字。 The document has no colour swatches. 文件中沒有色票。 The edge of the paper the printer can't reach: the art goes inside it, and the preview shows it dashed. 印表機無法觸及的紙張邊緣:圖稿會放在其內側,預覽中會以虛線顯示。 @@ -4820,6 +4841,27 @@ lighting Light 光源 Movie Clip 影片片段 @msg name is empty 名稱為空 @msg no symbol named `{n}` 沒有名為 `{n}` 的符號 + Smudge Stick… 塗抹棒… + Smudge Stick 塗抹棒 + Sponge… 海綿… + Sponge 海綿 + Watercolor… 水彩… + Watercolor 水彩 + Brush Size 筆刷大小 + Definition 清晰度 + Brush Detail 筆刷細節 + Shadow Intensity 陰影強度 + Bas Relief… 淺浮雕… + Bas Relief 淺浮雕 + Charcoal… 炭筆… + Charcoal 炭筆 + Photocopy… 影印… + Photocopy 影印 + Stamp… 圖章… + Stamp 圖章 + Thickness 粗細 + Detail 細節 + Light/Dark Balance 明暗平衡 Enable Guides for 9-Slice Scaling 啟用 9-slice 縮放參考線 Persistent 持久 Library Panel Options 資料庫面板選項 @@ -4848,3 +4890,21 @@ lighting Light 光源 @msg {key} must be an array of non-negative integer object ids {key} 必須是由非負整數物件 id 組成的陣列 @msg invalid object id {value}: expected a non-negative integer 無效的物件 id {value}:應為非負整數 @msg no such object id {value} 沒有 id 為 {value} 的物件 + Move Anchor Point 移動錨點 +@msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} 只保留文件 {n} 個工作區域中的 1 個:檔案重新開啟時只有一個。開啟「保留編輯功能」可全部保留。 + Chalk & Charcoal… 粉筆和炭筆… + Chalk & Charcoal 粉筆和炭筆 + Graphic Pen… 繪圖筆… + Graphic Pen 繪圖筆 + Reticulation… 網狀… + Reticulation 網狀 + Plastic Wrap… 塑膠包裝… + Plastic Wrap 塑膠包裝 + Chrome… 鉻黃… + Chrome 鉻黃 + Drop here to take it out of its group 放到此處即可將其移出所屬群組 + Move Library Group 移動資料庫群組 + Plaster… 塑膠效果… + Plaster 塑膠效果 + Note Paper… 便條紙… + Note Paper 便條紙 diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index ac6274e70b..a2fa994852 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -115,6 +115,7 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-new-fill", include_bytes!("../../../assets/icons/dc-new-fill.svg")), ("dc-new-item", include_bytes!("../../../assets/icons/dc-new-item.svg")), ("dc-new-stroke", include_bytes!("../../../assets/icons/dc-new-stroke.svg")), + ("dc-objects-on-path", include_bytes!("../../../assets/icons/dc-objects-on-path.svg")), ("dc-options", include_bytes!("../../../assets/icons/dc-options.svg")), ("dc-para-center", include_bytes!("../../../assets/icons/dc-para-center.svg")), ("dc-para-justify-all", include_bytes!("../../../assets/icons/dc-para-justify-all.svg")), diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index fb4ea148cb..52476db6f4 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -84,6 +84,7 @@ pub fn tool_icon(name: &str) -> &'static str { "tool-measure" => "dc-measure", "tool-dimension" => "dc-dimension", "tool-blend" => "dc-blend", + "tool-objects-on-path" => "dc-objects-on-path", "tool-symbol" => "dc-symbol-sprayer", "tool-graph" => "chart-column", "tool-artboard" => "frame", @@ -176,6 +177,16 @@ mod tests { } } + /// Appearance (effects) and Pathfinder both lived in the icon column; they used the same + /// overlapping-squares motif (storytold/vectorcraft#2681). + #[test] + fn appearance_panel_icon_is_not_the_pathfinder_icon() { + let appearance = String::from_utf8_lossy(include_bytes!("../../../assets/icons/dc-appearance.svg")); + let pathfinder = String::from_utf8_lossy(include_bytes!("../../../assets/icons/dc-pathfinder.svg")); + assert_ne!(appearance.as_bytes(), pathfinder.as_bytes()); + assert!(appearance.contains(" Result, +/// Options, the Save PDF dialog, or the save options dialog: native files on Save As only, `.ai` +/// files on Save As and Save a Copy), and so does Save As or Save a Copy to a given SVG path. +/// → `{path, format, warnings…}` once written, or `{pending: , /// path?}` while a dialog is open. pub fn save(app: &mut VectorcraftApp, mode: SaveMode, p: &Value, ask_options: bool) -> Result { remember_view(app); @@ -524,12 +525,14 @@ fn ask_before_losing(app: &mut VectorcraftApp, path: &str, command: &str, params } /// Does a save (`mode`) to a picked file of format `f` ask for its options first? Native and `.ai` -/// files only on Save As (the options dialog after the save panel); Save, a Copy and templates -/// reuse the remembered options or Use Compression. +/// files on Save As (the options dialog after the save panel), and `.ai` files also on Save a Copy, +/// so the copy is not written in the version last saved whatever the panel's `.ai` type says +/// (#3141); Save and templates reuse the remembered options or Use Compression. fn asks_options(mode: SaveMode, f: &Format) -> bool { !f.options.is_empty() && match f.id { - "vectorcraft" | "ai" => mode == SaveMode::SaveAs, + "vectorcraft" => mode == SaveMode::SaveAs, + "ai" => matches!(mode, SaveMode::SaveAs | SaveMode::Copy), "template" | "ait" => false, _ => true, } @@ -722,9 +725,13 @@ pub fn export(app: &mut VectorcraftApp, format: Option<&str>, path: Option z, _ => f, }; - // Background Export: encoded and written from this snapshot while editing goes on. + // Background Export: encoded and written from this snapshot while editing goes on. The + // encoder is told the file it writes (an exporter plug-in gets its name and extension). let label = format!("Exporting {}", fileio::file_name(&path)); - let (params, target) = (params.clone(), path.clone()); + let (mut params, target) = (params.clone(), path.clone()); + if let Some(o) = params.as_object_mut() { + o.insert("path".into(), json!(path)); + } // The progress dialog's counts and Cancel: a cancelled export stops drawing and never starts // writing. let progress = Progress::new(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index cbcde9e403..7d63c21a84 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -311,6 +311,9 @@ pub struct CanvasCache { /// drag's lower resolution ([`vectorcraft_render::FrameStats::moved`]): the next frame outside /// an interaction runs them again, on the worker when there is one. pub moved: bool, + /// The frame shown was rendered on the worker: an interaction's frames stay there + /// ([`canvas::show`]). + pub from_worker: bool, pub worker: Option, pub worker_started: bool, /// The slices as laid out for (document uid, revision): the canvas draws them every frame. @@ -395,6 +398,8 @@ pub struct VectorcraftApp { pub titlebar_inset: f32, /// Last applied effect (Effect → Apply Last Effect). pub last_effect: Option<(String, serde_json::Value)>, + /// Last confirmed Warp Options (bend, distortion, orientation) for the next new warp dialog. + pub last_warp: Option, /// Commands run through [`Self::run`] so far: the native menu bar reads its rows again when it /// moves ([`native_menu::sync`]). run_count: u64, @@ -525,6 +530,7 @@ impl VectorcraftApp { key: None, last_ms: 0.0, moved: false, + from_worker: false, worker: None, worker_started: false, slices: None, @@ -538,6 +544,7 @@ impl VectorcraftApp { perf: Perf::default(), titlebar_inset: 0.0, last_effect: None, + last_warp: None, run_count: 0, clipboard_out: None, clipboard_published: None, @@ -677,6 +684,7 @@ impl VectorcraftApp { // nor the Live Corners widgets, and the tools do not answer the pointer on them. show_bbox: self.ui.view.bounding_box && self.ui.view.edges, 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, screen: self.screen_frame(), artboard: self.view().map_or(0, |v| v.artboard), @@ -1458,6 +1466,13 @@ impl VectorcraftApp { chrome::doc_tabs(self, ui); } canvas::show(self, ui); + // Over the canvas inside the rulers, so the rulers and scroll bars stay uncovered. + if self.ui.screen_mode < 3 + && !menus::home_showing(self) + && let Some(area) = self.canvas_rect + { + chrome::isolation_bar(self, ui, area); + } }); dock::floating_panel(self, &ctx); floating::show(self, &ctx); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 04ee813c0e..557ddfccd0 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -192,6 +192,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ("view.trimView", "Trim View", "", "{} toggle: hide everything outside the artboards"), ("view.cornerWidget", "Hide Corner Widget", "", "{} toggle the live corner widgets"), ("view.snapToPixel", "Snap to Pixel", "", "{} toggle: drawing and moving land on whole pixels"), + ("view.snapToGlyph", "Snap to Glyph", "", "{} toggle: drawing snaps to live-text baselines and glyph bounds"), ( "view.preciseCursors", "Precise Cursors", @@ -471,7 +472,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; OK runs artboard.setProps), 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 and y, draws one there with them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph (dialog `command` running graph.setType; an error without one), 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 (pt), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), size (pt); OK runs tool.setOption {tool, values})", + "{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; 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 and y, draws one there with them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph (dialog `command` running graph.setType; an error without one), 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 (pt), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), size (pt); 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})", ), ( "ui.colorGuideOptions", @@ -553,7 +554,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.layersPanelOptions", "Panel Options…", "", - "{} open the Layers panel's Panel Options: dialog `layersPanelOptions`, fields layersOnly, rowSize (small|medium|large|other), otherSize (12–100 pt), thumbLayers, thumbGroups, thumbObjects; OK applies them (kept with the UI state)", + "{} open the Layers panel's Panel Options: dialog `layersPanelOptions`, fields layersOnly, locateSelected (Locate Selected Objects, off by default: when the last selected object changes outside the panel, on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as after layer.locate, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off; a change made during a drag is located when the drag ends), rowSize (small|medium|large|other), otherSize (12–100 pt), thumbLayers, thumbGroups, thumbObjects; OK applies them (kept with the UI state)", ), ( "ui.layersExpand", @@ -666,6 +667,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{id?, corners?: [i…]} open Corners for path `id` (default: the selected one) and its corners (anchor indices of the path with its corners uncut, as object.setLiveShape takes them: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; default: the Direct-Selected corners, else every corner) (dialog `corners`: kind (round|invertedRound|chamfer), radius (pt); double-clicking a corner widget opens it too): OK runs object.setLiveShape", ), + ( + "ui.simplifyAuto", + "Auto-Simplify", + "", + "{} the open Simplify slider (Object › Path › Simplify opens it: dialog `simplifySlider` with field `level` 0..100, object.path.simplify's level, 50 as it opens, previewed on the canvas until ui.dialog.confirm keeps it as one undo step; after OK in the Simplify dialog with `retain` ticked, the menu item opens the dialog `simplify` with the fields of that OK instead) moves to the level object.path.simplify {auto: true} picks for the selection and previews it → {level}; an error when the slider isn't open", + ), + ( + "ui.simplifyMoreOptions", + "More Options", + "", + "{} the Simplify dialog (dialog `simplify`: tolerance (pt), angleThreshold, straightLines, showOriginal, retain: ticked, OK makes Object › Path › Simplify open this dialog with these fields next time) takes the open Simplify slider's place, at the slider's tolerance → {tolerance}; an error when the slider isn't open", + ), ( "ui.justification", "Justification…", @@ -830,7 +843,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "file.exportSelection", "Export Selection…", "", - "{multiple?: true} collect the selected objects as assets (assets.add: one per object; false: one of them all) and open Export for Screens on its Assets tab with them checked → {assets: [asset id…]}; document.exportSelection exports the selection in one go instead", + "{multiple?: false} collect the selected objects as assets (assets.add: one of them all, as one image; true: one per object) and open Export for Screens on its Assets tab with them checked → {assets: [asset id…]}; document.exportSelection exports the selection in one go instead", ), ( "css.copy", @@ -1193,6 +1206,7 @@ pub fn run_ui_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Err("no such saved selection".into()), }, "view.snapToPixel" => flag(&mut app.ui.view.snap_to_pixel), + "view.snapToGlyph" => flag(&mut app.ui.view.snap_to_glyph), // The preference itself (General › Use Precise Cursors), so the command, the dialog and the saved // preferences share one value. "view.preciseCursors" => { @@ -1583,6 +1597,8 @@ pub fn run_ui_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Err("no such user library".into()), }, "ui.expandDialog" => crate::dialogs::expand::open(app), + "ui.simplifyAuto" => crate::dialogs::simplify_slider::auto(app), + "ui.simplifyMoreOptions" => crate::dialogs::simplify_slider::more_options(app), "attributes.openUrl" => crate::panels::attributes::open_url(app, p), "ui.javascriptFilesDialog" => crate::panels::svg_interactivity::files_dialog(app, p), "ui.spotColors" => crate::dialogs::spot_colors::open(app), @@ -1650,13 +1666,15 @@ pub fn run_ui_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::save_for_web::open(app), "file.saveForWeb" => crate::dialogs::save_for_web::save(app, p.clone()), "file.saveForWeb.browser" => crate::dialogs::save_for_web::browser_preview(app, p), - // File → Export Selection…: the selection becomes assets, shown checked on Export for - // Screens' Assets tab. - "file.exportSelection" => app.run("assets.add", json!({ "multiple": p.get("multiple").and_then(Value::as_bool).unwrap_or(true) })).map(|r| { - let ids: Vec = r["assets"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect(); - crate::dialogs::open_export_for_screens_assets(app, Some(&ids)); - json!({ "assets": ids }) - }), + // File → Export Selection…: the selection becomes one asset (`multiple: true`: one per + // object), shown checked on Export for Screens' Assets tab. + "file.exportSelection" => { + app.run("assets.add", json!({ "multiple": p.get("multiple").and_then(Value::as_bool).unwrap_or(false) })).map(|r| { + let ids: Vec = r["assets"].as_array().into_iter().flatten().filter_map(Value::as_u64).collect(); + crate::dialogs::open_export_for_screens_assets(app, Some(&ids)); + json!({ "assets": ids }) + }) + } "css.copy" => crate::panels::css_properties::copy(app, p), "css.exportFile" => crate::panels::css_properties::export_file(app, p), // File → Print…: its dialog; with params, print (or save the job as a PDF) without it. @@ -1763,6 +1781,7 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { "view.pixelPreview" => v.pixel_preview, "view.trimView" => v.trim_view, "view.snapToPixel" => v.snap_to_pixel, + "view.snapToGlyph" => v.snap_to_glyph, // Type on a Path effect of the selected path type. "type.pathOptions" if p.get("effect").is_some() => { selected_text(true).is_some_and(|t| p.get("effect").and_then(Value::as_str) == Some(t.path_effect.id())) @@ -2292,6 +2311,7 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { "ui.expandDialog" => app.session.active().is_some_and(|d| !d.selection.is_empty()), "ui.spotColors" => app.session.active().is_some(), "ui.menuDialog" => app.session.active().is_some_and(|d| !d.selection.is_empty()), + "ui.simplifyAuto" | "ui.simplifyMoreOptions" => crate::dialogs::simplify_slider::showing(app), "ui.dxfOptionsDialog" => app.session.active().is_some(), "links.editOriginal" | "links.reveal" => selected_image(app, |im| im.link.is_some()) || selected_placed(app), "ui.placementOptionsDialog" => selected_image(app, |_| true) || selected_placed(app), @@ -2572,6 +2592,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { "Intertwine", vec![c("Make", "object.intertwine.make"), c("Edit", "object.intertwine.edit"), c("Release", "object.intertwine.release")], ), + sub("Objects on Path", vec![c("Attach", "object.objectsOnPath.attach"), c("Expand", "object.objectsOnPath.expand")]), sub( "Blend", vec![ @@ -2896,7 +2917,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { c("Snap to Grid", "view.snapToGrid"), c("Snap to Pixel", "view.snapToPixel"), c("Snap to Point", "view.snapToPoint"), - todo("Snap to Glyph"), + c("Snap to Glyph", "view.snapToGlyph"), Sep, c("New View…", "view.saved.new"), c("Edit Views…", "view.saved.edit"), @@ -3095,6 +3116,10 @@ pub fn context_items(app: &VectorcraftApp) -> Vec { if several && paths { v.push(c("Make Compound Path", "object.compoundPath.make")); } + // Chooses the Objects on Path tool, whose click on a path attaches the selection to it. + if several { + v.push(c("Objects on Path", "object.objectsOnPath.attach")); + } if any(|k| matches!(k, NodeKind::Compound { .. })) { v.push(c("Release Compound Path", "object.compoundPath.release")); } @@ -3364,10 +3389,10 @@ fn menu_dialog(app: &VectorcraftApp, id: &str) -> Option<(&'static str, Value)> // Offset Path opens on the values it was last confirmed with. "object.path.offsetPath" if app.ui.offset_path.is_object() => ("offsetPath", app.ui.offset_path.clone()), "object.path.offsetPath" => ("offsetPath", json!({"offset": "10 pt", "joins": "miter", "miterLimit": 4})), - "object.path.simplify" => ( - "simplify", - json!({"tolerance": "1 pt", "angleThreshold": crate::dialogs::path_ops::ANGLE_THRESHOLD, "straightLines": false, "showOriginal": false, "preview": true}), - ), + // Simplify opens its slider, or the dialog on the fields it was last confirmed with when + // "Open this dialog with these settings next time" was ticked. + "object.path.simplify" if app.ui.simplify.is_object() => ("simplify", app.ui.simplify.clone()), + "object.path.simplify" => (crate::dialogs::simplify_slider::KIND, crate::dialogs::simplify_slider::fields()), "object.path.splitIntoGrid" => { // The grid starts at the size of the selection. let size = diff --git a/crates/ui-egui/src/panels/align.rs b/crates/ui-egui/src/panels/align.rs index c675bce541..9421711930 100644 --- a/crates/ui-egui/src/panels/align.rs +++ b/crates/ui-egui/src/panels/align.rs @@ -37,10 +37,10 @@ pub fn deserialize_align_to<'de, D: serde::Deserializer<'de>>(d: D) -> Result AlignTo { - if n_selected == 1 { AlignTo::Artboard } else { to } + if n_selected == 1 && to != AlignTo::Key { AlignTo::Artboard } else { to } } /// `object.align` params: a single object aligns to the artboard (Illustrator does the same). @@ -112,8 +112,19 @@ pub fn align_buttons(app: &mut VectorcraftApp, ui: &mut Ui, size: f32) { } } -/// Whether the selection has a key object. +/// Whether the selection has a key object or a key guide. fn has_key(app: &VectorcraftApp) -> bool { + app.session.active().is_some_and(|st| st.selection.has_key()) +} + +/// The first selected ruler guide while objects are selected too: the one Align to Key Object +/// makes the key when there is no other object to be it. +fn guide_for_key(app: &VectorcraftApp) -> Option { + app.session.active().filter(|st| !st.selection.is_empty()).and_then(|st| st.selection.guides.first().copied()) +} + +/// Whether the key is an object, which Distribute Spacing spaces from (not a guide). +fn has_key_object(app: &VectorcraftApp) -> bool { app.session.active().is_some_and(|st| st.selection.key.is_some()) } @@ -136,7 +147,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // `spacing` is the Distribute Spacing value. The Distribute Objects and Distribute Spacing // buttons send it while there is a key object. let spacing: f64 = pstate::>(ui.ctx(), "align-spacing").unwrap_or(0.0); - let key = to == AlignTo::Key; + let key = to == AlignTo::Key && has_key_object(app); let sp = if key { Some(spacing) } else { None }; // Two or more objects, or anchor points, which may all be on one path. let distributes = n >= 2 || has_anchors(app); @@ -206,17 +217,21 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { (AlignTo::Key, "dc-alignto-key", tl!("Align to Key Object")), (AlignTo::Artboard, "dc-alignto-artboard", tl!("Align to Artboard")), ] { - // A key object is one of two or more selected objects. - let on = v != AlignTo::Key || n >= 2; + // A key object is one of two or more selected objects, or a guide selected + // with objects. + let on = v != AlignTo::Key || n >= 2 || has_key(app) || guide_for_key(app).is_some(); if widgets::icon_button_enabled(ui, icon, tl!(tip), shown == v, on, 28.0).clicked() { if v == AlignTo::Key { // The topmost selected object becomes the key object, unless // there is one already. The Align To choice stays as it was, and // Align To shows it again once the key is cleared. - if !has_key(app) - && let Some(id) = topmost(app) - { - app.run("select.key", json!({"id": id.0})).ok(); + // With one object, a guide selected with it becomes the key. + if !has_key(app) { + match (topmost(app).filter(|_| n >= 2), guide_for_key(app)) { + (Some(id), _) => app.run("select.key", json!({"id": id.0})).ok(), + (None, Some(g)) => app.run("select.key", json!({"guide": g})).ok(), + (None, None) => None, + }; } } else { app.ui.align_to = v; @@ -263,7 +278,28 @@ mod tests { assert_eq!(p["to"], "artboard"); let p = align_params(json!({"vertical": "top"}), AlignTo::Selection, 3); assert_eq!(p["to"], "selection"); - assert_eq!(align_params(json!({}), AlignTo::Key, 1)["to"], "artboard"); + // One object and a key: the key is a guide (#2143), which it aligns to. + assert_eq!(align_params(json!({}), AlignTo::Key, 1)["to"], "key"); + } + + /// #2143: with one object and a guide selected, Align to Key Object is on and makes the guide + /// the key; Align then lines the object up on it rather than on the artboard. + #[test] + fn align_to_key_object_makes_a_selected_guide_the_key() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let a = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap()["id"].clone(); + app.run("guide.add", json!({"vertical": true, "pos": 120})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run("guide.select", json!({"indexes": [0], "toggle": true})).unwrap(); + let ctx = egui::Context::default(); + let ([_, key, _], left) = panel_buttons(&mut app, &ctx); + click(&ctx, &mut app, key.center(), show); + assert_eq!(app.session.active().unwrap().selection.key_guide, Some(0), "{}", app.ui.status); + assert_eq!(align_to(&app), AlignTo::Key); + click(&ctx, &mut app, left.center(), show); + assert_eq!(left_edge(&app, &a), 120.0, "on the guide, not the artboard: {}", app.ui.status); + assert_eq!(app.session.active().unwrap().doc.guides[0].pos, 120.0); } /// A Shift-click that leaves the key object selected on its own lets the key go, and the align diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 7eb441617f..d024609571 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -625,15 +625,20 @@ fn contents_row(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, label: &str, se chip(ui, cr, n.proxy_paint(stroke, None).map_or(&Paint::None, |(p, ..)| p)); } } - let resp = - resp.on_hover_text(if characters { tl!("Double-click to edit the characters' paint") } else { tl!("Double-click to target the contents") }); + // An image's row has no members to target. + let image = matches!(n.kind, vectorcraft_doc::NodeKind::Image(_)); + let resp = if image { + resp + } else { + resp.on_hover_text(if characters { tl!("Double-click to edit the characters' paint") } else { tl!("Double-click to target the contents") }) + }; if resp.clicked() || resp.double_clicked() { select_row(app, ui.ctx(), Sel::Contents); } if resp.double_clicked() { if characters { app.ui.open_panel = Some("color".into()); - } else { + } else if !image { app.run("appearance.targetContents", json!({})).ok(); } } @@ -734,6 +739,10 @@ fn effect_editor(app: &mut VectorcraftApp, ui: &mut Ui, item: Option, k: let mut change: Option<(String, Value)> = None; let mut edit = false; let built_in = built_in_effect(&e.id); + // A plug-in effect's parameters are labelled, measured and shown as its manifest says. + let plugin = vectorcraft_plugins::effect::installed(&e.id); + let manifest = plugin.as_ref().map(|p| p.manifest()); + let visible = manifest.map(|m| m.visible(¶ms)); let (unit, relative) = (app.session.general_unit(), params.get("relative").and_then(Value::as_bool).unwrap_or(false)); let cmyk = app.session.active().is_some_and(|s| s.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk); egui::Frame::NONE.fill(t.panel_darker).inner_margin(egui::Margin { left: (EYE_W + 12.0) as i8, right: 6, top: 4, bottom: 4 }).show(ui, |ui| { @@ -742,9 +751,16 @@ fn effect_editor(app: &mut VectorcraftApp, ui: &mut Ui, item: Option, k: widgets::dim_label(ui, tl!("No options")); } for (key, v) in ¶ms { + if visible.as_ref().is_some_and(|v| !v.contains(key.as_str())) { + continue; + } + let ui_keys = manifest.and_then(|m| m.param(key)).map(|p| &p.ui); ui.horizontal(|ui| { - let label = param_label(key, built_in); - ui.add_sized(vec2(84.0, 22.0), egui::Label::new(egui::RichText::new(label.as_str()).size(11.5).color(t.text)).truncate()); + let label = ui_keys.and_then(|u| u.label.clone()).unwrap_or_else(|| param_label(key, built_in)); + let shown = ui.add_sized(vec2(84.0, 22.0), egui::Label::new(egui::RichText::new(label.as_str()).size(11.5).color(t.text)).truncate()); + if let Some(help) = ui_keys.and_then(|u| u.help.as_deref()) { + shown.on_hover_text(help); + } if e.id == "stylize.dropShadow" && key == "shade" { let cur = v.as_str().unwrap_or_default(); for (label, value) in crate::dialogs::SHADES { @@ -766,6 +782,19 @@ fn effect_editor(app: &mut VectorcraftApp, ui: &mut Ui, item: Option, k: } return; } + // A plug-in's number list is typed as its dialog's is: "45, 135". + if let Some(spec) = manifest.and_then(|m| m.param(key)).map(|p| &p.spec) + && matches!(spec, vectorcraft_plugins::manifest::ParamSpec::NumberList { .. }) + { + let typed = widgets::exact_text_field(ui, ("fx", item, k, key.as_str()), &crate::dialogs::number_list_text(v), 90.0); + if let Some(list) = typed.and_then(|text| crate::dialogs::read_number_list(&text, spec)) { + change = Some((key.clone(), list)); + } + if let Some(unit) = ui_keys.and_then(|u| u.unit.as_deref()) { + widgets::dim_label(ui, unit); + } + return; + } // Only our own effects show a `mode` parameter as the blend mode dropdown; a plug-in's `mode` stays a plain field. if built_in && let Some(cur) = widgets::blend_param(key, v) { if let Some(m) = widgets::blend_param_dropdown(ui, ("fx-blend", item, k, key.as_str()), cur) { @@ -781,10 +810,11 @@ fn effect_editor(app: &mut VectorcraftApp, ui: &mut Ui, item: Option, k: } Value::Number(n) => { let (x, id) = (n.as_f64().unwrap_or(0.0), ("fx", item, k, key.as_str())); + let suffix = ui_keys.and_then(|u| u.unit.as_deref()).map(crate::dialogs::unit_suffix).unwrap_or_default(); let nx = if vectorcraft_effects::is_length(&e.id, key, relative) { widgets::num_field(ui, id, Some(x), unit, 70.0) } else { - widgets::plain_field(ui, id, x, "", 2, 70.0) + widgets::plain_field(ui, id, x, &suffix, 2, 70.0) }; if let Some(nx) = nx { change = Some((key.clone(), json!(nx))); @@ -1159,6 +1189,46 @@ mod tests { assert!(texts.iter().any(|s| s == "screen") && !texts.iter().any(|s| s == "Screen"), "{texts:?}"); } + /// A plug-in effect's editor labels its parameters, shows their units and leaves out those whose + /// `visibleWhen` isn't met, as the effect's dialog does, and reads a typed number list the same + /// way. + #[test] + fn a_plug_in_effect_s_editor_follows_its_manifest() { + use vectorcraft_plugins::wat as tpl; + let params = r#"{"outline":{"type":"bool","default":true,"label":"Outline"}, + "spacing":{"type":"number","min":0.1,"max":10,"default":1.5,"label":"Spacing","unit":"mm","help":"Distance between the lines."}, + "angles":{"type":"numberList","min":0,"max":360,"default":[45,135],"minItems":1,"maxItems":4,"unit":"°"}, + "width":{"type":"number","min":0,"max":10,"default":0.5,"label":"Width","unit":"pt","visibleWhen":{"outline":[true]}}}"#; + let src = tpl::module(&tpl::manifest("test.ui.inlinekeys", "effect", params), tpl::ECHO, "", 1); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wat::parse_str(src).unwrap())})).unwrap(); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("effect.apply", json!({"effect": "plugin.test.ui.inlinekeys"})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + set_pstate(&ctx, "ap-fx-open-None-0", true); + let texts = shown_texts(&mut app, &ctx); + for shown in ["Spacing", "1.5 mm", "Angles", "45, 135", "°", "Width", "0.5 pt"] { + assert!(texts.iter().any(|s| s == shown), "no {shown:?} in {texts:?}"); + } + assert!(!texts.iter().any(|s| s == "spacing" || s == "width"), "the labels replace the names: {texts:?}"); + // Without the outline, its width isn't shown. + app.run("effect.setParams", json!({"item": null, "index": 0, "params": {"outline": false}})).unwrap(); + let texts = shown_texts(&mut app, &ctx); + assert!(!texts.iter().any(|s| s == "Width") && texts.iter().any(|s| s == "Spacing"), "{texts:?}"); + // A list typed in the field: separated by a semicolon and a space, and clamped. + click_text(&mut app, &ctx, "45, 135"); + let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; + panel_frame(&mut app, &ctx, vec![key(egui::Key::A, egui::Modifiers::COMMAND)]); + panel_frame(&mut app, &ctx, vec![egui::Event::Text("10; 400 20".into())]); + panel_frame(&mut app, &ctx, vec![key(egui::Key::Enter, egui::Modifiers::NONE)]); + panel_frame(&mut app, &ctx, vec![]); + let angles = app.session.doc().unwrap().doc.node(NodeId(id)).unwrap().appearance.effects[0].params["angles"].clone(); + assert_eq!(angles, json!([10.0, 360.0, 20.0])); + app.run("plugin.remove", json!({"id": "test.ui.inlinekeys"})).unwrap(); + } + /// Glass with a loaded texture lists Loaded Texture in its Texture menu, as its dialog does. #[test] fn the_effect_editor_lists_a_loaded_glass_texture() { @@ -1389,6 +1459,22 @@ mod tests { assert_eq!(rows(frame(&mut app)), ["Fill:", "Characters"]); } + #[test] + fn images_show_a_contents_row_with_new_fills_and_strokes_below_it() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let run = |app: &mut VectorcraftApp, id: &str, p: Value| app.session.execute(id, &p).unwrap(); + run(&mut app, "file.new", json!({"width": 100, "height": 100})); + let rows = |t: Vec| t.into_iter().filter(|t| ["Fill:", "Stroke:", "Contents"].contains(&t.as_str())).collect::>(); + let mut png = vec![]; + image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 255])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + run(&mut app, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png)})); + assert_eq!(rows(frame(&mut app)), ["Contents"]); + run(&mut app, "appearance.addStroke", json!({})); + assert_eq!(rows(frame(&mut app)), ["Contents", "Stroke:"]); + } + #[test] fn drops_move_items_across_the_contents_row_and_the_row_itself() { use vectorcraft_doc::FillLayer; diff --git a/crates/ui-egui/src/panels/artboards.rs b/crates/ui-egui/src/panels/artboards.rs index 7e8a4c2dac..81f5e443dd 100644 --- a/crates/ui-egui/src/panels/artboards.rs +++ b/crates/ui-egui/src/panels/artboards.rs @@ -8,6 +8,7 @@ use egui::{Sense, Ui, pos2, vec2}; use serde_json::{Value, json}; +use vectorcraft_geom::Rect; use super::{alt_held, pstate, set_pstate}; use crate::theme::Tokens; @@ -110,7 +111,7 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { "width" => [None, None, Some(nv), None], _ => [None, None, None, Some(nv)], }; - super::transform::set_artboard(app, i, r, refi, xywh, link); + super::transform::set_artboard(app, i, refi, xywh, link); } } true @@ -153,6 +154,53 @@ pub(crate) fn picked(app: &VectorcraftApp, n: usize) -> Vec { all } +/// The artboards a new size for artboard `i` goes to: the selected artboards ([`picked`]) when +/// `i` is one of them, else `i` alone. +pub(crate) fn resized_with(app: &VectorcraftApp, i: usize) -> Vec { + let all = picked(app, app.session.active().map_or(0, |d| d.doc.artboards.len())); + if all.contains(&i) { all } else { vec![i] } +} + +/// The `artboard.setProps` params that set `entries` (each an artboard's `index` and its fields) +/// with `common` (an object: `scaleArt`, `moveArt`), in one undo step: the one entry's fields +/// beside `common`, or an `artboards` list of several beside it; None for no entry. +pub(crate) fn set_props_params(common: Value, mut entries: Vec) -> Option { + let mut p = common; + let o = p.as_object_mut()?; + match entries.len() { + 0 => return None, + 1 => { + if let Value::Object(e) = entries.remove(0) { + o.extend(e); + } + } + _ => { + o.insert("artboards".into(), Value::Array(entries)); + } + } + Some(p) +} + +/// Run `artboard.setProps` with `common` on each artboard of `indices` that `entry` gives fields for +/// (from its index and rectangle), in one undo step ([`set_props_params`]). Nothing runs when it +/// gives none. +pub(crate) fn set_props( + app: &mut VectorcraftApp, + indices: &[usize], + common: Value, + entry: impl Fn(usize, Rect) -> Option, +) -> Result { + let entries: Vec = app + .session + .active() + .map(|d| indices.iter().filter_map(|&i| d.doc.artboards.get(i).and_then(|a| entry(i, a.rect))).collect()) + .unwrap_or_default(); + match set_props_params(common, entries) { + Some(p) => app.run("artboard.setProps", p), + None => Ok(Value::Null), + } +} + /// Delete the picked artboards and select a remaining one. pub(crate) fn delete_selected(app: &mut VectorcraftApp) { let n = app.session.active().map_or(0, |d| d.doc.artboards.len()); diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index c7252993ff..7838967daf 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -535,7 +535,7 @@ pub(crate) fn font_pickers(app: &mut VectorcraftApp, ui: &mut Ui, s: &CharStyle, /// The Variable Font button, `width` wide, shown when the font of style `s` is a variable font: it /// opens the font's axis sliders ([`axis_sliders`]). -fn variable_font(app: &mut VectorcraftApp, ui: &mut Ui, s: &CharStyle, width: f32) { +pub(crate) fn variable_font(app: &mut VectorcraftApp, ui: &mut Ui, s: &CharStyle, width: f32) { let Some(face) = vectorcraft_text::FontDb::global().face_version(&s.font_family, &s.font_style, s.font_version.as_deref()) else { return }; if face.axes().iter().all(|a| a.hidden) { return; diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index 2213ed9340..32c4468296 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -1044,7 +1044,7 @@ mod tests { // A spot swatch tile dropped on a stop links it: editing the swatch recolours the stop. app.run("swatch.new", json!({"name": "Ink", "color": "#cc0066", "spot": true})).unwrap(); let ink = app.session.doc().unwrap().doc.swatch("Ink").unwrap().paint.clone(); - egui::DragAndDrop::set_payload(&p.ctx, PanelDrag::Paint { paint: ink, params: json!({"swatch": "Ink"}), rows: None }); + egui::DragAndDrop::set_payload(&p.ctx, PanelDrag::Paint { paint: ink, params: json!({"swatch": "Ink"}), rows: None, library: None }); p.frame(&mut app, vec![Event::PointerMoved(a)], Modifiers::NONE); p.frame( &mut app, diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index d20e54a220..6c6ba27915 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -351,7 +351,12 @@ fn zone_input(ui: &Ui, zone: &Response, d: &Document, ev: &mut Events) { PanelDrag::GraphicStyle(n) => (Some(n), None), PanelDrag::Art(ids) => (None, ids.first().copied()), PanelDrag::Appearance(id) => (None, Some(*id)), - PanelDrag::Paint { .. } | PanelDrag::Symbol(_) | PanelDrag::Brush { .. } | PanelDrag::LibraryGraphic { .. } => (None, None), + PanelDrag::Paint { .. } + | PanelDrag::Symbol(_) + | PanelDrag::Brush { .. } + | PanelDrag::LibraryGraphic { .. } + | PanelDrag::LibraryItem { .. } + | PanelDrag::LibraryGroup { .. } => (None, None), }; if style.is_none() && source.is_none() { return; diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index b7974e6c31..3871b7df78 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -66,6 +66,11 @@ const SQUARE_X: f32 = 11.0; pub struct PanelOptions { /// Show Layers Only: no rows for groups and objects. pub layers_only: bool, + /// Locate Selected Objects (off by default): when the last selected object changes outside the + /// panel, on the canvas or by a command, the panel opens the rows around it and scrolls to its + /// row, as after Locate Object, without highlighting the row. When Show Layers Only, a search or + /// the filter leaves the object without a row, the panel opens no rows for it. + pub locate_selected: bool, /// Row height in points: [`ROW_SMALL`], [`ROW_MEDIUM`], [`ROW_LARGE`] or another (12–100). pub row_size: f32, /// Thumbnails on layer, group and object rows. @@ -80,7 +85,7 @@ pub const ROW_LARGE: f32 = 40.0; impl Default for PanelOptions { fn default() -> Self { - Self { layers_only: false, row_size: ROW_MEDIUM, thumb_layers: true, thumb_groups: true, thumb_objects: true } + Self { layers_only: false, locate_selected: false, row_size: ROW_MEDIUM, thumb_layers: true, thumb_groups: true, thumb_objects: true } } } @@ -538,16 +543,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let seen: Vec = ui.data(|d| d.get_temp(key("seen"))).unwrap_or_default(); let mut reveal = None; if rows != seen { - let around: Vec = - rows.iter().flat_map(|r| doc.ancestry(*r).unwrap_or_default().split_last().map(|(_, a)| a.to_vec()).unwrap_or_default()).collect(); - if let Some(st) = app.session.active_mut() { - for a in around { - st.layers_open.set(a, true); - } - } + open_around(app, &doc, &rows); reveal = rows.first().copied(); ui.data_mut(|d| d.insert_temp(key("seen"), rows.clone())); } + let highlighted = reveal.is_some(); // A new active layer (a canvas selection highlights no row): reveal it too, unless a row // highlighted in the panel holds the view. let seen_current: Option = ui.data(|d| d.get_temp(key("seen-current"))).flatten(); @@ -565,6 +565,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.data_mut(|d| d.insert_temp(key("seen-current"), current)); } + // With Locate Selected Objects on, an object selected anew outside the panel (below). + let located = newly_selected(app, ui).filter(|_| !highlighted); // Search All, and the Filter button at its right. let query = ui .horizontal(|ui| { @@ -577,6 +579,16 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .inner .trim() .to_lowercase(); + // The located object, when it has a row once the rows around it are open (Show Layers Only, a + // search or the filter can leave it out): those rows open, and its row is revealed instead of + // the row revealed above. Otherwise nothing opens. + let located = located.filter(|id| { + app.session.active().is_some_and(|st| listed_when_opened(&doc, &st.layers_open, &app.ui.layers_panel, &query, &app.ui.layers_filter, *id)) + }); + if let Some(id) = located { + open_around(app, &doc, &[id]); + } + let reveal = located.or(reveal); let Some(st) = app.session.active() else { return }; let list = rows_of_doc(ui, st, &app.ui.layers_panel, &query, &app.ui.layers_filter); let view = View { @@ -618,6 +630,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { st.layers_open.set(id, open); } } + let selected = last_selected(app); // The column drag: live while it lasts, one undo step when the button is released. let released = ui.input(|i| i.pointer.any_released()); // Layers dragged into the empty space under the last row go below the bottom layer (there is @@ -687,6 +700,63 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { for (c, p) in out.actions { app.run(&c, p).ok(); } + see_selection(app, ui, selected); +} + +/// Open the layers and groups around rows `ids`. +fn open_around(app: &mut VectorcraftApp, doc: &Document, ids: &[NodeId]) { + let around: Vec = + ids.iter().flat_map(|r| doc.ancestry(*r).unwrap_or_default().split_last().map(|(_, a)| a.to_vec()).unwrap_or_default()).collect(); + if let Some(st) = app.session.active_mut() { + for a in around { + st.layers_open.set(a, true); + } + } +} + +/// Whether [`list_rows`] gives `id` a row once the layers and groups around it are open as well as +/// `open`. Only the rows of `id`'s top-level layer are listed. +fn listed_when_opened(doc: &Document, open: &OpenRows, opts: &PanelOptions, query: &str, filter: &Filter, id: NodeId) -> bool { + let Some(ancestry) = doc.ancestry(id) else { return false }; + let Some(layer) = doc.layers.iter().find(|l| ancestry.first() == Some(&l.id)) else { return false }; + if doc.mask_edit.is_some_and(|m| m.layer != layer.id) { + return false; + } + let mut open = open.clone(); + for a in ancestry.split_last().map(|(_, a)| a).unwrap_or_default() { + open.set(*a, true); + } + let mut rows = vec![]; + push_rows(layer, 0, false, (Color32::PLACEHOLDER, true), (&open, opts, query, filter, doc), &mut rows); + rows.iter().any(|r| r.node.id == id && r.guide.is_none()) +} + +/// The active document's uid and its last selected object, the one Locate Object locates. +fn last_selected(app: &VectorcraftApp) -> Option<(u64, Option)> { + app.session.active().map(|st| (st.uid, st.selection.objects.last().copied())) +} + +/// Locate Selected Objects: the object to locate in this frame. With the option on, that is the +/// last selected object when it differs from the one noted in an earlier frame for the same +/// document. [`see_selection`] notes the panel's own changes, so only a change made on the canvas +/// or by a command is located. This function notes nothing during a drag, so a selection made on +/// the canvas during one is located when the drag ends. When another document becomes active, +/// nothing is located. +fn newly_selected(app: &VectorcraftApp, ui: &Ui) -> Option { + let busy = app.session.active().is_some_and(|st| st.interaction.is_some()) || app.session.tool_busy(); + let now = last_selected(app).filter(|_| !busy)?; + let was = ui.data(|d| d.get_temp::<(u64, Option)>(key("selected"))); + ui.data_mut(|d| d.insert_temp(key("selected"), now)); + let anew = was.is_some_and(|w| w.0 == now.0 && w.1 != now.1); + now.1.filter(|_| anew && app.ui.layers_panel.locate_selected) +} + +/// Note the selection as seen when the panel's rows, buttons or menu changed it (`before`: what +/// [`last_selected`] gave before they ran), so Locate Selected Objects does not locate it. +fn see_selection(app: &VectorcraftApp, ui: &Ui, before: Option<(u64, Option)>) { + if let Some(now) = last_selected(app).filter(|now| Some(*now) != before) { + ui.data_mut(|d| d.insert_temp(key("selected"), now)); + } } /// The Filter button, lit while a filter is on, and its popup: Clear All, the object kinds under @@ -1586,7 +1656,9 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { Some(("Save Selection", "", ..)) => save_selection_menu(app, ui), Some((label, cmd, p, enabled, checked)) => { if widgets::menu_item(ui, label, enabled, checked) { + let selected = last_selected(app); app.run(cmd, p).ok(); + see_selection(app, ui, selected); } } } @@ -1626,7 +1698,9 @@ fn save_selection_menu(app: &mut VectorcraftApp, ui: &mut Ui) { } for name in names { if widgets::menu_item_name(ui, &name, true, false) { + let selected = last_selected(app); app.run("select.recall", json!({ "name": name })).ok(); + see_selection(app, ui, selected); ui.close(); } } @@ -2741,6 +2815,293 @@ mod tests { assert_eq!(app.session.active().unwrap().current_layer(), Some(sub)); } + // ---- Locate Selected Objects (Panel Options) ---- + + /// A layer of `n` groups of one path each, with only the layer open, as a document opens → + /// (app, layer, the paths in stacking order, so the first is in the bottom row). The path in + /// group `i` is named `Path {i}`. + fn groups_of_one(n: usize) -> (VectorcraftApp, NodeId, Vec) { + use vectorcraft_doc::Appearance; + use vectorcraft_geom::{Rect, shapes}; + let mut d = Document::new(1000.0, 1000.0); + let mut groups = vec![]; + let mut paths = vec![]; + for i in 0..n { + let r = Rect::new(0.0, i as f64, 1.0, i as f64 + 1.0); + let mut path = Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default()); + path.name = Some(format!("Path {i}")); + paths.push(path.id); + groups.push(Arc::new(Node::group(d.alloc_id(), vec![Arc::new(path)]))); + } + *Arc::make_mut(&mut d.layers[0]).children_mut().unwrap() = groups; + let layer = d.layers[0].id; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.add_document(d, None); + (app, layer, paths) + } + + /// One frame of the panel in a 300 × 800 window, one second after the previous frame: the + /// centers of the target circles, top row first, and whether `name` is drawn. + fn tall_frame(app: &mut VectorcraftApp, ctx: &egui::Context, name: &str) -> (Vec, bool) { + let time = ctx.input(|i| i.time) + 1.0; + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 800.0)); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + let found = out.shapes.iter().any(|c| matches!(&c.shape, egui::Shape::Text(t) if t.galley.text() == name)); + let mut circles: Vec = out + .shapes + .iter() + .filter_map(|c| match &c.shape { + egui::Shape::Circle(cs) if cs.radius == 5.0 => Some(cs.center), + _ => None, + }) + .collect(); + circles.sort_by(|a, b| a.y.total_cmp(&b.y)); + (circles, found) + } + + /// Without Locate Selected Objects (the default), an object selected outside the panel leaves + /// the open rows and the scroll position as they were. + #[test] + fn without_the_option_a_selection_leaves_the_rows_and_the_scroll_as_they_were() { + let (mut app, layer, paths) = groups_of_one(500); + let ctx = egui::Context::default(); + let (before, _) = tall_frame(&mut app, &ctx, ""); + // The bottom row's path: out of view, in a closed group. + app.session.execute("select.set", &json!({"ids": [paths[0].0]})).unwrap(); + for _ in 0..4 { + let (circles, found) = tall_frame(&mut app, &ctx, "Path 0"); + assert!(!found); + assert_eq!(circles, before, "nothing opens or scrolls"); + } + let st = app.session.active().unwrap(); + let group = st.doc.parent_of(paths[0]).unwrap(); + assert!(st.layers_open.contains(layer) && !st.layers_open.contains(group)); + } + + /// With Locate Selected Objects on, an object selected outside the panel is located as Locate + /// Object locates it: the layer and the group around it open and its row is scrolled into + /// view. The highlighted row stays as it was. + #[test] + fn with_the_option_a_selected_object_is_opened_and_scrolled_into_view() { + let (mut app, layer, paths) = groups_of_one(500); + app.ui.layers_panel.locate_selected = true; + let ctx = egui::Context::default(); + let top = app.session.active().unwrap().doc.parent_of(paths[499]).unwrap(); + app.session.execute("layer.highlight", &json!({"ids": [top.0]})).unwrap(); + tall_frame(&mut app, &ctx, ""); + expand(&mut app, &json!({"ids": [layer.0], "open": false})).unwrap(); + assert_eq!(tall_frame(&mut app, &ctx, "").0.len(), 1, "only the layer's row"); + app.session.execute("select.set", &json!({"ids": [paths[0].0]})).unwrap(); + let found = (0..4).any(|_| tall_frame(&mut app, &ctx, "Path 0").1); + let st = app.session.active().unwrap(); + let group = st.doc.parent_of(paths[0]).unwrap(); + assert!(st.layers_open.contains(layer) && st.layers_open.contains(group), "the layer and the group open"); + assert!(found, "the row is scrolled into view"); + assert_eq!(st.highlighted_rows(), [top], "the highlighted row stays"); + } + + /// With Locate Selected Objects on, the panel's own clicks locate nothing: a Shift-click + /// highlights the rows down to the one it clicks, and Shift-clicking selection squares selects + /// art in a closed sublayer without opening it. An object then selected outside the panel is + /// located, and the highlighted rows stay. + #[test] + fn with_the_option_the_panels_own_clicks_locate_nothing() { + let (mut app, [layer, sub, g, b, _, c]) = nested(); + app.ui.layers_panel.locate_selected = true; + expand(&mut app, &json!({"ids": [sub.0, g.0], "open": false})).unwrap(); + let ctx = egui::Context::default(); + // Rows top down: Layer 1, Sub (closed), c. + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 3); + let name = |i: usize| egui::pos2(150.0, circles[i].y); + let square = |i: usize| circles[i] + vec2(TARGET_X - SQUARE_X, 0.0); + click_with(&mut app, &ctx, name(0), egui::Modifiers::NONE); + click_with(&mut app, &ctx, name(2), egui::Modifiers::SHIFT); + assert_eq!(rows_of(&app), [layer, sub, c], "both rows clicked and the one between them"); + click_with(&mut app, &ctx, square(2), egui::Modifiers::SHIFT); + click_with(&mut app, &ctx, square(1), egui::Modifiers::SHIFT); + let st = app.session.active().unwrap(); + assert!(st.selection.objects.len() >= 3 && st.selection.objects.contains(&c), "c and Sub's art are selected"); + let (after, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(after, circles, "no row opens and nothing scrolls"); + assert_eq!(rows_of(&app), [layer, sub, c]); + // Selected outside the panel: b's sublayer and group open, and the rows stay highlighted. + app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + assert_eq!(frame(&mut app, &ctx, vec![], false).0.len(), 6); + assert_eq!(rows_of(&app), [layer, sub, c]); + } + + /// With Locate Selected Objects on, a selection the panel menu changes is not located: Delete + /// Selection deletes the highlighted object, and the object left selected stays in its closed + /// sublayer and group. + #[test] + fn with_the_option_the_panel_menu_locates_nothing() { + let (mut app, [_, sub, g, b, _, c]) = nested(); + app.ui.layers_panel.locate_selected = true; + app.session.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, vec![], false); + expand(&mut app, &json!({"ids": [sub.0, g.0], "open": false})).unwrap(); + app.session.execute("layer.highlight", &json!({"ids": [c.0]})).unwrap(); + assert_eq!(frame(&mut app, &ctx, vec![], false).0.len(), 3, "Layer 1, Sub (closed) and c"); + let menu_frame = |app: &mut VectorcraftApp, events| super::super::tests_appearance::frame_events(&ctx, app, events, menu); + let at = menu_frame(&mut app, vec![]).iter().find(|(t, _)| t.trim() == "Delete Selection").map(|(_, r)| r.center()).unwrap(); + for e in [egui::Event::PointerMoved(at), button(at, true), button(at, false)] { + menu_frame(&mut app, vec![e]); + } + assert_eq!(app.session.active().unwrap().selection.objects, [b], "c is deleted and b stays selected"); + assert_eq!(frame(&mut app, &ctx, vec![], false).0.len(), 2, "Sub stays closed"); + } + + /// With Locate Selected Objects on, a saved selection recalled from the panel menu's Save + /// Selection submenu is not located: the recalled object stays in its closed sublayer and group. + #[test] + fn with_the_option_a_selection_recalled_from_the_panel_menu_is_not_located() { + let (mut app, [_, sub, g, b, _, c]) = nested(); + app.ui.layers_panel.locate_selected = true; + app.run("select.set", json!({"ids": [b.0]})).unwrap(); + app.run("select.save", json!({"name": "Kept"})).unwrap(); + app.run("select.set", json!({"ids": [c.0]})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + frame(&mut app, &ctx, vec![], false); + expand(&mut app, &json!({"ids": [sub.0, g.0], "open": false})).unwrap(); + assert_eq!(frame(&mut app, &ctx, vec![], false).0.len(), 3, "Layer 1, Sub (closed) and c"); + let menu_frame = |app: &mut VectorcraftApp, events| super::super::tests_appearance::frame_events(&ctx, app, events, menu); + let at = |texts: &[(String, egui::Rect)], label: &str| texts.iter().find(|(t, _)| t.trim() == label).map(|(_, r)| r.center()); + let sub_menu = at(&menu_frame(&mut app, vec![]), "Save Selection").expect("the Save Selection submenu"); + for e in [egui::Event::PointerMoved(sub_menu), button(sub_menu, true), button(sub_menu, false)] { + menu_frame(&mut app, vec![e]); + } + let item = at(&menu_frame(&mut app, vec![]), "Kept").expect("the saved selection's item"); + for e in [egui::Event::PointerMoved(item), button(item, true), button(item, false)] { + menu_frame(&mut app, vec![e]); + } + assert_eq!(app.session.active().unwrap().selection.objects, [b], "the saved selection is recalled"); + assert_eq!(frame(&mut app, &ctx, vec![], false).0.len(), 3, "Sub stays closed"); + } + + /// With Locate Selected Objects on, the object selected in a document that becomes active is + /// not located; an object selected after that is. Neither document has highlighted rows, so + /// the switch reveals no row of its own. + #[test] + fn with_the_option_a_document_becoming_active_locates_nothing() { + let (mut app, [_, sub, g, b, a, _]) = nested(); + app.ui.layers_panel.locate_selected = true; + app.session.execute("layer.highlight", &json!({"ids": []})).unwrap(); + app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![], false); + expand(&mut app, &json!({"ids": [sub.0, g.0], "open": false})).unwrap(); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + frame(&mut app, &ctx, vec![], false); + app.session.execute("document.activate", &json!({"index": 0})).unwrap(); + assert_eq!(frame(&mut app, &ctx, vec![], false).0.len(), 3, "b's sublayer and group stay closed"); + app.session.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + assert_eq!(frame(&mut app, &ctx, vec![], false).0.len(), 5, "a's sublayer opens"); + } + + /// With Locate Selected Objects on, the copies an Alt-drag selects are located once the drag + /// ends, not while it lasts. + #[test] + fn with_the_option_a_selection_made_during_a_drag_is_located_when_it_ends() { + let (mut app, [_, sub, g, b, ..]) = nested(); + app.ui.layers_panel.locate_selected = true; + app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![], false); + expand(&mut app, &json!({"ids": [sub.0, g.0], "open": false})).unwrap(); + app.session.begin_interaction("Move").unwrap(); + for i in 1..=3 { + app.session.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, i * 10, 0], "copy": true})).unwrap(); + assert_eq!(frame(&mut app, &ctx, vec![], false).0.len(), 3, "nothing opens while the drag lasts"); + } + app.session.commit_interaction().unwrap(); + let st = app.session.active().unwrap(); + let copy = st.selection.objects.last().copied().unwrap(); + assert!(copy != b && st.doc.parent_of(copy) == Some(g), "the copy is selected, in b's group"); + assert_eq!(frame(&mut app, &ctx, vec![], false).0.len(), 7, "Sub and the group open on the copy's row"); + } + + /// With Locate Selected Objects on, art selected outside the panel in another layer is + /// located: the selection makes that layer the active one, and the panel scrolls to the art's + /// row, not to the layer's row. + #[test] + fn with_the_option_the_located_object_is_revealed_instead_of_its_active_layer() { + let (mut app, layer, paths) = groups_of_one(500); + app.ui.layers_panel.locate_selected = true; + app.session.execute("layer.new", &json!({})).unwrap(); + assert_ne!(app.session.active().unwrap().current_layer(), Some(layer)); + let ctx = egui::Context::default(); + tall_frame(&mut app, &ctx, ""); + app.session.execute("select.set", &json!({"ids": [paths[0].0]})).unwrap(); + assert_eq!(app.session.active().unwrap().current_layer(), Some(layer), "the path's layer is the active one"); + let found = (0..4).any(|_| tall_frame(&mut app, &ctx, "Path 0").1); + let st = app.session.active().unwrap(); + let group = st.doc.parent_of(paths[0]).unwrap(); + assert!(st.layers_open.contains(group), "the group opens"); + assert!(found, "the path's row is scrolled into view"); + } + + /// With Locate Selected Objects and Show Layers Only on, art selected outside the panel has no + /// row, so the panel scrolls to the row of the layer that the selection makes the active one. + #[test] + fn with_the_option_and_show_layers_only_the_active_layer_is_revealed() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.ui.layers_panel.locate_selected = true; + app.ui.layers_panel.layers_only = true; + let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap(); + run(&mut app, "file.new", json!({"width": 100, "height": 100})); + let rect = |app: &mut VectorcraftApp| run(app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 5, "height": 5}))["id"].as_u64().unwrap(); + let bottom = rect(&mut app); + for _ in 0..59 { + run(&mut app, "layer.new", json!({})); + rect(&mut app); + } + run(&mut app, "select.none", json!({})); + let doc = app.session.active().unwrap().doc.clone(); + let name = doc.node(doc.layer_of(NodeId(bottom)).unwrap()).unwrap().display_name(); + let ctx = egui::Context::default(); + assert!(!(0..4).any(|_| tall_frame(&mut app, &ctx, &name).1), "the bottom layer's row is out of view"); + run(&mut app, "select.set", json!({"ids": [bottom]})); + assert!((0..4).any(|_| tall_frame(&mut app, &ctx, &name).1), "the active layer's row is scrolled into view"); + } + + /// With Locate Selected Objects on, art selected outside the panel that Show Layers Only or the + /// filter leaves without a row opens nothing, so its group stays closed once the panel lists + /// every row again. Art the filter keeps has its group opened. + #[test] + fn with_the_option_art_the_panel_does_not_list_opens_nothing() { + let (mut app, _, paths) = groups_of_one(500); + app.ui.layers_panel.locate_selected = true; + let ctx = egui::Context::default(); + let open = |app: &VectorcraftApp, i: usize| { + let st = app.session.active().unwrap(); + st.layers_open.contains(st.doc.parent_of(paths[i]).unwrap()) + }; + let locate = |app: &mut VectorcraftApp, i: usize| { + app.session.execute("select.set", &json!({"ids": [paths[i].0]})).unwrap(); + for _ in 0..4 { + tall_frame(app, &ctx, ""); + } + }; + tall_frame(&mut app, &ctx, ""); + app.ui.layers_panel.layers_only = true; + locate(&mut app, 0); + app.ui.layers_panel.layers_only = false; + tall_frame(&mut app, &ctx, ""); + assert!(!open(&app, 0), "Show Layers Only: the group stays closed"); + app.ui.layers_filter = Filter { objects: vec![ObjectKind::Text], layers: vec![] }; + locate(&mut app, 1); + assert!(!open(&app, 1), "a filter that leaves the path out: the group stays closed"); + app.ui.layers_filter = Filter { objects: vec![ObjectKind::Paths], layers: vec![] }; + locate(&mut app, 2); + assert!(open(&app, 2), "a filter that keeps the path: the group opens"); + } + /// A layer of 2,000 groups of 10 paths with every row open: one frame lays out only the rows /// in view, and a row highlighted far below them is scrolled to. #[test] diff --git a/crates/ui-egui/src/panels/libraries.rs b/crates/ui-egui/src/panels/libraries.rs index f0ec3093ab..8fa48da92e 100644 --- a/crates/ui-egui/src/panels/libraries.rs +++ b/crates/ui-egui/src/panels/libraries.rs @@ -8,6 +8,12 @@ //! The search field filters the items by name; items can be moved into user-named groups, shown as //! collapsible sections after the ungrouped items; and the panel menu exports the library to a //! `.vclibrary` file and imports one as a new library (#926). +//! +//! The list fills the panel down to its bottom bar and scrolls (also while a drag nears its top or +//! bottom edge). An item dragged within it lands before or after another of its kind, in that one's +//! group (`library.moveItem` with `before`/`after`), or, dropped elsewhere on a group or on the +//! ungrouped items, goes into that group or out of its own; a group dragged by its header goes +//! before or after another group (`library.moveGroup`). use std::collections::HashMap; @@ -24,6 +30,13 @@ use crate::{VectorcraftApp, icons}; const TILE: f32 = 56.0; /// The size of a colour chip. const CHIP: f32 = 22.0; +/// The height under the list the bottom bar takes (its divider and buttons) until it has been +/// measured. +const BAR: f32 = 42.0; +/// The least height the list takes. +const MIN_LIST: f32 = 140.0; +/// How near the list's top or bottom edge a drag scrolls it. +const EDGE: f32 = 28.0; /// The current library: its id and a copy of it (the panel menu acts on it after reading). fn current(app: &VectorcraftApp) -> Option<(String, Library)> { @@ -75,6 +88,25 @@ enum Act { RenameGroup(String), } +/// What a drag in the panel holds of the library shown: one of its items, or one of its groups +/// (by the group's header). +#[derive(Clone, Debug, PartialEq)] +enum Grab { + Item(ItemKind, String), + Group(String), +} + +/// The item or group of library `library` that `drag` holds, if it holds one. +fn grabbed(drag: &PanelDrag, library: &str) -> Option { + match drag { + PanelDrag::Paint { library: Some((l, item)), .. } if l == library => Some(Grab::Item(ItemKind::Color, item.clone())), + PanelDrag::LibraryGraphic { library: l, item } if l == library => Some(Grab::Item(ItemKind::Graphic, item.clone())), + PanelDrag::LibraryItem { library: l, kind, item } if l == library => Some(Grab::Item(*kind, item.clone())), + PanelDrag::LibraryGroup { library: l, group } if l == library => Some(Grab::Group(group.clone())), + _ => None, + } +} + /// What the item list draws from. struct Items<'a> { library: &'a str, @@ -82,6 +114,8 @@ struct Items<'a> { /// The group of each grouped item ([`Library::group_index`]). groups: HashMap<(ItemKind, &'a str), usize>, fill_active: bool, + /// What a drag in progress holds of this library. + grab: Option, } impl Items<'_> { @@ -121,7 +155,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let query = query.trim().to_lowercase(); let searching = !query.is_empty(); let shown = |name: &str| !searching || name.to_lowercase().contains(&query); - let items = Items { library: &lib_id, lib, groups: lib.group_index(), fill_active }; + let grab = egui::DragAndDrop::payload::(ui.ctx()).and_then(|d| grabbed(&d, &lib_id)); + let items = Items { library: &lib_id, lib, groups: lib.group_index(), fill_active, grab }; // The items shown in each section: the ungrouped ones first, then each group's. let mut counts = vec![0usize; lib.groups.len() + 1]; for (kind, key, _) in lib.items().filter(|(_, _, name)| shown(name)) { @@ -130,76 +165,113 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } ui.add_space(4.0); + // The list takes the panel's height down to the bottom bar (as tall as it was last frame), and + // scrolls. + let bar_id = egui::Id::new("library-bottom-bar"); + let bar: f32 = ui.data(|d| d.get_temp(bar_id)).unwrap_or(BAR); + let list_h = ui.available_height() - bar; + let list_h = if list_h.is_finite() { list_h.max(MIN_LIST) } else { MIN_LIST }; + // Each section's rows: the ungrouped items (None), then each group (its index), header included. + let mut sections: Vec<(Option, Rect)> = vec![]; + // Whether an item takes the drag in progress (dropped next to it), so its section doesn't. + let mut over_item = false; let list_rect = widgets::list_box(ui, |ui| { - ui.set_min_height(140.0); - ui.set_width(ui.available_width()); - if empty { - super::empty_state( - ui, - "library", - tl!("This library is empty"), - tl!("Drag art or swatches here, or use + to add the selection's colors and text styles."), - ); - return ui.min_rect(); - } - if searching && counts.iter().all(|n| *n == 0) { - let body = crate::i18n::fmt(tl!("No items in this library match “{query}”."), &[("query", &query)]); - super::empty_state(ui, "search", tl!("No results"), &body); - return ui.min_rect(); - } - egui::Frame::NONE.inner_margin(egui::Margin::same(6)).show(ui, |ui| { - items.show(ui, &mut act, |kind, key, name| items.group_of(kind, key).is_none() && shown(name)); - for (i, g) in lib.groups.iter().enumerate() { - let n = counts.get(i + 1).copied().unwrap_or_default(); - if searching && n == 0 { - continue; - } - // Open unless closed; open while searching, to show what matched. - let key = format!("library-group-closed:{lib_id}:{}", g.name); - let closed: bool = super::pstate(ui.ctx(), &key); - let open = searching || !closed; - let header = widgets::section_toggle_name(ui, &g.name, open); - ui.painter().text( - header.rect.right_center() - vec2(6.0, 0.0), - egui::Align2::RIGHT_CENTER, - n.to_string(), - egui::FontId::proportional(11.5), - t.text_dim, + let out = egui::ScrollArea::vertical().id_salt("library-scroll").max_height(list_h).auto_shrink([false, false]).show(ui, |ui| { + ui.set_width(ui.available_width()); + if empty { + super::empty_state( + ui, + "library", + tl!("This library is empty"), + tl!("Drag art or swatches here, or use + to add the selection's colors and text styles."), ); - if header.clicked() && !searching { - super::set_pstate(ui.ctx(), &key, !closed); + return; + } + if searching && counts.iter().all(|n| *n == 0) { + let body = crate::i18n::fmt(tl!("No items in this library match “{query}”."), &[("query", &query)]); + super::empty_state(ui, "search", tl!("No results"), &body); + return; + } + egui::Frame::NONE.inner_margin(egui::Margin::same(6)).show(ui, |ui| { + let span = |ui: &Ui, top: f32| Rect::from_x_y_ranges(ui.max_rect().x_range(), top..=ui.cursor().top()); + let top = ui.cursor().top(); + if counts.first().is_some_and(|n| *n > 0) { + items.show(ui, &mut act, &mut over_item, |kind, key, name| items.group_of(kind, key).is_none() && shown(name)); + } else if let Some(Grab::Item(kind, item)) = &items.grab + && items.group_of(*kind, item).is_some() + { + no_group_strip(ui); } - header.context_menu(|ui| { - if menu_item(ui, "Rename Group…", true, false) { - act = Some(Act::RenameGroup(g.name.clone())); - ui.close(); + sections.push((None, span(ui, top))); + for (i, g) in lib.groups.iter().enumerate() { + let n = counts.get(i + 1).copied().unwrap_or_default(); + if searching && n == 0 { + continue; } - if menu_item(ui, "Delete Group", true, false) { - act = Some(Act::Run("library.deleteGroup", json!({ "group": g.name }))); - ui.close(); + let top = ui.cursor().top(); + // Open unless closed; open while searching, to show what matched. + let key = format!("library-group-closed:{lib_id}:{}", g.name); + let closed: bool = super::pstate(ui.ctx(), &key); + let open = searching || !closed; + // The header also drags the group to another place in the list. + let header = widgets::section_toggle_name(ui, &g.name, open).interact(Sense::drag()); + widgets::drag_source(ui, &header, || PanelDrag::LibraryGroup { library: lib_id.clone(), group: g.name.clone() }); + ui.painter().text( + header.rect.right_center() - vec2(6.0, 0.0), + egui::Align2::RIGHT_CENTER, + n.to_string(), + egui::FontId::proportional(11.5), + t.text_dim, + ); + if header.clicked() && !searching { + super::set_pstate(ui.ctx(), &key, !closed); } - }); - if !open { - continue; - } - ui.add_space(2.0); - if n == 0 { - ui.label(egui::RichText::new(tl!("Right-click an item to move it into this group.")).size(11.5).color(t.text_dim)); - ui.add_space(6.0); - } else { - items.show(ui, &mut act, |kind, key, name| items.group_of(kind, key) == Some(i) && shown(name)); + header.context_menu(|ui| { + if menu_item(ui, "Rename Group…", true, false) { + act = Some(Act::RenameGroup(g.name.clone())); + ui.close(); + } + if menu_item(ui, "Delete Group", true, false) { + act = Some(Act::Run("library.deleteGroup", json!({ "group": g.name }))); + ui.close(); + } + }); + if open { + ui.add_space(2.0); + if n == 0 { + ui.label( + egui::RichText::new(tl!("Drag an item here, or right-click one, to put it in this group.")) + .size(11.5) + .color(t.text_dim), + ); + ui.add_space(6.0); + } else { + items.show(ui, &mut act, &mut over_item, |kind, key, name| items.group_of(kind, key) == Some(i) && shown(name)); + } + } + sections.push((Some(i), span(ui, top))); } + }); + if items.grab.is_some() { + scroll_at_edges(ui); } }); - ui.min_rect() + out.inner_rect }); - // Art dragged off the canvas, or a swatch, dropped on the list is added to the library. + if let Some(grab) = &items.grab + && !over_item + { + section_drop(ui, &items, grab, §ions, list_rect, &mut act); + } + // Art dragged off the canvas, or a swatch (not one of this library's colours), dropped on the + // list is added to the library. let zone = ui.interact(list_rect, ui.id().with("libraries-drop"), Sense::hover()); if let Some(ids) = widgets::art_drop(ui, &zone) { act = Some(Act::Run("library.add", json!({ "kind": "graphic", "ids": ids }))); } if let Some(drag) = zone.dnd_hover_payload::() - && let PanelDrag::Paint { paint: Paint::Solid { color, .. }, .. } = &*drag + && let PanelDrag::Paint { paint: Paint::Solid { color, .. }, library, .. } = &*drag + && library.as_ref().is_none_or(|(l, _)| *l != lib_id) { ui.painter().rect_stroke(zone.rect, 0.0, Stroke::new(1.5, t.accent), StrokeKind::Inside); let color = *color; @@ -207,6 +279,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { act = Some(Act::Run("library.add", json!({ "kind": "fillColor", "color": color }))); } } + let bar_top = ui.cursor().top(); widgets::bottom_bar(ui, |ui| { if widgets::icon_button(ui, "group", tl!("New Group"), false, 24.0).clicked() { act = Some(Act::NewGroup(json!([]))); @@ -227,6 +300,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } }); }); + let bar_h = ui.min_rect().bottom() - bar_top; + if bar_h.is_finite() && bar_h > 0.0 { + ui.data_mut(|d| d.insert_temp(bar_id, bar_h)); + } match act { Some(Act::Run(cmd, mut p)) => { if cmd != "library.setCurrent" { @@ -248,8 +325,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { impl Items<'_> { /// The colours, character and paragraph styles and graphics `keep` keeps (given the kind, key - /// and name of each), each kind under its heading. - fn show(&self, ui: &mut Ui, act: &mut Option, keep: impl Fn(ItemKind, &str, &str) -> bool) { + /// and name of each), each kind under its heading. Each drags to another place in the list; + /// `over` is set while one of them takes the drag in progress. + fn show(&self, ui: &mut Ui, act: &mut Option, over: &mut bool, keep: impl Fn(ItemKind, &str, &str) -> bool) { let t = Tokens::get(ui.ctx()); let lib = self.lib; let colors: Vec<_> = lib.colors.iter().filter(|c| keep(ItemKind::Color, &c.name, &c.name)).collect(); @@ -262,7 +340,13 @@ impl Items<'_> { let paint = Paint::solid(c.color); widgets::swatch_tile(ui, r, &paint, false, false); ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, t.border), StrokeKind::Inside); - widgets::drag_source(ui, &resp, || PanelDrag::Paint { paint: paint.clone(), params: json!({ "color": c.color }), rows: None }); + widgets::drag_source(ui, &resp, || PanelDrag::Paint { + paint: paint.clone(), + params: json!({ "color": c.color }), + rows: None, + library: Some((self.library.to_string(), c.name.clone())), + }); + self.drop_next_to(ui, &resp, ItemKind::Color, &c.name, false, act, over); let resp = resp.on_hover_text(&c.name); if resp.clicked() { let to = if self.fill_active { "fill" } else { "stroke" }; @@ -282,13 +366,15 @@ impl Items<'_> { } heading(ui, title); for st in list { - let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click()); + let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click_and_drag()); if resp.hovered() { ui.painter().rect_filled(r, 0.0, t.hover); } let icon = if kind == ItemKind::ParaStyle { "pilcrow" } else { "type" }; icons::paint(ui, icon, Rect::from_center_size(r.left_center() + vec2(10.0, 0.0), vec2(14.0, 14.0)), t.icon); ui.painter().text(r.left_center() + vec2(24.0, 0.0), egui::Align2::LEFT_CENTER, &st.name, egui::FontId::proportional(12.5), t.text); + widgets::drag_source(ui, &resp, || PanelDrag::LibraryItem { library: self.library.to_string(), kind, item: st.name.clone() }); + self.drop_next_to(ui, &resp, kind, &st.name, true, act, over); let resp = resp.on_hover_text(tl!("Click to apply to the selected type")); if resp.clicked() { *act = Some(Act::Run("library.use", json!({ "kind": kind_param(kind), "item": st.name }))); @@ -308,6 +394,7 @@ impl Items<'_> { ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, if resp.hovered() { t.accent } else { t.border }), StrokeKind::Inside); // Dragged onto the canvas, a copy is placed where it is dropped. widgets::drag_source(ui, &resp, || PanelDrag::LibraryGraphic { library: self.library.to_string(), item: g.id.clone() }); + self.drop_next_to(ui, &resp, ItemKind::Graphic, &g.id, false, act, over); let resp = resp.on_hover_text(&g.name); let place = || Act::Run("library.use", json!({ "kind": "graphic", "item": g.id })); if resp.double_clicked() { @@ -326,6 +413,41 @@ impl Items<'_> { } } + /// An item of `kind` dragged over item `key`'s cell `resp` lands just before or after it, by + /// the pointer's half (`row`: rows stack downwards; else chips and tiles run across), in its + /// group: an accent line shows where, and `over` is set. Dropped on itself it stays. + #[allow(clippy::too_many_arguments)] + fn drop_next_to(&self, ui: &Ui, resp: &egui::Response, kind: ItemKind, key: &str, row: bool, act: &mut Option, over: &mut bool) { + let Some(Grab::Item(grabbed_kind, moving)) = &self.grab else { return }; + if *grabbed_kind != kind || resp.dnd_hover_payload::().is_none() { + return; + } + *over = true; + if moving == key { + resp.dnd_release_payload::(); + return; + } + let r = resp.rect; + let at = ui.input(|i| i.pointer.interact_pos()).unwrap_or(r.center()); + let after = if row { at.y > r.center().y } else { at.x > r.center().x }; + let accent = Stroke::new(2.0, Tokens::get(ui.ctx()).accent); + if row { + let y = if after { r.bottom() } else { r.top() }; + ui.painter().line_segment([egui::pos2(r.left(), y), egui::pos2(r.right(), y)], accent); + } else { + let x = if after { r.right() + 2.0 } else { r.left() - 2.0 }; + ui.painter().line_segment([egui::pos2(x, r.top()), egui::pos2(x, r.bottom())], accent); + } + if resp.dnd_release_payload::().is_some() { + let mut p = json!({ "kind": kind_param(kind), "item": moving }); + p[if after { "after" } else { "before" }] = json!(key); + if let Some(g) = self.group_of(kind, key).and_then(|i| self.lib.groups.get(i)) { + p["group"] = json!(g.name); + } + *act = Some(Act::Run("library.moveItem", p)); + } + } + /// An item's context menu entries: Move to Group (No Group, the library's groups, New /// Group…) and Delete. fn item_menu(&self, ui: &mut Ui, act: &mut Option, kind: ItemKind, key: &str) { @@ -371,6 +493,82 @@ fn kind_param(kind: ItemKind) -> &'static str { } } +/// Where an item dragged out of its group can be dropped when no ungrouped item is showing. +fn no_group_strip(ui: &mut Ui) { + let t = Tokens::get(ui.ctx()); + let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 28.0), Sense::hover()); + ui.painter().rect_stroke(r, 3.0, Stroke::new(1.0, t.border), StrokeKind::Inside); + ui.painter().text( + r.center(), + egui::Align2::CENTER_CENTER, + tl!("Drop here to take it out of its group"), + egui::FontId::proportional(11.5), + t.text_dim, + ); + ui.add_space(6.0); +} + +/// While something is dragged near the top or bottom edge of the scrolled list (`ui`: its +/// contents), scroll that way, faster nearer the edge. +fn scroll_at_edges(ui: &mut Ui) { + let Some(pos) = ui.ctx().pointer_hover_pos() else { return }; + let view = ui.clip_rect(); + if !view.x_range().contains(pos.x) { + return; + } + let speed = |depth: f32| if (0.0..EDGE).contains(&depth) { 2.0 + 10.0 * (1.0 - depth / EDGE) } else { 0.0 }; + let delta = speed(pos.y - view.top()) - speed(view.bottom() - pos.y); + if delta != 0.0 { + ui.scroll_with_delta(vec2(0.0, delta)); + ui.ctx().request_repaint(); + } +} + +/// The drag in progress held over a section of the list (`sections`, seen through `clip`), away +/// from the items that take one: an item goes into that section's group (the ungrouped section: +/// out of its group), the section outlined; a group goes before or after that group, by the +/// pointer's half, an accent line showing where. +fn section_drop(ui: &Ui, items: &Items, grab: &Grab, sections: &[(Option, Rect)], clip: Rect, act: &mut Option) { + // By the pointer, not by hover zones: the headers and items over the sections take the hover. + let Some(pos) = ui.ctx().pointer_latest_pos() else { return }; + let released = ui.input(|i| i.pointer.any_released()); + let take = || egui::DragAndDrop::take_payload::(ui.ctx()).is_some(); + let t = Tokens::get(ui.ctx()); + let Some((group, rect)) = sections.iter().find(|(_, rect)| rect.intersect(clip).contains(pos)) else { return }; + let r = rect.intersect(clip); + let name = |i: &usize| items.lib.groups.get(*i).map(|g| g.name.clone()); + match grab { + Grab::Item(kind, item) => { + if items.group_of(*kind, item) == *group { + return; + } + ui.painter().rect_stroke(r, 3.0, Stroke::new(1.5, t.accent), StrokeKind::Inside); + if released && take() { + let mut p = json!({ "kind": kind_param(*kind), "item": item }); + if let Some(g) = group.as_ref().and_then(name) { + p["group"] = json!(g); + } + *act = Some(Act::Run("library.moveItem", p)); + } + } + Grab::Group(moving) => { + // Groups only go among the groups; dropped on itself, one stays. + let (Some(to), Some(from)) = (*group, items.lib.groups.iter().position(|g| g.name == *moving)) else { return }; + if from == to { + return; + } + let after = pos.y > rect.center().y; + let y = if after { rect.bottom() } else { rect.top() }; + ui.painter().line_segment([egui::pos2(r.left(), y), egui::pos2(r.right(), y)], Stroke::new(2.0, t.accent)); + if released && take() { + let to = to + usize::from(after); + let to = if from < to { to - 1 } else { to }; + *act = Some(Act::Run("library.moveGroup", json!({ "group": moving, "to": to }))); + } + } + } +} + /// A section heading in the list. fn heading(ui: &mut Ui, text: &str) { let t = Tokens::get(ui.ctx()); @@ -584,6 +782,131 @@ mod tests { assert!(none.iter().any(|t| t == "No results"), "{none:?}"); } + /// A library imported from `styles` (character style names) and `groups` ([(name, its styles)]) + /// → its id. + fn styled(app: &mut VectorcraftApp, styles: &[&str], groups: &[(&str, &[&str])]) -> String { + let styles: Vec = styles.iter().enumerate().map(|(i, n)| json!({"name": n, "attrs": {"size": 8 + i}})).collect(); + let groups: Vec = groups + .iter() + .map(|(g, items)| json!({"name": g, "items": items.iter().map(|i| json!({"kind": "charStyle", "item": i})).collect::>()})) + .collect(); + let data = json!({"name": "Order", "charStyles": styles, "groups": groups}).to_string(); + app.run("library.import", json!({"data": data})).unwrap()["id"].as_str().unwrap().to_string() + } + + /// One frame of the panel in a 260 × `tall` window with `events` → where each text it shows is + /// (its rect), and the panel's height. + fn frame_at(app: &mut VectorcraftApp, ctx: &egui::Context, tall: f32, events: Vec) -> (Vec<(String, Rect)>, f32) { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::pos2(0.0, 0.0), vec2(260.0, tall))), events, ..Default::default() }; + let mut height = 0.0; + let mut out = ctx.run_ui(raw, |ui| { + show(app, ui); + height = ui.min_rect().height(); + }); + out.textures_delta.clear(); + let mut texts = vec![]; + for s in out.shapes { + if let egui::epaint::Shape::Text(t) = s.shape { + texts.push((t.galley.text().to_string(), t.galley.rect.translate(t.pos.to_vec2()))); + } + } + (texts, height) + } + + /// Where text `name` is in `texts`. + fn at(texts: &[(String, Rect)], name: &str) -> Rect { + texts.iter().find(|(t, _)| t == name).map(|(_, r)| *r).unwrap_or_else(|| panic!("{name} isn't shown: {texts:?}")) + } + + /// `drag` released at `pos`. + fn drop_at(app: &mut VectorcraftApp, ctx: &egui::Context, drag: PanelDrag, pos: egui::Pos2) { + egui::DragAndDrop::set_payload(ctx, drag); + let up = egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; + frame_at(app, ctx, 600.0, vec![egui::Event::PointerMoved(pos), up]); + frame_at(app, ctx, 600.0, vec![]); + } + + fn style_order(app: &mut VectorcraftApp) -> Vec { + let got = app.run("library.get", json!({})).unwrap(); + got["charStyles"].as_array().unwrap().iter().map(|s| s["name"].as_str().unwrap().to_string()).collect() + } + + fn group_names(app: &mut VectorcraftApp) -> Vec<(String, Vec)> { + let got = app.run("library.get", json!({})).unwrap(); + let items = |g: &Value| g["items"].as_array().unwrap().iter().map(|i| i["item"].as_str().unwrap().to_string()).collect(); + got["groups"].as_array().unwrap().iter().map(|g| (g["name"].as_str().unwrap().to_string(), items(g))).collect() + } + + /// Dragging in the list: a style dropped on the top or bottom half of another lands before or + /// after it, in its group; one dropped on a group's header goes into that group; a group's + /// header dropped on another group moves the group; and with every item grouped, a strip + /// takes an item out of its group. + #[test] + fn items_and_groups_move_by_dragging() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let lib = styled(&mut app, &["A", "B", "C", "D"], &[("Warm", &["D"]), ("Cool", &[])]); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let (texts, _) = frame_at(&mut app, &ctx, 600.0, vec![]); + let item = |name: &str| PanelDrag::LibraryItem { library: lib.clone(), kind: ItemKind::CharStyle, item: name.into() }; + // C onto A's top half: first. + let a = at(&texts, "A"); + drop_at(&mut app, &ctx, item("C"), egui::pos2(a.center().x, a.top() - 4.0)); + assert_eq!(style_order(&mut app), ["C", "A", "B", "D"]); + // A onto D's bottom half (in Warm): after D, in Warm. + let (texts, _) = frame_at(&mut app, &ctx, 600.0, vec![]); + let d = at(&texts, "D"); + drop_at(&mut app, &ctx, item("A"), egui::pos2(d.center().x, d.bottom() + 4.0)); + assert_eq!(style_order(&mut app), ["C", "B", "D", "A"]); + assert_eq!(group_names(&mut app), [("Warm".into(), vec!["D".to_string(), "A".into()]), ("Cool".into(), vec![])]); + // B onto Cool's header: into Cool, the order kept. + let (texts, _) = frame_at(&mut app, &ctx, 600.0, vec![]); + drop_at(&mut app, &ctx, item("B"), at(&texts, "Cool").center()); + assert_eq!(style_order(&mut app), ["C", "B", "D", "A"]); + assert_eq!(group_names(&mut app)[1], ("Cool".into(), vec!["B".to_string()])); + // Cool's header onto Warm's header (its top half): Cool first. + let (texts, _) = frame_at(&mut app, &ctx, 600.0, vec![]); + let warm = at(&texts, "Warm"); + drop_at(&mut app, &ctx, PanelDrag::LibraryGroup { library: lib.clone(), group: "Cool".into() }, egui::pos2(warm.center().x, warm.top())); + assert_eq!(group_names(&mut app).iter().map(|(g, _)| g.as_str()).collect::>(), ["Cool", "Warm"]); + // Every item grouped: while one is dragged a strip takes it out of its group. + app.run("library.moveItem", json!({"kind": "charStyle", "item": "C", "group": "Warm"})).unwrap(); + egui::DragAndDrop::set_payload(&ctx, item("C")); + let (texts, _) = frame_at(&mut app, &ctx, 600.0, vec![]); + let strip = at(&texts, "Drop here to take it out of its group"); + drop_at(&mut app, &ctx, item("C"), strip.center()); + assert!(group_names(&mut app).iter().all(|(_, items)| !items.contains(&"C".to_string())), "{:?}", group_names(&mut app)); + // Without a drag there is no strip. + let (texts, _) = frame_at(&mut app, &ctx, 600.0, vec![]); + assert!(!texts.iter().any(|(t, _)| t == "Drop here to take it out of its group")); + } + + /// A long list scrolls inside the panel (its bottom bar stays in the window), and a drag held + /// near the list's bottom edge scrolls it. + #[test] + fn a_long_list_scrolls_also_while_dragging() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let names: Vec = (0..60).map(|i| format!("Style {i}")).collect(); + let lib = styled(&mut app, &names.iter().map(String::as_str).collect::>(), &[]); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let (texts, height) = frame_at(&mut app, &ctx, 400.0, vec![]); + assert!(height <= 400.0, "the panel fits the window: {height}"); + let first = at(&texts, "Style 0"); + // The list's bottom edge: the last text drawn before the window's bottom bar area. + let bottom = texts.iter().filter(|(t, _)| t.starts_with("Style ")).map(|(_, r)| r.bottom()).fold(0.0, f32::max).min(400.0 - BAR - 4.0); + egui::DragAndDrop::set_payload(&ctx, PanelDrag::LibraryItem { library: lib, kind: ItemKind::CharStyle, item: "Style 0".into() }); + let hold = egui::pos2(first.center().x, bottom - 4.0); + for _ in 0..5 { + frame_at(&mut app, &ctx, 400.0, vec![egui::Event::PointerMoved(hold)]); + } + let (texts, _) = frame_at(&mut app, &ctx, 400.0, vec![egui::Event::PointerMoved(hold)]); + let moved = texts.iter().find(|(t, _)| t == "Style 0").map_or(f32::NEG_INFINITY, |(_, r)| r.top()); + assert!(moved < first.top(), "the list scrolled down: {} → {moved}", first.top()); + } + /// New Group… and Rename Group… ask for a name and act on the library and group they came /// from; the dialog shows only the name. #[test] diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index dc92a4b7e4..cf8b7d15a3 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -202,7 +202,8 @@ fn multi_color(app: &mut VectorcraftApp, ctx: &egui::Context) -> bool { /// Edit Artboards (the Artboard tool): the active artboard's name, which can be edited to rename /// it, and the Artboard Options icon; its position and size, its preset and -/// orientation (#671) (with Scale Artwork with Artboard on, a new size scales its art, #602), Move +/// orientation (#671) (with Scale Artwork with Artboard on, a new size scales its art, #602; a new +/// W or H, preset or orientation goes to every selected artboard, in one undo step), Move /// and Scale Artwork with Artboard, New Artboard and Delete Artboard, and Quick Actions: Rearrange All (#681) and /// Exit back to the Selection tool (#530). fn artboard_sections(app: &mut VectorcraftApp, ui: &mut Ui) { @@ -241,7 +242,10 @@ fn artboard_sections(app: &mut VectorcraftApp, ui: &mut Ui) { _ => 0.0, }; if let Some(v) = widgets::num_field(ui, ("ab", key, row), Some(v - offset), units, fw) { - app.run("artboard.setProps", json!({"index": i, key: v + offset, "scaleArt": scale_art, "moveArt": move_art})).ok(); + // A new X or Y moves the active artboard; a new W or H goes to every selected one. + let indices = if matches!(key, "width" | "height") { super::artboards::resized_with(app, i) } else { vec![i] }; + let common = json!({"scaleArt": scale_art, "moveArt": move_art}); + super::artboards::set_props(app, &indices, common, |j, _| Some(json!({"index": j, key: v + offset}))).ok(); } } ui.end_row(); @@ -278,16 +282,21 @@ fn rearrange_button(app: &mut VectorcraftApp, ui: &mut Ui, artboards: usize, w: } } +/// A preset `pw` × `ph` turned to an artboard's orientation (`landscape`, or portrait; a square +/// preset as it is). +fn turned(landscape: bool, pw: f64, ph: f64) -> (f64, f64) { + if (pw > ph) == landscape || pw == ph { (pw, ph) } else { (ph, pw) } +} + /// Artboard `i`'s size preset (New Document's saved and built-in presets, by category, either way /// round; Custom when its `w` × `h` points match none) and its orientation, here and in the Control -/// bar. A preset sizes it in its current orientation; the other orientation swaps its width and -/// height. Its top-left corner stays put either way. +/// bar. A preset sizes each selected artboard in its own orientation; an orientation swaps the +/// width and height of each selected artboard that is not square and not already in it. Each +/// top-left corner stays put. pub(crate) fn artboard_size_row(app: &mut VectorcraftApp, ui: &mut Ui, i: usize, w: f64, h: f64) { let landscape = w > h; - // A preset `pw` × `ph` turned to the artboard's orientation. - let turned = |pw: f64, ph: f64| if (pw > ph) == landscape || pw == ph { (pw, ph) } else { (ph, pw) }; let same = |s: &newdoc::DocSettings| { - let (pw, ph) = turned(s.width, s.height); + let (pw, ph) = turned(landscape, s.width, s.height); (pw - w).abs() < 0.01 && (ph - h).abs() < 0.01 }; // Recent holds documents made, not presets. @@ -297,17 +306,19 @@ pub(crate) fn artboard_size_row(app: &mut VectorcraftApp, ui: &mut Ui, i: usize, .filter(|(_, l)| !l.is_empty()) .collect(); let current = cats.iter().flat_map(|(_, l)| l).find(|s| same(s)).map_or(tl!("Custom"), |s| crate::dialogs::preset_name(&s.name)).to_string(); - let mut size = None; + // The preset's width and height as listed, or the orientation clicked. + let mut preset = None; + let mut orientation = None; ui.horizontal(|ui| { dim_label(ui, tl!("Preset:")); - size = widgets::combo(ui, "ab-preset", ¤t, 140.0, false, |ui| { + preset = widgets::combo(ui, "ab-preset", ¤t, 140.0, false, |ui| { let mut chosen = None; for (cat, list) in &cats { ui.menu_button(tl!(cat), |ui| { widgets::menu_scroll(ui, |ui| { for s in list { if widgets::menu_item_name(ui, crate::dialogs::preset_name(&s.name), true, same(s)) { - chosen = Some(turned(s.width, s.height)); + chosen = Some((s.width, s.height)); } } }); @@ -317,15 +328,26 @@ pub(crate) fn artboard_size_row(app: &mut VectorcraftApp, ui: &mut Ui, i: usize, }); ui.spacing_mut().item_spacing.x = 2.0; for (is_landscape, tip) in [(false, tl!("Portrait")), (true, tl!("Landscape"))] { - if widgets::orientation_button(ui, is_landscape, landscape == is_landscape, tip) && landscape != is_landscape { - size = Some((h, w)); + if widgets::orientation_button(ui, is_landscape, landscape == is_landscape, tip) { + orientation = Some(is_landscape); } } }); - if let Some((width, height)) = size { - let scale_art = super::artboards::scale_art(app); - app.run("artboard.setProps", json!({"index": i, "width": width, "height": height, "scaleArt": scale_art})).ok(); + if preset.is_none() && orientation.is_none() { + return; } + let scale_art = super::artboards::scale_art(app); + let indices = super::artboards::resized_with(app, i); + super::artboards::set_props(app, &indices, json!({"scaleArt": scale_art}), |j, r| { + let (w, h) = (r.width(), r.height()); + let (width, height) = match (preset, orientation) { + (Some((pw, ph)), _) => turned(w > h, pw, ph), + (None, Some(l)) if (w > h) != l && w != h => (h, w), + _ => return None, + }; + Some(json!({"index": j, "width": width, "height": height})) + }) + .ok(); } fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) { @@ -561,6 +583,7 @@ pub fn type_sections(app: &mut VectorcraftApp, ui: &mut Ui) { // The font, Font Size, Leading, Kerning and Tracking as in the Character panel. let w = ui.available_width(); super::character::font_pickers(app, ui, &s, ("font", "font-style"), (w - 4.0, w - 4.0)); + super::character::variable_font(app, ui, &s, w - 4.0); super::character::metrics_grid(app, ui, "props-char", &s, w, false); section_header(ui, tl!("Paragraph")); // As in the Paragraph panel: the seven alignments and Hyphenate (#775); the rest is there. @@ -798,6 +821,59 @@ mod tests { } } + /// Three landscape artboards, with Artboards 1 and 3 selected with the Artboard tool (Artboard + /// 1 active): 200 × 100, 200 × 100 and 300 × 150. + fn two_selected_artboards() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100, "artboards": 3})).unwrap(); + app.run("artboard.setProps", json!({"index": 2, "width": 300, "height": 150})).unwrap(); + app.select_tool("artboard"); + super::super::artboards::select(&mut app, 0); + app.session.set_tool_option("selected", &json!([0, 2])); + app + } + + /// Each artboard's (x0, y0, width, height). + fn boards(app: &VectorcraftApp) -> Vec<(f64, f64, f64, f64)> { + app.session.doc().unwrap().doc.artboards.iter().map(|a| (a.rect.x0, a.rect.y0, a.rect.width(), a.rect.height())).collect() + } + + /// #1482: with Artboards 1 and 3 selected, a W typed into Properties or the Transform panel + /// resizes both in one undo step, and Artboard 2 keeps its size. Properties keeps each top-left + /// corner; the Transform panel resizes each about its own center, its default reference point. + #[test] + fn artboard_width_resizes_every_selected_artboard_in_properties_and_transform() { + for (draw, centered) in [(show as fn(&mut VectorcraftApp, &mut Ui), false), (super::super::transform::show, true)] { + let mut app = two_selected_artboards(); + let before = boards(&app); + let undo = app.session.doc().unwrap().history.undo.len(); + let ctx = egui::Context::default(); + panel_frame(&mut app, &ctx, vec![], draw); + let texts = panel_frame(&mut app, &ctx, vec![], draw); + let label = texts.iter().find(|(t, _)| t == "W:").unwrap().1; + let at = egui::pos2(label.right() + 40.0, label.center().y); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + let key = |key, modifiers| Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; + panel_frame(&mut app, &ctx, vec![Event::PointerMoved(at), press(true)], draw); + panel_frame(&mut app, &ctx, vec![press(false)], draw); + panel_frame(&mut app, &ctx, vec![key(egui::Key::A, egui::Modifiers::COMMAND)], draw); + panel_frame(&mut app, &ctx, vec![Event::Text("250".into())], draw); + panel_frame(&mut app, &ctx, vec![key(egui::Key::Enter, egui::Modifiers::NONE)], draw); + panel_frame(&mut app, &ctx, vec![], draw); + let mut want = before.clone(); + for (i, shift) in [(0, 25.0), (2, -25.0)] { + want[i].2 = 250.0; + if centered { + want[i].0 -= shift; + } + } + assert_eq!(boards(&app), want, "centered: {centered}"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(boards(&app), before); + } + } + /// #530: Edit Artboards shows the active artboard, with New Artboard, Delete Artboard and Exit. /// #775: type's Paragraph section has Hyphenate, and its checkbox turns it on. #[test] @@ -813,6 +889,22 @@ mod tests { assert!(hyphenate(&app)); } + /// Variable fonts get the same Variable Font button in Properties as in the Character panel. + #[test] + fn properties_variable_font_button_for_variable_type() { + use vectorcraft_text::test_fonts::{TWO_AXIS_FAMILY, two_axis_font}; + vectorcraft_text::FontDb::global().add_font(two_axis_font().unwrap()); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let plain = app.run("text.create", json!({"x": 20, "y": 50, "text": "Static"})).unwrap()["id"].clone(); + let id = app.run("text.create", json!({"x": 20, "y": 120, "text": "lIn", "font": TWO_AXIS_FAMILY})).unwrap()["id"].clone(); + let ctx = egui::Context::default(); + app.run("select.set", json!({"ids": [plain]})).unwrap(); + assert!(!frame(&mut app, &ctx, vec![]).iter().any(|(t, _)| t == "Variable Font")); + app.run("select.set", json!({"ids": [id]})).unwrap(); + assert!(frame(&mut app, &ctx, vec![]).iter().any(|(t, _)| t == "Variable Font")); + } + #[test] fn edit_artboards_adds_artboards_and_exits() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -1346,6 +1438,106 @@ mod tests { assert!(frame(&mut app, &ctx, vec![]).iter().any(|(t, _)| t == "Custom")); } + /// The center of Edit Artboards' Portrait (`landscape` false) or Landscape button. + fn orientation_button(ctx: &egui::Context, texts: &[(String, Rect)], landscape: bool) -> Pos2 { + let row = texts.iter().find(|(t, _)| t == "Preset:").map(|(_, r)| *r).unwrap(); + ctx.viewport(|vp| { + let mut r: Vec = vp + .prev_pass + .widgets + .layers() + .flat_map(|(_, w)| w.iter()) + .filter(|w| w.sense.senses_click() && w.rect.y_range().contains(row.center().y) && w.rect.left() > row.right()) + .map(|w| w.rect) + .collect(); + r.sort_by(|a, b| a.left().total_cmp(&b.left())); + r[r.len() - if landscape { 1 } else { 2 }].center() + }) + } + + /// #1482: with Artboards 1 and 3 selected, Portrait swaps the width and height of both in one + /// undo step, each keeping its top-left corner; Artboard 2 stays landscape. An artboard already + /// in that orientation keeps its size. + #[test] + fn edit_artboards_orientation_turns_every_selected_artboard() { + let mut app = two_selected_artboards(); + let before = boards(&app); + let undo = app.session.doc().unwrap().history.undo.len(); + let ctx = egui::Context::default(); + let portrait = |app: &mut VectorcraftApp| { + frame(app, &ctx, vec![]); + let texts = frame(app, &ctx, vec![]); + let at = orientation_button(&ctx, &texts, false); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, &ctx, vec![Event::PointerMoved(at), press(true)]); + frame(app, &ctx, vec![press(false)]); + }; + portrait(&mut app); + let mut want = before.clone(); + for i in [0, 2] { + (want[i].2, want[i].3) = (before[i].3, before[i].2); + } + assert_eq!(boards(&app), want); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(boards(&app), before); + // Artboard 3 portrait already: Portrait turns Artboard 1 alone. + app.run("artboard.setProps", json!({"index": 2, "width": 150, "height": 300})).unwrap(); + let before = boards(&app); + portrait(&mut app); + let mut want = before.clone(); + (want[0].2, want[0].3) = (100.0, 200.0); + assert_eq!(boards(&app), want); + } + + /// #1482: with Artboards 1 and 3 selected, a preset chosen in Edit Artboards sizes both in one + /// undo step, each in its own orientation and keeping its top-left corner: Letter (612 × 792 pt) + /// stays portrait for Artboard 1 and turns landscape for Artboard 3. Artboard 2 keeps its size. + #[test] + fn edit_artboards_preset_sizes_every_selected_artboard() { + let mut app = two_selected_artboards(); + app.run("artboard.setProps", json!({"index": 0, "width": 100, "height": 200})).unwrap(); + let before = boards(&app); + let undo = app.session.doc().unwrap().history.undo.len(); + let ctx = egui::Context::default(); + // A frame on a wide screen, with the texts of nested shapes too (the open list and its + // submenu), and the center of `label` among them (menu items carry a check-mark column). + let run = |app: &mut VectorcraftApp, events: Vec| { + 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 raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(800.0, 700.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + let mut v = vec![]; + out.shapes.iter().for_each(|c| walk(&c.shape, &mut v)); + v + }; + let at = |texts: &[(String, Rect)], label: &str| { + texts.iter().find(|(t, _)| t.trim() == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no {label:?} in {texts:?}")) + }; + let press = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + run(&mut app, vec![]); + let custom = at(&run(&mut app, vec![]), "Custom"); + run(&mut app, vec![Event::PointerMoved(custom), press(custom, true)]); + run(&mut app, vec![press(custom, false)]); + // Hovering Print opens its submenu. + let print = at(&run(&mut app, vec![]), "Print"); + run(&mut app, vec![Event::PointerMoved(print)]); + let letter = at(&run(&mut app, vec![]), "Letter"); + run(&mut app, vec![Event::PointerMoved(letter), press(letter, true)]); + run(&mut app, vec![press(letter, false)]); + let mut want = before.clone(); + (want[0].2, want[0].3) = (612.0, 792.0); + (want[2].2, want[2].3) = (792.0, 612.0); + assert_eq!(boards(&app), want); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + } + /// #602: Edit Artboards shows Move and Scale Artwork with Artboard; with Scale on, a new size /// (here the other orientation) takes the art on the artboard along. #[test] diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index 33ac5b4b16..56c48d23c1 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -410,7 +410,7 @@ fn drag_of(e: &Entry, names: Vec) -> PanelDrag { Entry::Folder(_) => Paint::None, }; let rows = SwatchRows { grabbed: e.name().to_string(), names, groups: e.is_folder() }; - PanelDrag::Paint { paint, params: swatch_params(e).unwrap_or_default(), rows: Some(rows) } + PanelDrag::Paint { paint, params: swatch_params(e).unwrap_or_default(), rows: Some(rows), library: None } } /// What the tiles or rows saw this frame. @@ -614,6 +614,7 @@ pub(crate) fn drag_preview(app: &VectorcraftApp, ctx: &egui::Context) { }, PanelDrag::Brush { def, .. } => return pointer_chip(ctx, |ui, r| super::brushes::chip(ui, r, def)), PanelDrag::LibraryGraphic { library, item } => return pointer_chip(ctx, |ui, r| super::libraries::chip(app, ui, r, library, item)), + PanelDrag::LibraryItem { .. } | PanelDrag::LibraryGroup { .. } => return, }; pointer_chip(ctx, |ui, r| { if registration { diff --git a/crates/ui-egui/src/panels/tabs.rs b/crates/ui-egui/src/panels/tabs.rs index 4b299bd51d..2a5af459e6 100644 --- a/crates/ui-egui/src/panels/tabs.rs +++ b/crates/ui-egui/src/panels/tabs.rs @@ -1,5 +1,7 @@ -//! Tabs panel: tab-stop alignment, X position, leader and "align on", and a ruler on which a click -//! adds a stop, dragging moves one and dragging it off the ruler deletes it. +//! Tabs panel: tab-stop alignment, X position, leader and "align on", and a ruler numbered in the +//! General unit on which a click adds a stop, dragging moves one and dragging it off the ruler +//! deletes it. With Snap to Unit on, or Shift held, a stop placed or dragged on the ruler lands on +//! the ruler's nearest tick. use egui::{Sense, Stroke, Ui, vec2}; use serde_json::{Value, json}; @@ -175,22 +177,33 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let scale = (w as f64 - 8.0) / span; let to_x = |pt: f64| rect.left() + 4.0 + (pt * scale) as f32; let to_pt = |x: f32| (((x - rect.left() - 4.0) as f64) / scale).max(0.0); - let mut tick = 0.0; - while tick <= span + 1e-6 { - let x = to_x(tick); - let major = (tick / 36.0).round() * 36.0 == tick && ((tick / 36.0) as i64) % 2 == 0; - p.line_segment([egui::pos2(x, rect.bottom() - if major { 10.0 } else { 5.0 }), egui::pos2(x, rect.bottom())], Stroke::new(1.0, t.text_dim)); - if major { + // The ruler is numbered in the General unit, with the canvas rulers' label step at its scale + // and a tick every tenth of a step. + let unit = app.session.general_unit(); + let step = unit.ruler_step(scale); + let minor = step / 10.0; + for k in 0..=(unit.from_pt(span) / minor + 1e-6).floor() as usize { + let v = k as f64 * minor; + let x = to_x(unit.to_pt(v)); + let len = match k % 10 { + 0 => 10.0, + 5 => 7.0, + _ => 4.0, + }; + p.line_segment([egui::pos2(x, rect.bottom() - len), egui::pos2(x, rect.bottom())], Stroke::new(1.0, t.text_dim)); + if k % 10 == 0 { p.text( egui::pos2(x + 2.0, rect.top() + 1.0), egui::Align2::LEFT_TOP, - format!("{}", (tick / 72.0 * 100.0).round() / 100.0), + crate::canvas::ruler_label(v, step), egui::FontId::proportional(9.0), t.text_dim, ); } - tick += 18.0; } + // Snap to Unit, or Shift held: a stop placed or dragged on the ruler lands on its nearest tick. + let snap = pstate::(ui.ctx(), "tabs-snap") || ui.input(|i| i.modifiers.shift); + let place = |x: f32| if snap { unit.snap_to_ruler_tick(to_pt(x), scale).max(0.0) } else { to_pt(x) }; for (i, s) in stops.iter().enumerate() { let x = to_x(s.position); let c = if i == sel { t.accent } else { t.text }; @@ -230,7 +243,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // Dragged off the ruler: delete. stops.remove(i); } else { - stops[i].position = to_pt(pos.x); + stops[i].position = place(pos.x); stops.sort_by(|a, b| a.position.total_cmp(&b.position)); } apply(app, &stops); @@ -241,12 +254,18 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { match hit_at(pos.x) { Some(i) => set_pstate(ui.ctx(), "tabs-sel", i), None => { - let position = to_pt(pos.x); - stops.push(TabStop { position, align: ALIGNS[align_idx.min(3)].0, leader: String::new(), align_on: '.' }); - stops.sort_by(|a, b| a.position.total_cmp(&b.position)); + let position = place(pos.x); + // A snapped click onto a stop's tick selects that stop and records no undo step. + let added = !stops.iter().any(|s| s.position == position); + if added { + stops.push(TabStop { position, align: ALIGNS[align_idx.min(3)].0, leader: String::new(), align_on: '.' }); + stops.sort_by(|a, b| a.position.total_cmp(&b.position)); + } let i = stops.iter().position(|s| s.position == position).unwrap_or(0); set_pstate(ui.ctx(), "tabs-sel", i); - apply(app, &stops); + if added { + apply(app, &stops); + } } } } @@ -256,6 +275,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let Some((_, para, _)) = current_para(app) else { ui.add_enabled(false, egui::Button::new(tl!("Select text")).frame(false)); + snap_to_unit_item(ui); return; }; let mut stops = para.tabs; @@ -290,6 +310,17 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } apply(app, &stops); } + snap_to_unit_item(ui); +} + +/// The panel menu's Snap to Unit, checked while it is on: stops placed or dragged on the ruler land +/// on its nearest tick. +fn snap_to_unit_item(ui: &mut Ui) { + ui.separator(); + let on: bool = pstate(ui.ctx(), "tabs-snap"); + if menu_item(ui, tl!("Snap to Unit"), true, on) { + set_pstate(ui.ctx(), "tabs-snap", !on); + } } #[cfg(test)] @@ -405,9 +436,9 @@ mod tests { }; let labels = frame(&mut app, vec![]); let at = |label: &str| labels.iter().find(|(t, _)| t == label).unwrap_or_else(|| panic!("{label} in {labels:?}")).1; - // A label sits 2 px right of its tick: 0 and 1 inch give the ruler's scale. - let (zero, inch) = (at("0"), at("1")); - let to_x = |pt: f32| zero.x - 2.0 + pt * (inch.x - zero.x) / 72.0; + // A label sits 2 px right of its tick: 0 and 100 pt give the ruler's scale. + let (zero, hundred) = (at("0"), at("100")); + let to_x = |pt: f32| zero.x - 2.0 + pt * (hundred.x - zero.x) / 100.0; let y = zero.y + 15.0; let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; // Press 3 px right of the stop, then drag right; egui starts the drag 6+ px from the press. @@ -425,6 +456,150 @@ mod tests { assert!((moved_to - end.x).abs() < 1.0, "stop at {moved_to}, released at {}", end.x); } + /// One frame of the panel with `events`, Shift held when `shift` → the ruler's labels (9 pt) and + /// where they are painted, left to right. + fn ruler_frame(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec, shift: bool) -> Vec<(String, egui::Pos2)> { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 400.0)); + let modifiers = if shift { egui::Modifiers::SHIFT } else { egui::Modifiers::NONE }; + let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect(); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + out.shapes + .iter() + .filter_map(|c| match &c.shape { + egui::Shape::Text(t) if t.galley.job.sections.first().is_some_and(|s| s.format.font_id.size == 9.0) => { + Some((t.galley.text().to_string(), t.pos)) + } + _ => None, + }) + .collect() + } + + /// The labels the ruler shows in a frame of [`ruler_frame`]. + fn ruler_labels(ctx: &egui::Context, app: &mut VectorcraftApp) -> Vec { + ruler_frame(ctx, app, vec![], false).into_iter().map(|(t, _)| t).collect() + } + + /// Press on the ruler at `from` (points), move to `to` and release there, Shift held when + /// `shift`. A label sits 2 px right of its tick, so the first two labels give the ruler's scale. + fn drag_on_ruler(ctx: &egui::Context, app: &mut VectorcraftApp, from: f64, to: f64, shift: bool) { + let labels = ruler_frame(ctx, app, vec![], shift); + let [(zero, a), (next, b), ..] = &labels[..] else { panic!("ruler labels {labels:?}") }; + assert_eq!(zero, "0"); + let per = next.parse::().unwrap() * app.session.general_unit().points(); + let x = |pt: f64| a.x - 2.0 + (pt / per) as f32 * (b.x - a.x); + let y = a.y + 15.0; + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let (press, end) = (egui::pos2(x(from), y), egui::pos2(x(to), y)); + ruler_frame(ctx, app, vec![egui::Event::PointerMoved(press), button(press, true)], shift); + if press != end { + for f in [0.25, 0.5, 1.0] { + ruler_frame(ctx, app, vec![egui::Event::PointerMoved(press.lerp(end, f))], shift); + } + } + ruler_frame(ctx, app, vec![button(end, false)], shift); + ruler_frame(ctx, app, vec![], shift); + } + + /// The ruler is numbered in the General unit (the document's units), with labels at least 50 px + /// apart as on the canvas rulers. + #[test] + fn ruler_is_numbered_in_the_general_unit() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap(); + let ctx = egui::Context::default(); + assert_eq!(ruler_labels(&ctx, &mut app), ["0", "50", "100", "150", "200", "250", "300"]); + app.session.execute("document.setUnits", &json!({"units": "in"})).unwrap(); + assert_eq!(ruler_labels(&ctx, &mut app), ["0", "1", "2", "3", "4"]); + app.session.execute("document.setUnits", &json!({"units": "mm"})).unwrap(); + assert_eq!(ruler_labels(&ctx, &mut app), ["0", "25", "50", "75", "100"]); + } + + /// Snap to Unit, chosen from the panel menu with or without text selected, puts a stop dragged + /// or placed by a click on the ruler on its nearest tick (every 5 pt on this points ruler). + /// Chosen again, it turns off. + #[test] + fn snap_to_unit_puts_dragged_and_clicked_stops_on_the_nearest_tick() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({})).unwrap(); + let ctx = egui::Context::default(); + let row = |app: &mut VectorcraftApp| { + let rows = menu_frame(&ctx, app, vec![]); + rows.into_iter().find(|(t, _)| t.trim_start_matches(['✓', ' ']) == "Snap to Unit").unwrap_or_else(|| panic!("Snap to Unit")) + }; + choose(&ctx, &mut app, "Snap to Unit"); + assert_eq!(row(&mut app).0, "✓ Snap to Unit"); + app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap(); + app.session.execute("text.tabs.set", &json!({"stops": [{"position": 50}]})).unwrap(); + assert_eq!(ruler_labels(&ctx, &mut app)[..2], ["0", "50"]); + let positions = |app: &VectorcraftApp| current(app).unwrap().1.iter().map(|s| s.position).collect::>(); + drag_on_ruler(&ctx, &mut app, 50.0, 13.4, false); + assert_eq!(positions(&app), [15.0]); + // A click at 33.4 pt adds a stop at 35. + drag_on_ruler(&ctx, &mut app, 33.4, 33.4, false); + assert_eq!(positions(&app), [15.0, 35.0]); + assert_eq!(row(&mut app).0, "✓ Snap to Unit"); + // Chosen again, Snap to Unit turns off and the stop stays where it is dropped. + let at = row(&mut app).1.center(); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + menu_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(at), button(true)]); + menu_frame(&ctx, &mut app, vec![button(false)]); + assert_eq!(row(&mut app).0.trim_start(), "Snap to Unit"); + drag_on_ruler(&ctx, &mut app, 35.0, 23.4, false); + let p = positions(&app); + assert!((p[1] - 23.4).abs() < 1.0 && p[1] != 25.0, "{p:?}"); + } + + /// A snapped click more than 5 px from a stop, nearest to the tick that stop is on, selects the + /// stop and records no undo step. On this millimeters ruler the ticks are 2.5 mm (7.09 pt, 12.4 + /// px) apart. + #[test] + fn a_snapped_click_onto_a_stop_selects_it() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({})).unwrap(); + app.session.execute("document.setUnits", &json!({"units": "mm"})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 224, "height": 100}})).unwrap(); + app.session.execute("text.tabs.set", &json!({"stops": [{"position": 100}]})).unwrap(); + let ctx = egui::Context::default(); + assert_eq!(ruler_labels(&ctx, &mut app), ["0", "25", "50", "75"]); + set_pstate(&ctx, "tabs-snap", true); + let tick = 2.5 * 72.0 / 25.4; + drag_on_ruler(&ctx, &mut app, 28.4, 28.4, false); + let positions = |app: &VectorcraftApp| current(app).unwrap().1.iter().map(|s| s.position).collect::>(); + assert_eq!(positions(&app).len(), 2); + assert!((positions(&app)[0] - 4.0 * tick).abs() < 1e-9, "{:?}", positions(&app)); + set_pstate(&ctx, "tabs-sel", 1usize); + let steps = app.session.active().unwrap().history.undo.len(); + // The click is 3.3 pt (5.8 px) right of the stop, past the 5 px hit tolerance and nearest its tick. + drag_on_ruler(&ctx, &mut app, 4.0 * tick + 3.3, 4.0 * tick + 3.3, false); + assert_eq!(positions(&app).len(), 2, "{:?}", positions(&app)); + assert_eq!(pstate::(&ctx, "tabs-sel"), 0); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps, "no undo step"); + } + + /// With Snap to Unit off, Shift held during the drag puts the stop on the ruler's nearest tick. + #[test] + fn shift_drag_snaps_a_stop_to_the_nearest_tick() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap(); + app.session.execute("text.tabs.set", &json!({"stops": [{"position": 50}]})).unwrap(); + let ctx = egui::Context::default(); + let position = |app: &VectorcraftApp| current(app).unwrap().1[0].position; + drag_on_ruler(&ctx, &mut app, 50.0, 13.4, false); + assert!((position(&app) - 13.4).abs() < 1.0, "{}", position(&app)); + let from = position(&app); + drag_on_ruler(&ctx, &mut app, from, 41.6, true); + assert_eq!(position(&app), 40.0); + // In an inches document the ticks divide the inch in half, not in ten (#2827), so the + // nearest one to 100 pt is 99 pt -- 1 3/8 in, an eighth of an inch from 1 1/4. + app.session.execute("document.setUnits", &json!({"units": "in"})).unwrap(); + drag_on_ruler(&ctx, &mut app, 40.0, 100.0, true); + assert!((position(&app) - 99.0).abs() < 1e-9, "{}", position(&app)); + assert_eq!((position(&app) / 72.0 * 8.0).round(), position(&app) / 72.0 * 8.0, "a binary fraction of an inch"); + } + /// One frame of the panel menu with `events` → the rows' texts and where they are painted. fn menu_frame(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec) -> Vec<(String, egui::Rect)> { let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 400.0)); diff --git a/crates/ui-egui/src/panels/tests_units.rs b/crates/ui-egui/src/panels/tests_units.rs index 86c55e0264..da5be17f4d 100644 --- a/crates/ui-egui/src/panels/tests_units.rs +++ b/crates/ui-egui/src/panels/tests_units.rs @@ -117,6 +117,27 @@ fn new_documents_start_in_the_general_preference() { assert_eq!((d.units, d.artboards[0].rect.width()), (Unit::Millimeters, 612.0)); } +/// A label spelled down the left ruler is tall, and a sixteenth-inch step does not always leave +/// room for a long one: at zoom 12 the labels are 54 pt apart while "-0.0625" reaches 60.5 pt, so +/// the ruler leaves that label out rather than drawing it over its neighbour. Every tick stays. +#[test] +fn a_long_vertical_label_does_not_fit_a_sixteenth_inch_step() { + use crate::canvas::vertical_label_height; + use vectorcraft_doc::Unit; + // One character is one line; each further character adds a line. + assert_eq!(vertical_label_height(1), 9.5); + assert_eq!(vertical_label_height(2), 18.0); + assert_eq!(vertical_label_height(7), 60.5); + // The gap a label has to fit into, at the zoom where a sixteenth is first chosen and beyond. + let gap = |zoom: f64| Unit::Inches.ruler_step(zoom) * Unit::Inches.points() * zoom; + assert!((gap(12.0) - 54.0).abs() < 1e-9, "{}", gap(12.0)); + assert!(vertical_label_height(7) > gap(12.0) as f32, "a seven-character label has to be left out"); + // The labels this ruler actually writes below an inch are six characters, which do fit. + assert!(vertical_label_height("0.0625".chars().count()) < gap(12.0) as f32); + // Zoomed further in the gap grows and even a long label fits. + assert!(vertical_label_height(7) < gap(20.0) as f32, "{}", gap(20.0)); +} + #[test] fn ruler_labels_have_the_steps_decimals() { use crate::canvas::ruler_label; @@ -125,6 +146,13 @@ fn ruler_labels_have_the_steps_decimals() { assert_eq!(ruler_label(1.25, 0.05), "1.25"); assert_eq!(ruler_label(-0.0000001, 0.5), "0"); assert_eq!(ruler_label(-2.5, 0.5), "-2.5"); + // An inch ruler's binary steps keep their exact value: rounding the step's magnitude wrote + // 1/16 as "0.06" and 1/8 as "0.13" (#2827). + assert_eq!(ruler_label(0.0625, 0.0625), "0.0625"); + assert_eq!(ruler_label(0.125, 0.125), "0.125"); + assert_eq!(ruler_label(0.75, 0.25), "0.75"); + assert_eq!(ruler_label(1.0, 0.0625), "1"); + assert_eq!(ruler_label(1.1875, 0.0625), "1.1875"); } #[test] diff --git a/crates/ui-egui/src/panels/transform.rs b/crates/ui-egui/src/panels/transform.rs index 66a6f5f2fd..e10fde0917 100644 --- a/crates/ui-egui/src/panels/transform.rs +++ b/crates/ui-egui/src/panels/transform.rs @@ -1,7 +1,8 @@ //! Transform panel: reference point, X/Y/W/H with the constrain link, rotate and shear, flips, //! live-shape properties and the Scale Corners / Scale Strokes & Effects options. While the -//! Artboard tool is in use it shows and edits the active artboard's X/Y/W/H instead, and with only -//! ruler guides selected their X (vertical guides) and Y (horizontal ones). +//! Artboard tool is in use it shows and edits the active artboard's X/Y/W/H instead (a new W or H +//! resizes every selected artboard), and with only ruler guides selected their X (vertical guides) +//! and Y (horizontal ones). use egui::Ui; use serde_json::json; @@ -62,28 +63,34 @@ pub fn reference_locator(ui: &mut Ui, refi: usize) { } } -/// Set artboard `index` (now at `r`) to a new X, Y, W or H from reference point `refi` -/// ([`artboard_rect`]) with `artboard.setProps`, passing the Artboard tool's Move and Scale Artwork -/// with Artboard options as `moveArt` and `scaleArt`; an error is shown in the status bar. -pub fn set_artboard(app: &mut VectorcraftApp, index: usize, r: Rect, refi: usize, xywh: [Option; 4], link: bool) { +/// Set artboard `index` to a new X, Y, W or H from reference point `refi` ([`artboard_rect`]) with +/// `artboard.setProps`, passing the Artboard tool's Move and Scale Artwork with Artboard options as +/// `moveArt` and `scaleArt`; an error is shown in the status bar. A new X or Y moves artboard +/// `index` alone; a new W or H resizes every selected artboard about its own reference point +/// ([`crate::panels::artboards::resized_with`]), in one undo step. +pub fn set_artboard(app: &mut VectorcraftApp, index: usize, refi: usize, xywh: [Option; 4], link: bool) { let [x, y, w, h] = xywh; - let n = artboard_rect(r, refi, x, y, w, h, link); let scale_art = crate::panels::artboards::scale_art(app); let move_art = crate::panels::artboards::move_art(app); - let p = json!({"index": index, "x": n.x0, "y": n.y0, "width": n.width(), "height": n.height(), "scaleArt": scale_art, "moveArt": move_art}); - if let Err(e) = app.run("artboard.setProps", p) { + let indices = if x.is_none() && y.is_none() { crate::panels::artboards::resized_with(app, index) } else { vec![index] }; + let common = json!({"scaleArt": scale_art, "moveArt": move_art}); + let r = crate::panels::artboards::set_props(app, &indices, common, |i, r| { + let n = artboard_rect(r, refi, x, y, w, h, link); + Some(json!({"index": i, "x": n.x0, "y": n.y0, "width": n.width(), "height": n.height()})) + }); + if let Err(e) = r { app.status(e); } } -/// The Artboard tool's view of the panel: the active artboard's position and size. +/// The Artboard tool's view of the panel: the active artboard's position and size ([`set_artboard`]). fn artboard_fields(app: &mut VectorcraftApp, ui: &mut Ui, index: usize, r: Rect) { let units = app.session.general_unit(); let origin = app.ruler_origin(); let refi = reference_index(ui); let link = proportional(app, ui); let rp = vectorcraft_geom::reference_point(r, refi); - let set = |app: &mut VectorcraftApp, x, y, w, h| set_artboard(app, index, r, refi, [x, y, w, h], link); + let set = |app: &mut VectorcraftApp, x, y, w, h| set_artboard(app, index, refi, [x, y, w, h], link); ui.horizontal(|ui| { reference_locator(ui, refi); ui.add_space(4.0); diff --git a/crates/ui-egui/src/panels/variables.rs b/crates/ui-egui/src/panels/variables.rs index 96f32e1322..ca1fc29f60 100644 --- a/crates/ui-egui/src/panels/variables.rs +++ b/crates/ui-egui/src/panels/variables.rs @@ -317,10 +317,10 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.separator(); if widgets::menu_item(ui, tl!("Import Data Sets…"), true, false) { - import_datasets(app); + crate::picks::button(app, import_datasets); } if widgets::menu_item(ui, tl!("Export Data Sets…"), !vars.is_empty(), false) { - export_datasets(app); + crate::picks::button(app, export_datasets); } ui.separator(); // What the highlighted variable drives, selected — its bindings are left alone. @@ -390,6 +390,29 @@ mod tests { assert_eq!(app.run("dataset.list", json!({})).unwrap()["datasets"][0]["matches"], json!(true)); } + /// Choosing a data set, or stepping to one with the arrows, shows a status message when no + /// object is bound to a variable it has a value for, for example after Import Data Sets… + /// defines new variables. With such an object bound, it shows none. + #[test] + fn a_data_set_with_nothing_bound_shows_a_status_message() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 300, "height": 200})).unwrap(); + let t = app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "x"})).unwrap()["id"].as_u64().unwrap(); + app.run("dataset.import", json!({"csv": "name,Name\nA,Ann\nB,Bob\n"})).unwrap(); + let message = |row: &str| format!("nothing in data set {row} was applied: no object is bound to a variable it has a value for"); + app.run("dataset.select", json!({"name": "A"})).unwrap(); + assert_eq!(app.ui.status, message("A")); + app.run("dataset.next", json!({})).unwrap(); + assert_eq!(app.ui.status, message("B")); + app.run("dataset.prev", json!({})).unwrap(); + assert_eq!(app.ui.status, message("A")); + + app.ui.status.clear(); + app.run("variable.bind", json!({"variable": "Name", "ids": [t]})).unwrap(); + app.run("dataset.select", json!({"name": "B"})).unwrap(); + assert_eq!(app.ui.status, ""); + } + #[test] fn the_panel_menu_lists_the_row_commands() { let mut app = app_with_data(); diff --git a/crates/ui-egui/src/render_worker.rs b/crates/ui-egui/src/render_worker.rs index 59488f6440..4dcf879b84 100644 --- a/crates/ui-egui/src/render_worker.rs +++ b/crates/ui-egui/src/render_worker.rs @@ -63,6 +63,14 @@ impl Worker { Some(Self { tx, rx, pending: None }) } + /// A controlled worker: tests receive jobs and decide when a frame completes. + #[cfg(test)] + pub(crate) fn test_channel() -> (Self, Receiver, Sender) { + let (tx, jobs) = channel(); + let (done_tx, rx) = channel(); + (Self { tx, rx, pending: None }, jobs, done_tx) + } + pub fn submit(&mut self, job: Job) { if self.pending.as_ref() == Some(&job.key) { return; diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 9d0b3aea64..7773428e0c 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -1014,4 +1014,16 @@ mod tests { assert!(assign(&mut ov, "symbol.breakLink", Some("Cmd+Alt+Shift+F9"), true).is_ok()); assert_eq!(effective_in(&ov, "symbol.breakLink").as_deref(), Some("Cmd+Alt+Shift+F9")); } + + /// #2991: Enter Isolation Mode has no default key but runs on the selection, so it belongs in + /// Edit › Keyboard Shortcuts. + #[test] + fn enter_isolation_mode_command_is_listed_and_assignable() { + let e = entry("object.isolate").expect("listed"); + assert_eq!((e.label.as_str(), e.group.as_str(), e.is_tool), ("Enter Isolation Mode", "Object", false)); + assert_eq!(default_of("object.isolate"), None); + let mut ov = BTreeMap::new(); + assign(&mut ov, "object.isolate", Some("Cmd+Alt+Shift+F11"), false).unwrap(); + assert_eq!(effective_in(&ov, "object.isolate").as_deref(), Some("Cmd+Alt+Shift+F11")); + } } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index a27c7ba5f7..d6e5a179ed 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -224,6 +224,9 @@ pub struct ViewFlags { pub corner_widgets: bool, /// View → Snap to Pixel. pub snap_to_pixel: bool, + /// View → Snap to Glyph. + #[serde(default)] + pub snap_to_glyph: bool, /// View → Show/Hide Text Threads. pub text_threads: bool, /// View → Show/Hide Gradient Annotator. @@ -252,6 +255,7 @@ impl Default for ViewFlags { trim_view: false, corner_widgets: true, snap_to_pixel: false, + snap_to_glyph: false, text_threads: true, gradient_annotator: true, hidden_chars: false, @@ -488,6 +492,11 @@ pub struct UiState { /// dialog opens on them (#1152). #[serde(default)] pub offset_path: Value, + /// The Simplify dialog's fields confirmed last with "Open this dialog with these settings next + /// time" ticked (null: not ticked): Object › Path › Simplify opens the dialog on them instead + /// of the Simplify slider. + #[serde(default)] + pub simplify: Value, /// The Move dialog's checkboxes as it was last confirmed with (copy, objects, preview; null: /// never used): it opens with them. #[serde(default)] @@ -501,7 +510,7 @@ pub struct UiState { /// becoming active, leaves it. #[serde(skip)] pub home: Option<(Option, usize)>, - /// Layers panel › Panel Options… (row size, thumbnails, Show Layers Only). + /// Layers panel › Panel Options… (row size, thumbnails, Show Layers Only, Locate Selected Objects). #[serde(default)] pub layers_panel: crate::panels::layers::PanelOptions, /// The Layers panel's Filter (`ui.layersFilter`). It is not saved and lasts the session, as the @@ -823,6 +832,7 @@ impl Default for UiState { dxf_options: Value::Null, eps_options: Value::Null, offset_path: Value::Null, + simplify: Value::Null, move_options: Value::Null, dxf_import: Value::Null, home: None, diff --git a/crates/ui-egui/src/sysclip.rs b/crates/ui-egui/src/sysclip.rs index 42aed4b4eb..2eedc91623 100644 --- a/crates/ui-egui/src/sysclip.rs +++ b/crates/ui-egui/src/sysclip.rs @@ -12,7 +12,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc::channel; use serde_json::{Value, json}; -use vectorcraft_engine::cmd::clipboard::{BITMAP, EMF, EPS, Flavour, PASTE_ORDER, PDF, SVG, TEXT, looks_like_svg, names_a_picture}; +use vectorcraft_engine::cmd::clipboard::{AI, BITMAP, EMF, EPS, Flavour, PASTE_ORDER, PDF, SVG, TEXT, looks_like_svg, names_a_picture}; use crate::VectorcraftApp; use crate::background::{self, Writer}; @@ -59,6 +59,7 @@ pub(crate) fn import_command(f: &Flavour, center: Option<[f64; 2]>) -> (&'static } SVG => ("clipboard.importSvg", json!({ "dataBase64": b64(), "center": center })), PDF => ("clipboard.importPdf", json!({ "dataBase64": b64(), "center": center })), + AI => ("clipboard.importPdf", json!({ "dataBase64": b64(), "editingData": true, "center": center })), EPS => ("clipboard.importEps", json!({ "dataBase64": b64(), "center": center })), EMF => ("clipboard.importEmf", json!({ "dataBase64": b64(), "center": center })), mime => ("clipboard.importImage", json!({ "dataBase64": b64(), "mime": mime, "center": center })), diff --git a/crates/ui-egui/src/tests_aisave.rs b/crates/ui-egui/src/tests_aisave.rs index b6af7a31b4..03a17dd1d2 100644 --- a/crates/ui-egui/src/tests_aisave.rs +++ b/crates/ui-egui/src/tests_aisave.rs @@ -35,9 +35,30 @@ fn save_as_ai_writes_a_pdf_that_reopens_editable() { fn save_a_copy_as_ai_keeps_the_path() { let (mut app, written) = app("/tmp/copy.ai"); app.session.doc_mut().unwrap().path = Some("/tmp/doc.vectorcraft".into()); - app.run("file.saveCopy", json!({"compression": {"compressText": false}})).unwrap(); + // Save a Copy asks for the .ai options like Save As (#3141), then writes. + let r = app.run("file.saveCopy", json!({"compression": {"compressText": false}})).unwrap(); + assert_eq!(r["pending"], "saveOptions", "{r}"); + crate::dialogs::confirm(&mut app).unwrap(); let w = written.borrow(); assert_eq!(w[0].0, "/tmp/copy.ai"); assert!(vectorcraft_pdf::editing(&w[0].1).is_some_and(|e| e.intact)); assert_eq!(app.session.active().unwrap().path.as_deref(), Some("/tmp/doc.vectorcraft")); } + +/// A document last saved as legacy version 7 .ai: Save a Copy as .ai asks for the options (Version +/// included) instead of silently writing another legacy file, and choosing PDF-compatible there +/// writes a PDF (#3141). +#[test] +fn save_a_copy_as_ai_asks_for_the_version() { + let (mut app, written) = app("/tmp/copy.ai"); + app.run("file.saveAs", json!({"path": "/tmp/legacy.ai", "options": {"aiVersion": "7"}})).unwrap(); + written.borrow_mut().clear(); + let r = app.run("file.saveCopy", Value::Null).unwrap(); + assert_eq!(r["pending"], "saveOptions", "{r}"); + assert!(written.borrow().is_empty()); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!((d.str("format").as_str(), d.str("__action").as_str()), ("ai", "file.saveCopy")); + d.fields.insert("aiVersion".into(), json!("pdf")); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(written.borrow()[0].1.starts_with(b"%PDF")); +} diff --git a/crates/ui-egui/src/tests_background.rs b/crates/ui-egui/src/tests_background.rs index b793e695f1..1bb33d4cd1 100644 --- a/crates/ui-egui/src/tests_background.rs +++ b/crates/ui-egui/src/tests_background.rs @@ -178,6 +178,7 @@ pub(super) fn status_bar_texts(app: &mut VectorcraftApp) -> Vec { } } let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::chrome::status_bar(app, ui)); out.textures_delta.clear(); let mut v = vec![]; diff --git a/crates/ui-egui/src/tests_contextmenu.rs b/crates/ui-egui/src/tests_contextmenu.rs index 67ddbfcdc1..33f604af00 100644 --- a/crates/ui-egui/src/tests_contextmenu.rs +++ b/crates/ui-egui/src/tests_contextmenu.rs @@ -185,10 +185,14 @@ fn the_menu_follows_the_selection() { let (a, b) = (rect(&mut app, 0.0, 0.0), rect(&mut app, 50.0, 50.0)); app.run("select.set", json!({"ids": [a.0, b.0]})).unwrap(); let l = labels(&menus::context_items(&app)); - for label in ["Group", "Join", "Make Clipping Mask", "Make Compound Path", "Bring to Front", "Move…"] { + for label in ["Group", "Join", "Make Clipping Mask", "Make Compound Path", "Objects on Path", "Bring to Front", "Move…"] { assert!(l.contains(&label), "{label} in {l:?}"); } assert!(!l.contains(&"Ungroup") && !l.contains(&"Isolate Selected Group")); + // Objects on Path chooses its tool, which attaches the selection to the path clicked next. + menus::invoke(&mut app, "object.objectsOnPath.attach", json!({})); + assert_eq!(app.session.tool_id(), "objectsOnPath"); + app.select_tool("selection"); app.run("object.group", json!({})).unwrap(); let l = labels(&menus::context_items(&app)); assert!(l.contains(&"Ungroup") && l.contains(&"Isolate Selected Group")); diff --git a/crates/ui-egui/src/tests_home.rs b/crates/ui-egui/src/tests_home.rs index d998573f24..6e4aa29917 100644 --- a/crates/ui-egui/src/tests_home.rs +++ b/crates/ui-egui/src/tests_home.rs @@ -133,3 +133,111 @@ fn home_lists_recent_files_and_a_click_opens_one() { assert!(app.session.documents().is_empty()); assert!(!app.ui.status.is_empty(), "a file that can't be opened says so"); } + +/// One Home screen frame with `events`: the filled rectangles drawn in `fill`, and the cursor. +fn home_fills(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec, fill: egui::Color32) -> (Vec, egui::CursorIcon) { + fn walk(s: &egui::Shape, fill: egui::Color32, out: &mut Vec) { + match s { + egui::Shape::Rect(r) if r.fill == fill => out.push(r.rect), + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, fill, out)), + _ => {} + } + } + let raw = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 900.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| canvas::show(app, ui)); + out.textures_delta.clear(); + let mut rects = vec![]; + out.shapes.iter().for_each(|c| walk(&c.shape, fill, &mut rects)); + (rects, out.platform_output.cursor_icon) +} + +/// A Recent Files row is one button: the pointer over its folder lights the whole row (icon, name +/// and folder) with a pointing hand, and a click there opens the file like a click on its name. +#[test] +fn a_recent_file_row_lights_up_and_opens_from_anywhere_on_it() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let dir = std::env::temp_dir().join("vectorcraft-home-recent-row"); + app.ui.recent_files = vec![dir.join("Gone.svg").to_string_lossy().into_owned()]; + let texts = home_texts(&mut app, &ctx, vec![]); + let rect_of = |s: &str| texts.iter().find(|(t, _)| t == s).map(|(_, r)| *r).unwrap(); + let (name, folder) = (rect_of("Gone.svg"), rect_of(&dir.to_string_lossy())); + let hover = crate::theme::Tokens::get(&ctx).hover; + let lit = |rects: &[egui::Rect]| rects.iter().any(|r| r.contains(name.center()) && r.contains(folder.center())); + let (rects, cursor) = home_fills(&mut app, &ctx, vec![], hover); + assert!(!lit(&rects) && cursor != egui::CursorIcon::PointingHand, "no highlight without the pointer"); + let at = folder.center(); + home_fills(&mut app, &ctx, vec![egui::Event::PointerMoved(at)], hover); + let (rects, cursor) = home_fills(&mut app, &ctx, vec![], hover); + assert!(lit(&rects), "the pointer over the folder lights the whole row"); + assert_eq!(cursor, egui::CursorIcon::PointingHand); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + home_texts(&mut app, &ctx, vec![press(true)]); + home_texts(&mut app, &ctx, vec![press(false)]); + assert!(app.session.documents().is_empty()); + assert!(!app.ui.status.is_empty(), "the click on the folder tried to open the file"); +} + +/// One Home screen frame in a `w`×`h` window at `time` with `events`: the texts visible (inside +/// their clip rect and the window) and where. +fn visible_home_texts( + app: &mut VectorcraftApp, + ctx: &egui::Context, + (w, h): (f32, f32), + time: f64, + events: Vec, +) -> Vec<(String, egui::Rect)> { + fn walk(s: &egui::Shape, clip: egui::Rect, out: &mut Vec<(String, egui::Rect)>) { + match s { + egui::Shape::Text(t) if clip.contains_rect(t.visual_bounding_rect()) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())), + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, out)), + _ => {} + } + } + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(w, h)); + let raw = egui::RawInput { screen_rect: Some(screen), time: Some(time), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| canvas::show(app, ui)); + out.textures_delta.clear(); + let mut texts = vec![]; + out.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect.intersect(screen), &mut texts)); + texts +} + +/// Home scrolls when it is taller than the window: in a short window the Community section and +/// the last preset card are below the fold, the wheel brings them into view, and a card scrolled +/// into view still opens its preset. +#[test] +fn home_scrolls_in_a_short_window() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let dir = std::env::temp_dir().join("vectorcraft-home-scroll"); + app.ui.recent_files = (0..6).map(|i| dir.join(format!("Drawing {i}.svg")).to_string_lossy().into_owned()).collect(); + let size = (800.0, 300.0); + let has = |texts: &[(String, egui::Rect)], s: &str| texts.iter().any(|(t, _)| t == s); + let texts = visible_home_texts(&mut app, &ctx, size, 0.0, vec![]); + assert!(has(&texts, "Welcome to VectorCraft"), "{texts:?}"); + assert!(!has(&texts, "Community"), "below the fold at first"); + let at = egui::pos2(400.0, 150.0); + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -5000.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + }; + visible_home_texts(&mut app, &ctx, size, 0.1, vec![egui::Event::PointerMoved(at), wheel]); + let mut texts = vec![]; + for i in 2..40 { + texts = visible_home_texts(&mut app, &ctx, size, f64::from(i) * 0.1, vec![]); + } + assert!(has(&texts, "Community"), "the wheel reaches the bottom: {texts:?}"); + assert!(!has(&texts, "Welcome to VectorCraft"), "the top scrolled away"); + // The last preset card, scrolled into view, still takes a click. + let card = texts.iter().find(|(t, _)| t.starts_with("Social Square Post")).map(|(_, r)| r.center()).unwrap(); + let press = |pressed| egui::Event::PointerButton { pos: card, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + visible_home_texts(&mut app, &ctx, size, 4.0, vec![egui::Event::PointerMoved(card), press(true)]); + visible_home_texts(&mut app, &ctx, size, 4.1, vec![press(false)]); + assert_eq!(app.session.documents().len(), 1, "the card opened its preset"); +} diff --git a/crates/ui-egui/src/tests_labels.rs b/crates/ui-egui/src/tests_labels.rs index f7d0930c96..8d62e4db1e 100644 --- a/crates/ui-egui/src/tests_labels.rs +++ b/crates/ui-egui/src/tests_labels.rs @@ -86,7 +86,7 @@ fn effect_menu_lists_the_artistic_filters_before_blur() { let entries = menus::menu_entries(&app); let artistic: Vec<_> = entries.iter().filter(|e| e.path == ["Effect", "Artistic"]).collect(); let labels: Vec<&str> = artistic.iter().map(|e| e.label.as_str()).collect(); - assert_eq!(labels, ["Cutout…", "Film Grain…", "Neon Glow…", "Poster Edges…"]); + assert_eq!(labels, ["Cutout…", "Film Grain…", "Neon Glow…", "Plastic Wrap…", "Poster Edges…", "Smudge Stick…", "Sponge…", "Watercolor…"]); assert!(artistic.iter().all(|e| e.command.as_deref() == Some("effect.dialog"))); assert_eq!(artistic[2].params, json!({"effect": "artistic.neonGlow"})); let at = |name: &str| entries.iter().position(|e| e.path == ["Effect", name]).unwrap(); @@ -171,18 +171,47 @@ fn effect_menu_lists_the_texture_filters_between_sharpen_and_video() { assert!(at("Sharpen") < at("Texture") && at("Texture") < at("Video")); } -/// Effect › Sketch, between Sharpen and the raster Stylize: Halftone Pattern opens its dialog. +/// Effect › Sketch, between Sharpen and the raster Stylize: the raster sketch filters open their dialogs. #[test] fn effect_menu_lists_the_sketch_filters_between_sharpen_and_stylize() { let app = app(); let entries = menus::menu_entries(&app); let sketch: Vec<_> = entries.iter().filter(|e| e.path == ["Effect", "Sketch"]).collect(); let labels: Vec<&str> = sketch.iter().map(|e| e.label.as_str()).collect(); - assert_eq!(labels, ["Halftone Pattern…"]); - assert_eq!(sketch[0].command.as_deref(), Some("effect.dialog")); - assert_eq!(sketch[0].params, json!({"effect": "sketch.halftonePattern"})); + assert_eq!( + labels, + [ + "Bas Relief…", + "Chalk & Charcoal…", + "Charcoal…", + "Chrome…", + "Graphic Pen…", + "Halftone Pattern…", + "Note Paper…", + "Photocopy…", + "Plaster…", + "Reticulation…", + "Stamp…" + ] + ); + assert!(sketch.iter().all(|e| e.command.as_deref() == Some("effect.dialog"))); + assert_eq!(sketch[0].params, json!({"effect": "sketch.basRelief"})); + assert_eq!(sketch[1].params, json!({"effect": "sketch.chalkCharcoal"})); + assert_eq!(sketch[2].params, json!({"effect": "sketch.charcoal"})); + assert_eq!(sketch[3].params, json!({"effect": "sketch.chrome"})); + assert_eq!(sketch[4].params, json!({"effect": "sketch.graphicPen"})); + assert_eq!(sketch[5].params, json!({"effect": "sketch.halftonePattern"})); + assert_eq!(sketch[6].params, json!({"effect": "sketch.notePaper"})); + assert_eq!(sketch[7].params, json!({"effect": "sketch.photocopy"})); + assert_eq!(sketch[8].params, json!({"effect": "sketch.plaster"})); + assert_eq!(sketch[9].params, json!({"effect": "sketch.reticulation"})); + assert_eq!(sketch[10].params, json!({"effect": "sketch.stamp"})); let at = |label: &str| entries.iter().position(|e| e.path[0] == "Effect" && e.label == label).unwrap(); - assert!(at("Unsharp Mask…") < at("Halftone Pattern…") && at("Halftone Pattern…") < at("Glowing Edges…")); + assert!(at("Unsharp Mask…") < at("Chalk & Charcoal…") && at("Chalk & Charcoal…") < at("Chrome…")); + assert!(at("Chrome…") < at("Graphic Pen…") && at("Graphic Pen…") < at("Halftone Pattern…")); + assert!(at("Halftone Pattern…") < at("Note Paper…") && at("Note Paper…") < at("Plaster…")); + assert!(at("Plaster…") < at("Reticulation…")); + assert!(at("Reticulation…") < at("Glowing Edges…")); } /// Effect › Stylize under Raster Effects, between Sharpen and Texture: Glowing Edges opens its diff --git a/crates/ui-egui/src/tests_picks.rs b/crates/ui-egui/src/tests_picks.rs index 2c071fa2f1..e2198699a2 100644 --- a/crates/ui-egui/src/tests_picks.rs +++ b/crates/ui-egui/src/tests_picks.rs @@ -221,6 +221,33 @@ fn load_profile_asks_off_the_ui_thread() { assert!(app.ui.status.contains("/no/such/profile.icc"), "color.loadProfile ran on the path: {}", app.ui.status); } +/// The Variables panel menu's Import Data Sets… and Export Data Sets… ask off the UI thread: the +/// data sets in the file picked are loaded, and the data sets are written to the path the dialog +/// answers. +#[test] +fn variables_panel_data_sets_ask_off_the_ui_thread() { + let (mut app, shown, _) = app(); + app.run("file.new", json!({"width": 100, "height": 80})).unwrap(); + let dir = std::env::temp_dir().join(format!("vc-picks-data-sets-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (csv, out) = (dir.join("sets.csv"), dir.join("out.csv")); + std::fs::write(&csv, "name,Name\nB,y\n").unwrap(); + let sets = |app: &VectorcraftApp| app.session.doc().unwrap().doc.variables.datasets.iter().map(|d| d.name.clone()).collect::>(); + + click(&mut app, "Import Data Sets…", crate::panels::variables::menu); + assert!(matches!(shown.requests().as_slice(), [PickRequest::Open(_)])); + shown.answer(&[&csv.to_string_lossy()]); + poll(&mut app); + assert_eq!(sets(&app), ["B"], "{}", app.ui.status); + + click(&mut app, "Export Data Sets…", crate::panels::variables::menu); + assert!(matches!(shown.requests().as_slice(), [PickRequest::Save(_)])); + shown.answer(&[&out.to_string_lossy()]); + poll(&mut app); + assert!(std::fs::read_to_string(&out).is_ok_and(|text| text.starts_with("name,Name\n")), "{}", app.ui.status); + let _ = std::fs::remove_dir_all(dir); +} + /// The Swatches libraries menu's Other Library… asks off the UI thread; the file picked (another /// document) loads as a library and opens in the library panel. #[test] diff --git a/crates/ui-egui/src/tests_sysclip_emf.rs b/crates/ui-egui/src/tests_sysclip_emf.rs index 426b5e120d..1d79da98bd 100644 --- a/crates/ui-egui/src/tests_sysclip_emf.rs +++ b/crates/ui-egui/src/tests_sysclip_emf.rs @@ -4,7 +4,8 @@ use serde_json::json; use vectorcraft_doc::NodeKind; use vectorcraft_engine::Session; -use vectorcraft_engine::cmd::clipboard::{EMF, EPS, Flavour, PASTE_ORDER, PDF, PNG, TEXT, file_flavour}; +use vectorcraft_engine::cmd::clipboard::{AI, EMF, EPS, Flavour, PASTE_ORDER, PDF, PNG, TEXT, file_flavour}; +use vectorcraft_testkit::ai; use crate::sysclip::import_command; use crate::tests_sysclip::{app, blue_png, copy_elsewhere, pasted, run}; @@ -58,3 +59,17 @@ fn an_eps_from_another_app_pastes_as_vectors() { assert_eq!(file_flavour("equation.dat", &eps, &PASTE_ORDER), Some(EPS)); assert_eq!(file_flavour("equation.eps", &eps, &[TEXT]), None); } + +/// A `.ai` copied in a file manager pastes the objects of its editing data, named and in their +/// layers' stacking order, not its page's. +#[test] +fn a_copied_ai_file_pastes_from_its_editing_data() { + let file = ai::ai(&ai::sample_data(), ai::page_pdf()); + assert_eq!(file_flavour("art.ai", &file, &PASTE_ORDER), Some(AI)); + let (cmd, params) = import_command(&Flavour { mime: AI, data: file.clone() }, None); + assert_eq!((cmd, ¶ms["editingData"]), ("clipboard.importPdf", &json!(true))); + let (mut app, _) = app(); + app.paste_from_host(&egui::Context::default(), Flavour { mime: AI, data: file }, egui::Modifiers::COMMAND); + let names: Vec = pasted(&app).iter().map(|n| n.name.clone().unwrap_or_default()).collect(); + assert_eq!(names, ["Pair", "Ring", "Window", "Shaded", "", "Sub", ""]); +} diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 2844eeda7c..b2d9ab076e 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -366,6 +366,8 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result crate::dialogs::liquify::open(app, tool), // The freehand tools: their Tool Options (Fidelity, fill, the tolerances, the brush size). _ if crate::dialogs::freehand::TOOLS.contains(&tool) => crate::dialogs::freehand::open(app, tool), + // The Live Paint Selection tool: its Tool Options (what a click selects, the highlight). + "livePaintSelection" => crate::dialogs::live_paint_selection::open(app), // The Symbolism tools: the brush they share. _ if vectorcraft_tools::settings::SYMBOLISM.contains(&tool) => Ok(crate::dialogs::symbolism_options::open(app, tool)), // The graph tools: Graph Type for the selected graph. diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index b8a5f6e4d2..e154a78766 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -101,11 +101,22 @@ pub fn primary_button(ui: &mut Ui, text: &str) -> Response { /// [`primary_button`], greyed out and not clickable unless `enabled`. pub fn primary_button_enabled(ui: &mut Ui, text: &str, enabled: bool) -> Response { + primary_button_sized(ui, text, enabled, 72.0) +} + +/// Primary dialog button with a minimum width, for aligned action columns. +pub(crate) fn primary_button_width(ui: &mut Ui, text: &str, min_width: f32) -> Response { + primary_button_sized(ui, text, true, min_width) +} + +/// Draws a primary button at least `min_width` wide, growing to fit the translated label. +/// Returns its response with the enabled state and screen-reader name preserved. +fn primary_button_sized(ui: &mut Ui, text: &str, enabled: bool, min_width: f32) -> Response { let t = Tokens::get(ui.ctx()); let fg = if enabled { Color32::WHITE } else { t.text_disabled }; let galley = ui.painter().layout_no_wrap(tl!(text).to_string(), theme::semibold(12.5), fg); let w = galley.size().x + 32.0; - let (rect, resp) = ui.allocate_exact_size(vec2(w.max(72.0), 28.0), if enabled { Sense::click() } else { Sense::hover() }); + let (rect, resp) = ui.allocate_exact_size(vec2(w.max(min_width), 28.0), if enabled { Sense::click() } else { Sense::hover() }); let bg = match (enabled, resp.hovered()) { (false, _) => t.input, (true, true) => t.accent, @@ -122,10 +133,15 @@ pub fn primary_button_enabled(ui: &mut Ui, text: &str, enabled: bool) -> Respons /// The quiet secondary button (dialog Cancel). pub fn secondary_button(ui: &mut Ui, text: &str) -> Response { + secondary_button_width(ui, text, 72.0) +} + +/// Secondary dialog button with a minimum width, for aligned action columns. +pub(crate) fn secondary_button_width(ui: &mut Ui, text: &str, min_width: f32) -> Response { let t = Tokens::get(ui.ctx()); let galley = ui.painter().layout_no_wrap(tl!(text).to_string(), theme::semibold(12.5), t.text); let w = galley.size().x + 32.0; - let (rect, resp) = ui.allocate_exact_size(vec2(w.max(72.0), 28.0), Sense::click()); + let (rect, resp) = ui.allocate_exact_size(vec2(w.max(min_width), 28.0), Sense::click()); ui.painter().rect_filled(rect, CornerRadius::same(6), if resp.hovered() { t.hover } else { t.button }); ui.painter().galley(rect.center() - galley.size() / 2.0, galley, t.text); resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), tl!(text))); @@ -2018,8 +2034,9 @@ pub enum PanelDrag { /// is dropped on takes `params` (`{swatch}`, `{color}`, `{gradient}`…; null for a colour group, /// which paints nothing) through the active proxy's `paint.setFill`/`paint.setStroke`; the /// Gradient panel's ramp takes its colour as a stop; the Swatches panel moves `rows`, or makes - /// a swatch of a paint dragged from elsewhere. - Paint { paint: Paint, params: serde_json::Value, rows: Option }, + /// a swatch of a paint dragged from elsewhere. `library`: the Libraries panel colour it is + /// (library id, colour name), which that panel moves to where it is dropped. + Paint { paint: Paint, params: serde_json::Value, rows: Option, library: Option<(String, String)> }, /// The Appearance panel's thumbnail: art it is dropped on takes object `0`'s appearance /// (`appearance.copyFrom`); the Graphic Styles panel makes a style of it. Appearance(vectorcraft_doc::NodeId), @@ -2038,8 +2055,13 @@ pub enum PanelDrag { /// dropped on takes it (`brush.apply`). Brush { name: String, def: serde_json::Value }, /// A Libraries panel graphic (`item`: its id in `library`): the canvas places a copy centred - /// where it is dropped (`library.use`). + /// where it is dropped (`library.use`); the panel moves it to where it is dropped. LibraryGraphic { library: String, item: String }, + /// A Libraries panel text style (`item`: its name in `library`), which the panel moves to where + /// it is dropped. + LibraryItem { library: String, kind: vectorcraft_engine::cmd::library::ItemKind, item: String }, + /// A Libraries panel group, by its header, which the panel moves to where it is dropped. + LibraryGroup { library: String, group: String }, } /// A panel list `zone` that takes art dragged off the canvas: outlined while art is held over it; @@ -2072,7 +2094,7 @@ impl PanelDrag { g.geom = None; g.freeform = None; } - Self::Paint { params: crate::panels::paint_params(&paint), paint, rows: None } + Self::Paint { params: crate::panels::paint_params(&paint), paint, rows: None, library: None } } /// The dragged colour (a solid paint's), which the Gradient panel's ramp takes. pub fn color(&self) -> Option { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 1fbb9b1aa6..ff69110797 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -90,7 +90,7 @@ the two can still win that race. |---|---|---| | `engine.execute` | `{command, params}` | run any engine or UI command (see `engine.commands`). A key of `params` that the command's params description doesn't name is an error naming it and the nearest key the command takes, before anything runs (`unknown parameter `widht`; did you mean `width`?`); see [Parameter keys](mcp.md#parameter-keys) | | `engine.commands` | | every command with label, shortcut, params doc, enablement | -| `document.inspect` | `{depth?, childLimit?, ids?, kind?, limit?, offset?}` | layer tree, selection, the key object (`key`, null without one), history, paint defaults; `depth` / `childLimit` slice the layer tree as `document.node {summary: true}` does; `ids`, `kind`, `limit` and `offset` list just some nodes as `nodes` (with `total`) instead of the whole tree, see [mcp.md](mcp.md). Each node reports `opacity` below 1 and `blend` when it isn't Normal; objects and compound paths report `fill`, `stroke` and `strokeWidth`, a compound path's members `compoundMember: true` instead | +| `document.inspect` | `{depth?, childLimit?, ids?, kind?, limit?, offset?}` | layer tree, selection, the key object (`key`, null without one; a key ruler guide as `keyGuide`), history, paint defaults; `depth` / `childLimit` slice the layer tree as `document.node {summary: true}` does; `ids`, `kind`, `limit` and `offset` list just some nodes as `nodes` (with `total`) instead of the whole tree, see [mcp.md](mcp.md). Each node reports `opacity` below 1 and `blend` when it isn't Normal; objects and compound paths report `fill`, `stroke` and `strokeWidth`, a compound path's members `compoundMember: true` instead | | `ui.inspect` | | tool, UI state, `screenMode` (0 normal, 1 full screen with menu bar, 2 full screen, 3 Presentation Mode), `taskBar` (`pinned`, and `rect` `[x, y, w, h]` while the Contextual Task Bar shows), `freeTransformWidget` (`[x, y, w, h]` while the Free Transform widget shows), view, canvas rect, window size, perf, background saves and exports still running, `nativeMenuBar` (true when the menus are in the macOS menu bar rather than the window; `ui.menu.list` lists the in-window menus either way), `fileDialog` (`"open"`, `"place"`, `"save"` or `"folder"` while a native file dialog is open, `null` otherwise; see below) | | `ui.menu.list` / `ui.menu.invoke` | `{command, params}` | the full menu tree / invoke an item | | `ui.contextMenu.list` | | the canvas context menu for the current selection, flattened like `ui.menu.list` (`path` holds its submenus). `ui.click {x, y, button: "right"}` on the canvas opens it, after selecting the object there unless it is already selected. While a menu opened over locked objects is open, it has an `Unlock` submenu with one item for each locked object under the pointer, topmost first and at most 20, labeled with the object's name, which runs `layer.setProps {ids: [id], locked: false}`. A locked group gets one item, and the locked objects inside it get none. Hidden objects, objects on hidden, locked or template layers, and in isolation mode objects outside the isolated group get no item | @@ -121,7 +121,7 @@ the two can still win that race. | Background Save / Export | `app.save`, `app.export {path}`, `file.save`, `file.saveAs`, `file.saveCopy` | with the `backgroundSave` / `backgroundExport` preferences on (the default) the desktop app writes the file from a snapshot on a worker thread: the call returns `{path, background: true, status}` at once, `ui.inspect` lists the jobs still running in `background` (labels such as `"Saving a.vectorcraft"`), and the document counts as saved (as of the snapshot) once its file is written. Quit and Close wait for them. With the preferences off (`prefs.set`), saves return once written | | `engine.execute` `file.exportForScreens` | `{}` / `{…document.exportForScreens params}` | without params opens `exportForScreens` on the settings the document last exported with (`document.exportSettings`). While the Artboard tool is in use, the artboards it has selected (its `selected` option, the rows the Artboards panel highlights) are checked instead, and `select` is `range`, or `all` when every artboard is selected. Fields: `tab` (`artboards` \| `assets` \| `layers` \| `selection`; OK reads Export Layer or Export Selection on those), `layers` ([layer id…] checked), `selectionMode` (`one` \| `each`), `name` (the file name pattern of `document.exportForScreens`), `counterStart`, `folders` (`none` \| `rows` \| `format` \| `item` \| `itemFormat`), `exportPreset` (the preset applied last), `__savePreset` (the name typed to save one), `select` (`all` \| `range` \| `full`), `range` ("1-3, 5"), `boards` (a bool per artboard; checking them sets `select` and `range`), `includeBleed`, `folder` (desktop; default the Desktop, else home), `openLocation`, `subfolders`, `prefix`, `preset` (`""` \| `mobile` \| `density`), `formats` (rows `{format, scale: "2x" \| "100w" \| "100h" \| "72ppi", suffix, quality?, folder?}`), `settings` (`{png \| png8 \| jpg \| webp \| gif \| svg \| pdf: {…options}}`, the gear's Format Settings; `__settings` names the format shown). `ui.dialog.confirm` exports (a bad range or no folder keeps it open); on the web OK reads "Download" and the files download (several as one `.zip`). With params it runs `document.exportForScreens`: no `folder` returns the files (or with `zip: true` one store-only zip) as `dataBase64`; with `openLocation` the first file is shown in the file manager. When `warnings` is not empty, an export into a folder or a download shows the first in the status bar as Save As shows a save's notes | | Export for Screens' Assets tab, Asset Export panel | `ui.dialog.set` `tab: "assets"`, `assets: [asset id…]`; `window.panel {panel: "assetExport"}` | on the Assets tab of `exportForScreens` the `assets` field lists the checked asset ids (all of them when it opens); `ui.dialog.confirm` runs `document.exportForScreens {assets}` (nothing checked keeps it open) and OK reads "Export Asset". The Asset Export panel acts through `assets.*` and shares the format rows with the dialog (`assets.settings.set`) | -| `engine.execute` `file.exportSelection` | `{multiple?}` | File › Export Selection…: collects the selected objects as assets (`assets.add`; one per object unless `multiple` is false) and opens `exportForScreens` on its Assets tab with just them checked → `{assets}`. `document.exportSelection` still exports the selection in one go, without the dialog | +| `engine.execute` `file.exportSelection` | `{multiple?}` | File › Export Selection…: collects the selected objects as one asset (`assets.add`; one per object with `multiple: true`) and opens `exportForScreens` on its Assets tab with just them checked → `{assets}`. `document.exportSelection` still exports the selection in one go, without the dialog | | CSS Properties panel | `window.panel {panel: "cssProperties"}`; `engine.execute` `css.copy` / `css.exportFile` | the panel shows `css.selection` of the selection (after Generate CSS, while nothing is selected, `css.generate`); its menu holds the options the commands take (`units`, `position`, `dimensions`, `unnamed`, `rasterize`). `css.copy {scope?, …options}` copies the CSS to the clipboard → `{css, rules}`; `css.exportFile {path?, scope?, …options}` writes `css.export` to `path` (else a picked file; the web downloads it) with the pictures of rasterized art next to it → `{path, rules, images, warnings}`, and the status bar shows the first of `warnings` as Export As shows an export's notes | | `ui.dialog.*` on `importPdf` | `{field: "page" \| "allPages" \| "range" \| "cropTo" \| "password", value}` | opening (`app.open`, `file.open`) a PDF or `.ai` with several pages or a password, or placing one (`file.place` without `page`), opens the Import PDF dialog (`mode`: `open` or `place`; `pageCount`). While `__locked` is true, set `password` and `ui.dialog.confirm` to unlock it (a one-page file then opens or is placed). Then set `allPages: false` and `range` ("2-3, 5") to open some pages, or `page` to place one, and `cropTo` (`bounding`, `art`, `crop`, `trim`, `bleed`, `media`); `ui.dialog.confirm` opens or places them (placing keeps the other `file.place` params, such as `link`, `template` and `at`, in `__place`). `document.open {pages, cropTo, password}` and `file.place {page, crop, password}` do the same without the dialog | @@ -198,7 +198,9 @@ Plug-in dialogs: `engine.execute {command: "plugin.dialog", params: {id}}` (Obje plug-in at once when it takes no parameters, else opens the `plugin` dialog: one field per declared parameter (named after it), `__plugin` (the plug-in id) and `preview`. It previews `plugin.run` on the canvas while open; `ui.dialog.confirm` keeps the result as one undo step and `ui.dialog.cancel` rolls it back. Live-effect plug-ins open -the `effect` dialog (`effect.dialog {effect: "plugin."}`). `ui.installPlugin {path?}` installs a `.wasm` (without +the `effect` dialog (`effect.dialog {effect: "plugin."}`). An exporter plug-in with parameters opens the +`pluginExport` dialog once Export As has picked the file: one field per parameter, `__plugin`, and `__export` (the +export's own parameters); `ui.dialog.confirm` writes the file. `ui.installPlugin {path?}` installs a `.wasm` (without a path it asks for one); see [plugins.md](plugins.md). Overprint Black: the Edit → Edit Colors → Overprint Black… menu item opens a `command` parameter dialog for @@ -577,7 +579,7 @@ System clipboard formats: through the desktop app, `edit.copy` and `edit.cut` pu lists to the system clipboard (once they are written, the status bar shows the first of the PNG's and PDF's `warnings`, such as an image that couldn't be decoded), and every Paste command first loads what another app copied (`clipboard.importSvg`, `importPdf`, `importEps`, `importText` or `importImage`, centred in the view; the desktop app reads PDF and EPS from -the Windows clipboard and, with SVG, from the macOS pasteboard, and an `.eps` file, or a `.ai` or `.ait` file that holds a PDF or PostScript, copied in a file manager anywhere); an import error answers the Paste with that error +the Windows clipboard and, with SVG, from the macOS pasteboard, and an `.eps` file, or a `.ai` or `.ait` file that holds a PDF or PostScript, copied in a file manager anywhere; a copied `.ai` or `.ait` file that holds a PDF loads with `importPdf {editingData: true}`, which reads its editing data); an import error answers the Paste with that error and pastes nothing. Cmd+V also pastes a bitmap or PDF with no text beside it (on the key's release, as egui sends no Paste event for it). Screenshots paste on every platform: Windows reads `PNG`, else `CF_DIBV5`/`CF_DIB`, macOS the pasteboard's PNG or TIFF, Linux `image/png`, and the web the picture the browser's paste event carries (#457). diff --git a/docs/development.md b/docs/development.md index fe660a69a0..55ccbead12 100644 --- a/docs/development.md +++ b/docs/development.md @@ -104,11 +104,13 @@ On macOS the menus live in the system menu bar, not in the window's app bar (whi ## Linux: Wayland and X11 +On GNOME/Wayland, enable **Preferences › User Interface › System Title Bar** and restart to use winit's font-free Adwaita window controls (`wayland-csd-adwaita-notitle`); the existing custom title bar remains the Linux default. + The window runs natively on Wayland (eframe's `wayland` feature) and on X11. On machines with two GPUs it renders on the one the desktop runs on unless Preferences say otherwise; see [Desktop graphics processor](#desktop-graphics-processor) (#502). The system clipboard (`apps/vectorcraft/src/clipboard.rs`) is arboard with its `wayland-data-control` feature: - **Clipboard:** under Wayland arboard talks to the compositor through the data-control protocol (wlroots compositors such as Sway and Hyprland, KDE Plasma), so bitmaps (`image/png`), SVG markup and text copied in any app paste (#398). Where the compositor lacks the protocol (GNOME's Mutter, [arboard#223](https://github.com/1Password/arboard/issues/223)), arboard falls back to the X11 clipboard through XWayland, which only holds what X11 apps copied. egui's own text paste into fields goes through smithay-clipboard and works either way. - **Clipboard owners that never answer (#510):** reading the clipboard waits on the app that owns it: arboard gives up on an X11 owner after 4 s, and a Wayland read waits for the owner to send its data. So on Linux the check that enables the Paste menu items runs on a background thread with a second clipboard handle (`crates/ui-egui/src/clipboard_probe.rs`, installed as `Services::clipboard_probe`), only while nothing is copied in the app and a document is open, and the window keeps drawing. A paste itself still reads on the UI thread, so pasting from such an owner waits for it once. Windows and macOS keep the check on the UI thread: Windows only asks which formats the clipboard holds, macOS asks the pasteboard server. -- **Copied files:** files copied in a file manager (`text/uri-list`; `CF_HDROP` on Windows, file URLs on macOS) paste as the first one that is art (SVG, PDF, EPS, EMF/WMF or a bitmap; a `.ai` or `.ait` file as the PDF or PostScript it holds), before the clipboard's other formats (which include the files' paths as text). +- **Copied files:** files copied in a file manager (`text/uri-list`; `CF_HDROP` on Windows, file URLs on macOS) paste as the first one that is art (SVG, PDF, EPS, EMF/WMF or a bitmap; a `.ai` or `.ait` file from the editing data it holds, else as the PDF or PostScript it holds), before the clipboard's other formats (which include the files' paths as text). - **Dropping files on the window does not work under Wayland:** winit 0.30, which eframe 0.36 runs on, has no Wayland drag and drop ([winit#1881](https://github.com/rust-windowing/winit/issues/1881), added in winit 0.31; [egui#1563](https://github.com/emilk/egui/issues/1563)), so no `dropped_files` arrive. Until eframe moves to winit 0.31: copy the files in the file manager and paste them, use File › Place or Open, or open the window through XWayland, where drops work: set **Preferences › Performance › Linux Display Server** to **X11 (XWayland)** and restart (#1151), or start the app with `WAYLAND_DISPLAY= vectorcraft`. The preference (`linuxDisplayServer`, read at startup in `apps/vectorcraft/src/main.rs`, shown on Linux only) has winit open the window on X11 (`EventLoopBuilderExtX11::with_x11`) when the session is Wayland, `DISPLAY` is set and the X11 libraries winit loads are installed (`apps/vectorcraft/src/xwayland.rs` reads `ldconfig -p` and the usual library directories); otherwise the window opens on Wayland and the log says why. Unlike clearing `WAYLAND_DISPLAY`, it leaves the clipboard on the compositor's own. - **Pens and pen displays under Wayland (#491, #2028):** winit 0.30 doesn't bind the Wayland tablet protocol (`zwp_tablet_v2`; tablet input arrives in winit 0.31, [winit#4318](https://github.com/rust-windowing/winit/pull/4318), [egui#7731](https://github.com/emilk/egui/pull/7731)). Since Plasma 6.3, KWin no longer turns tablet input into pointer input for such apps ([kwin!6336](https://invent.kde.org/plasma/kwin/-/merge_requests/6336), commit [25c65abd](https://invent.kde.org/plasma/kwin/-/commit/25c65abddd95eb87fb892a8594faccbf509ff62f)), and GNOME's Mutter does not turn it into pointer input either (that commit's message): on KWin the pen moves the compositor's cursor over the window, but the app gets no motion or presses and shows none of its own cursors. Until eframe moves to winit 0.31, either run the app under XWayland, which supports the tablet protocol and hands the pen to X11 apps as a pointer (Preferences › Performance › Linux Display Server › X11 (XWayland); X11 (XWayland) When a Pen Is Attached (`x11WithPen`), which opens the window through XWayland only when `/proc/bus/input/devices` lists a pen as the app starts, a device with the `BTN_TOOL_PEN` key and the `ABS_X` and `ABS_Y` axes, and logs `pen found: opening the window through XWayland`; `WAYLAND_DISPLAY= vectorcraft`, or `env -u WAYLAND_DISPLAY vectorcraft`; for a desktop launcher, put `env WAYLAND_DISPLAY=` before the command in its `Exec=` line), or turn KWin's deprecated emulation back on for the whole session by setting `KWIN_WAYLAND_EMULATE_TABLET=1` in KWin's environment (for example in a file under `~/.config/environment.d/` or in `/etc/environment`) and logging in again. The pen then works as a mouse, without pressure: winit 0.30 reads pen pressure on Windows only (Windows Ink, which reaches the Liquify tools' Use Pressure Pen). Other compositors that don't emulate a pointer for tablets behave the same way. @@ -254,7 +256,7 @@ other `sv-*` locale resolve to it), Georgian (`ka`, complete; `ka-GE` and `ka_GE ## Vendor names gate -`cargo xtask brands` (part of `cargo xtask ci`) fails when user-visible text names another vendor's products or company: string literals in Rust sources (command labels and params docs, menus, panels, MCP tool definitions), `Cargo.toml` descriptions and packaging files. Comments and test code are not checked. Say "the reference app" or name the feature itself. A line that must keep an old name, such as an alias that files or preferences from earlier versions still use, carries a `brand-ok` comment. +`cargo xtask brands` (part of `cargo xtask ci`) fails when user-visible text names another vendor's products or company: string literals in Rust sources (command labels and params docs, menus, panels, MCP tool definitions), `Cargo.toml` descriptions and packaging files. Comments, test files and `#[cfg(test)]` modules are not checked. Say "the reference app" or name the feature itself. A line that must keep an old name, such as an alias that files or preferences from earlier versions still use, or a name another project defines, such as a shared MIME type, carries a `brand-ok` comment. In the Linux desktop entry, whose comments take whole lines, the comment goes on the `#` line just above it; `MARK_ABOVE` in `xtask/src/brands.rs` lists the files that accept a mark there. ## Robustness: VectorCraft never crashes diff --git a/docs/effects-parity.md b/docs/effects-parity.md index feb324be42..4fa4e6c179 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -1,6 +1,6 @@ # Effects parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-17 · **Change:** minor (3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; Zig Zag's Smooth points make a continuous wave, #2343; G2: Effect › Sketch › Halftone Pattern; Photoshop filters 30/57, 27 remaining (22–38 h); Round Corners also rounds corners where a curve meets a line or another curve, with Live Corners' cut; straight corners unchanged; score unchanged; Revolve: automatic smooth shading and default-on Cap with continuous rims; wide shadows and glows at high zoom, #1706; stacked Transform effects, #1705; 3D on nonzero compound paths, #1724; pattern tiles redraw, #1723; scores unchanged; Roughen's Smooth turn-backs, #1643; Scribble per region, #1648; score unchanged; Warp Arc bends in the object's proportions, #1578; Zig Zag ridges evenly spaced, #1558; effect parameters checked, #1592; score unchanged; raster effects after a pattern, radial or freeform gradient fill export at their place and size, #1536; score unchanged; 3D and Materials on outlined type and other shapes of many small curves, #1481; Twist 0° to 360°, #1524; twisted walls keep their faces, #1525; score unchanged; 3D and Materials: Inflate takes Twist, Taper and Cap; score unchanged; 3D and Materials: Perspective as the documented 0°–160° angle; 3D and Materials: the documented light settings) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-20 · **Change:** minor (G2: Effect › Sketch › Note Paper; Halftone Pattern and Note Paper defaults documented as unverified VectorCraft choices; G2: Effect › Artistic › Smudge Stick, Sponge and Watercolor; Sketch › Bas Relief, Charcoal, Photocopy and Stamp, #2533; Photoshop filters 46/57, 11 remaining (8–14 h); G2: Sketch › Chrome; Sketch › Chalk & Charcoal, Graphic Pen and Reticulation and Artistic › Plastic Wrap, #2972, #2967, #2976, #3034: 37/57 Photoshop effects; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; Zig Zag's Smooth points make a continuous wave, #2343; G2: Effect › Sketch › Halftone Pattern; Photoshop filters 46/57, 11 remaining (8–14 h); Round Corners also rounds corners where a curve meets a line or another curve, with Live Corners' cut; straight corners unchanged; score unchanged; Revolve: automatic smooth shading and default-on Cap with continuous rims; wide shadows and glows at high zoom, #1706; stacked Transform effects, #1705; 3D on nonzero compound paths, #1724; pattern tiles redraw, #1723; scores unchanged; Roughen's Smooth turn-backs, #1643; Scribble per region, #1648; score unchanged; Warp Arc bends in the object's proportions, #1578; Zig Zag ridges evenly spaced, #1558; effect parameters checked, #1592; score unchanged; raster effects after a pattern, radial or freeform gradient fill export at their place and size, #1536; score unchanged; 3D and Materials on outlined type and other shapes of many small curves, #1481; Twist 0° to 360°, #1524; twisted walls keep their faces, #1525; score unchanged; 3D and Materials: Inflate takes Twist, Taper and Cap; score unchanged; 3D and Materials: Perspective as the documented 0°–160° angle; 3D and Materials: the documented light settings) · **Target:** Adobe Illustrator 2026 (30.x) Every entry of Illustrator's Effect menu, by its public feature name, against VectorCraft's effects catalogue (`effect_catalog()` in `crates/effects/src/lib.rs`) and the Effect menu built from it @@ -12,7 +12,7 @@ Part of [target-app-parity.md](target-app-parity.md); open work is in [gaps.md]( | Group | Illustrator | VectorCraft | % | Remaining (h) | |---|---:|---:|---:|---:| | Illustrator effects (vector and stylize) | 50 | 46 | 92% | 6–10 | -| Photoshop effects (raster, Effect Gallery) | 57 | 33 | 58% | 21–35 | +| Photoshop effects (raster, Effect Gallery) | 57 | 46 | 81% | 8–14 | | 3D and Materials | 4 (+3 Classic) | 4 (initial: Extrude & Bevel, Revolve, Inflate, Rotate) | ~25% | 25–45 | | Beyond Illustrator: Effect › Color Adjustments (6), effect plug-ins (WebAssembly) | — | 6 + plug-ins | — | — | @@ -38,13 +38,13 @@ its resolution, PDF export warns once per object with the requested and the lowe | Submenu | Items | Ours | Missing | |---|---|---:|---| -| Artistic | Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Plastic Wrap, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting, Watercolor | 4/15 (approximate Cutout, Film Grain, Neon Glow, Poster Edges) | Colored Pencil, Dry Brush, Fresco, Paint Daubs, Palette Knife, Plastic Wrap, Rough Pastels, Smudge Stick, Sponge, Underpainting, Watercolor | +| Artistic | Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Plastic Wrap, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting, Watercolor | 8/15 (approximate Cutout, Film Grain, Neon Glow, Plastic Wrap, Poster Edges, Smudge Stick, Sponge, Watercolor) | Colored Pencil, Dry Brush, Fresco, Paint Daubs, Palette Knife, Rough Pastels, Underpainting | | Blur | Gaussian Blur, Radial Blur, Smart Blur | 3/3 | — | | Brush Strokes | Accented Edges, Angled Strokes, Crosshatch, Dark Strokes, Ink Outlines, Spatter, Sprayed Strokes, Sumi-e | 8/8 | — | | Distort | Diffuse Glow, Glass, Ocean Ripple | 3/3 | — | | Pixelate | Color Halftone, Crystallize, Mezzotint, Pointillize | 4/4 | — | | Sharpen | Unsharp Mask | 1/1 | — | -| Sketch | Bas Relief, Chalk & Charcoal, Charcoal, Chrome, Conté Crayon, Graphic Pen, Halftone Pattern, Note Paper, Photocopy, Plaster, Reticulation, Stamp, Torn Edges, Water Paper | 1/14 | Bas Relief, Chalk & Charcoal, Charcoal, Chrome, Conté Crayon, Graphic Pen, Note Paper, Photocopy, Plaster, Reticulation, Stamp, Torn Edges, Water Paper | +| Sketch | Bas Relief, Chalk & Charcoal, Charcoal, Chrome, Conté Crayon, Graphic Pen, Halftone Pattern, Note Paper, Photocopy, Plaster, Reticulation, Stamp, Torn Edges, Water Paper | 11/14 (approximate Bas Relief, Chalk & Charcoal, Charcoal, Chrome, Graphic Pen, Halftone Pattern, Note Paper, Photocopy, Plaster, Reticulation, Stamp; Chalk & Charcoal, Graphic Pen and Note Paper defaults unverified) | Conté Crayon, Torn Edges, Water Paper | | Stylize | Glowing Edges | 1/1 | — | | Texture | Craquelure, Grain, Mosaic Tiles, Patchwork, Stained Glass, Texturizer | 6/6 | Texturizer's Load Texture | | Video | De-Interlace, NTSC Colors | 2/2 | — | @@ -52,7 +52,7 @@ its resolution, PDF export warns once per object with the requested and the lowe The pixel-filter pipeline (`vectorcraft_effects::pixel`) is in place: each new filter is one function, a catalogue row, a menu entry and translations. Measured throughput: 0.7–1.2 agent hours per filter -(see [calibration](target-app-parity.md#calibration)), so the 24 missing filters are ~17–29 h and the Effect +(see [calibration](target-app-parity.md#calibration)), so the 12 missing filters are ~8–14 h and the Effect Gallery dialog another 4–6 h. These parallelize well across agents. Film Grain (`artistic.filmGrain`, Effect › Artistic) adds stable monochrome noise to shadows and @@ -83,6 +83,25 @@ Document Raster Effects resolution, and use the generic effect dialog with live defaults are chosen for VectorCraft. Evidence: `crates/effects/src/pixel/artistic.rs`, the `artistic_*`, `cutout_*`, `poster_edges_*` and `neon_glow_*` tests in `crates/effects/src/pixel/tests.rs`, and `artistic_settings_survive_a_save_and_open` in `crates/engine/src/tests_rasterfilters.rs`. +Smudge Stick (`artistic.smudgeStick`), Sponge (`artistic.sponge`) and Watercolor (`artistic.watercolor`), +Effect › Artistic, are original visual approximations from the public descriptions in +[Illustrator's effects reference](https://helpx.adobe.com/illustrator/using/summary-effects.html) and the +[public Artistic filters guide](https://helpx.adobe.com/photoshop-elements/using/artistic-filters.html), not +pixel-identical copies. Each has live preview, appearance editing, document-unit patterns that follow the +object, bounded work per pixel and kept coverage (they paint nothing outside the object), and bakes to an +image in SVG and PDF. Ranges and defaults are chosen for VectorCraft, not asserted as measured. +- Smudge Stick (Stroke Length 0–10, Highlight Area 0–20, Intensity 0–10): dark areas smudged along short + diagonal strokes; light areas smudged with strokes twice as long and lightened towards white. +- Sponge (Brush Size 0–10, Definition 0–25, Smoothness 1–15): the object softened, then lighter and darker + blobs of the same hue, their contrast set by Definition, their edges by Smoothness. +- Watercolor (Brush Detail 1–14, Shadow Intensity 0–10, Texture 1–3): detail simplified by an edge-keeping + average whose brush widens as Brush Detail falls, colour saturated and pooled darker where tones change at + edges, shadows deepened, a faint paper grain. Edges are found from tone only, so a change of hue at equal + brightness is not saturated. + +Tests: `pixel::tests_paint::*`, `tests_rasterfilters`, `dialogs::tests::raster_filter_dialogs_*`, +`tests_labels::effect_menu_lists_the_artistic_filters_*` and the `command_sweep` structured junk. + Near white, highlight headroom can limit grain equally at every Intensity; highlight lift still depends on Intensity when Highlight Area is nonzero. The two rotated, variance-normalised noise layers can leave a faint diagonal weave at high @@ -93,7 +112,52 @@ Calibration on uniform grey at Grain 20, using 32×32 fine samples per coarse pi grain standard deviation within about 15% of the dense area average at pixel widths of 2, 4 and 8 document units (ratios 1.13, 0.89, 0.85). This is evidence for the bounded approximation, not an accuracy guarantee for arbitrary artwork. Tests: `pixel::tests::film_grain_*`, -`tests_rasterfilters`, `tests_adjust::film_grain_dialog_*` and `tests_labels::effect_menu_lists_film_grain_*`. +`tests_rasterfilters`, `tests_adjust::film_grain_dialog_*` and `tests_labels::effect_menu_lists_the_artistic_filters_*`. + +Smudge Stick (`artistic.smudgeStick`), Sponge (`artistic.sponge`) and Watercolor (`artistic.watercolor`), +Effect › Artistic, are original visual approximations from the public descriptions in +[Illustrator's effects reference](https://helpx.adobe.com/illustrator/using/summary-effects.html) and the +[public Artistic filters guide](https://helpx.adobe.com/photoshop-elements/using/artistic-filters.html), not +pixel-identical copies. Each has live preview, appearance editing, document-unit patterns that follow the +object, bounded work per pixel and kept coverage (they paint nothing outside the object), and bakes to an +image in SVG and PDF. Ranges and defaults are chosen for VectorCraft, not asserted as measured. +- Smudge Stick (Stroke Length 0–10, Highlight Area 0–20, Intensity 0–10): dark areas smudged along short + diagonal strokes; light areas smudged with strokes twice as long and lightened towards white. +- Sponge (Brush Size 0–10, Definition 0–25, Smoothness 1–15): the object softened, then lighter and darker + blobs of the same hue, their contrast set by Definition, their edges by Smoothness. +- Watercolor (Brush Detail 1–14, Shadow Intensity 0–10, Texture 1–3): detail simplified by an edge-keeping + average whose brush widens as Brush Detail falls, colour saturated and pooled darker where tones change at + edges, shadows deepened, a faint paper grain. Edges are found from tone only, so a change of hue at equal + brightness is not saturated. + +Tests: `pixel::tests_paint::*`, `tests_rasterfilters`, `dialogs::tests::raster_filter_dialogs_*`, +`tests_labels::effect_menu_lists_the_artistic_filters_*` and the `command_sweep` structured junk. + +Bas Relief, Charcoal, Photocopy and Stamp (`sketch.basRelief`, `sketch.charcoal`, `sketch.photocopy`, +`sketch.stamp`, Effect › Sketch; `pixel/sketch_ink.rs`) redraw the object in black ink on white paper +and keep its coverage. Bas Relief carves low relief lit from one of eight directions (Detail, Smoothness, +Light Direction); Charcoal draws bold edges and sketches the midtones in diagonal strokes (Thickness, +Detail, Light/Dark Balance); Photocopy prints only where a pixel is darker than its surroundings, so large +dark areas copy around their edges (Detail, Darkness); Stamp reduces the object to solid black and +white (Light/Dark Balance, Smoothness). Sizes are in document points at any Document Raster Effects +resolution, strokes and noise lie in document space around the object's centre, and all four preview +live. Behaviour is an original visual approximation based on +[Illustrator's public effects reference](https://helpx.adobe.com/illustrator/using/summary-effects.html) +and the [public Sketch filters guide](https://helpx.adobe.com/photoshop-elements/using/sketch-filters.html), +not a pixel-identical proprietary implementation; the parameter ranges and defaults are chosen for +VectorCraft, not asserted as measured proprietary defaults. Tests: `pixel::tests_sketch::*`, +`tests_rasterfilters`, `command_sweep`, `dialogs::tests::raster_filter_dialogs_preview_and_apply` and +`tests_labels::effect_menu_lists_the_sketch_filters_*`. + +Effect › Sketch › Halftone Pattern and Note Paper (`sketch.halftonePattern`, `sketch.notePaper`) are +original black-and-white filters guided by [Illustrator's public Sketch effects summary](https://helpx.adobe.com/illustrator/using/summary-effects.html) +and [effects overview](https://helpx.adobe.com/illustrator/using/effects.html) (Halftone Size in points at any Document Raster Effects resolution). +The public help pages name each control but publish no numeric defaults or slider limits; VectorCraft's ranges +follow those control names and the emboss/halftone behaviour described there, while dialog defaults are chosen +for VectorCraft and are not verified against proprietary defaults. Evidence: `crates/effects/src/pixel/sketch.rs`, +`halftone_*` and `note_paper_*` in `crates/effects/src/pixel/tests.rs`, `SKETCH` and +`halftone_pattern_settings_survive_a_save_and_open` in `crates/engine/src/tests_rasterfilters.rs`, and +`tests_labels::effect_menu_lists_the_sketch_filters_between_sharpen_and_stylize`. ## 3D and Materials @@ -114,7 +178,11 @@ angular cut caps, exact visibility, 3D Classic, Turntable, 3D export) is 25–45 | Date | Change | Summary | |---|---|---| +| 2026-10-20 | minor | G2: Effect › Sketch › Note Paper (Image Balance, Graininess, Relief; embossed tones on fibrous paper); Halftone Pattern and Note Paper parameter ranges follow public control names, numeric defaults are unverified VectorCraft choices (public help gives no numbers); measured Photoshop filters 46/57, Sketch 11/14. | +| 2026-10-19 | minor | Sketch › Chalk & Charcoal, Graphic Pen and Reticulation and Artistic › Plastic Wrap landed (#2972, #2967, #2976, #3034): 36/57 Photoshop effects (estimated; defaults unverified) | | 2026-10-16 | minor | Zig Zag with Smooth points draws a continuous wave: every peak and valley is a smooth point with handles along the path, a third of the way to the next ridge, so each span follows a half cosine through the path instead of a straight diagonal with rounded tips, also at the ends of open paths and for ridges much taller than they are apart (#2343); score unchanged (estimated) | +| 2026-10-16 | minor | G2: Effect › Artistic › Smudge Stick, Sponge and Watercolor (live, with their documented options; original approximations); measured Photoshop filters 36/57 with Cutout, Neon Glow and Poster Edges, 21 remaining (19–31 h). | +| 2026-10-16 | minor | G2: Effect › Sketch › Bas Relief, Charcoal, Photocopy and Stamp (black ink on white paper, sizes in points at any Document Raster Effects resolution, live preview); measured Photoshop filters 37/57 with Cutout, Neon Glow and Poster Edges, 20 remaining (18–30 h). | | 2026-10-16 | minor | G2: Effect › Sketch › Halftone Pattern (Size, Contrast, Pattern Type Circle, Dot or Line; black ink on white paper, Size in points at any Document Raster Effects resolution); measured Photoshop filters 30/57, 27 remaining (22–38 h). | | 2026-10-17 | minor | Colored Inflate: shared membrane normals and smooth RGB vector ramps replace flat polygon bands; channel groups are batched per solid-fill surface. White-light Inflate retains its original polygons, paint composition and seam joins; the 0.05 seam minimum is restored. Scores and hour estimates unchanged. | | 2026-10-16 | minor | 3D lighting: one to ten directional lights, a selectable light list, Add Light and Delete Light, independent settings and artboard gestures; ambient applied once and smooth RGB vector export; scores and hour estimates unchanged | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index de67cd2c24..fd779e50ea 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-16 · **Change:** minor (an Illustrator 3 file without layers, as image editors export their paths, opens with its art on one layer, storytold/photocraft#6036; EPS editing data: legacy mesh corners, vector opacity masks and compound member paint retained; raster page comparison filters minification without relaxing limits; scores and hours unchanged; batch exporting, #1935; legacy `.ai` runs as PostScript with a prolog of its own, #868; legacy `.ai` of version 7 saved, with type as text, hidden objects and an artboard picker, and its type read, #868; PDF.R1: shared PDF reader with windowed content scanning and explicit incomplete-content errors; scores and estimates unchanged; PDF.W1: guarded shared PDF writer; output behavior, scores and estimates unchanged; later 2026-10-14 merges: SVG `:not()` selectors, #1557, stacked selectors, #1703, linked files, #1870; DXF VPORT, #1789; nesting caps, #1852; hostile PDF, `.ai`, EPS, Affinity and native data, #1862, #1863, #1871–#1873; failed saves, #1685, #1693, #1694; type in symbols after reopening, #1738; scores unchanged; verified PngSuite downloads, #1729; EPS stitched shadings, #1653; oversized images in WMF/EMF refused from the header, #1776; PDF name trees with shared nodes, #1781; native size limits for files read from memory, #1783; private temporary files on Unix, #1778; ruzstd 0.9.1, #1807; scores unchanged; SVG import: CSS transforms and the `font` shorthand, #1565, percentage lengths in symbols, #1596, Inkscape flowed text and pages, #1568, #1601, filter warnings, #1598; type on a path from PDF and `.ai`, #1585, #1586; ICC tag alignment in JPEG, TIFF and PSD, #1584; saves to folders that refuse the temporary file, #1620 in part; scores unchanged; TIFF is available in Export for Screens and Asset Export with shared format settings; scores and hours unchanged; compact native saves for documents with a lot of path data, #1492; PDF and EPS paste as vector art, #1499; `.ai` gradient stops listed upwards, #1530; SVG text on basic shapes, #1527; PDF soft masks drawn as images, #1551; Type 42 fonts in EPS, #1553; clips that only seem to cover the page, #1542; images too large to decode are reported, #1540; a `.ai` page's art past its artboard no longer lies over the page before it when read as its PDF part; grayscale TIFFs with an alpha channel or extra channels place and open, #1466 in part; a faded or masked fill keeps its stroke apart on PDF and `.ai` import, #1434; SVG knockout groups without masks, #1435; Affinity import: a text frame too short for its first line is made taller, #1423; `.ai` editing data: a compound path takes its last path's paint and keeps paths grouped inside it, #1410; a `.ai` whose PDF part is only text opens from it, #1387; PDF and `.ai` import keep overprint, #1388; `.ai` editing data: gradients with middle stops, #1390; type of objects with an appearance, hidden layers and later artboards, #1391; area type in a frame too short for the fallback font, #1392; `.ai` editing data: placed (linked) files read, #1264; gradient-filled shapes import as paths, #1304; white constant alpha soft masks, #1286 in part; DXF control-point SPLINE closure read, #1299 follow-up; `.ai` and PDF trim and bleed boxes as artboard and bleed, #1266; `.ai` gradient matrices, meshes and artboard names from the editing data; `.ai` art styles, clipping fills and compound looks from the editing data; `editingData: "always"` opens a `.ai` from its editing data; a `.ai` whose PDF part is only text opens from it, #1387; PDF and `.ai` import keep overprint, #1388; `.ai` editing data: gradients with middle stops, #1390; type of objects with an appearance, hidden layers and later artboards, #1391; area type in a frame too short for the fallback font, #1392; `.ai` editing data: placed (linked) files read, #1264; gradient-filled shapes import as paths, #1304; white constant alpha soft masks, #1286 in part; DXF control-point SPLINE closure read, #1299 follow-up; `.ai` and PDF trim and bleed boxes as artboard and bleed, #1266; `.ai` gradient matrices, meshes and artboard names from the editing data; `.ai` art styles, clipping fills and compound looks from the editing data; a `.ai` whose PDF part is only text opens from it, #1387; PDF and `.ai` import keep overprint, #1388; `.ai` editing data: gradients with middle stops, #1390; type of objects with an appearance, hidden layers and later artboards, #1391; area type in a frame too short for the fallback font, #1392; `.ai` editing data: placed (linked) files read, #1264; gradient-filled shapes import as paths, #1304; white constant alpha soft masks, #1286 in part; DXF control-point SPLINE closure read, #1299 follow-up; `.ai` and PDF trim and bleed boxes as artboard and bleed, #1266; `.ai` gradient matrices, meshes and artboard names from the editing data; a `.ai` whose PDF part is only text opens from it, #1387; PDF and `.ai` import keep overprint, #1388; `.ai` editing data: gradients with middle stops, #1390; type of objects with an appearance, hidden layers and later artboards, #1391; area type in a frame too short for the fallback font, #1392; `.ai` editing data: placed (linked) files read, #1264; gradient-filled shapes import as paths, #1304; white constant alpha soft masks, #1286 in part; DXF control-point SPLINE closure read, #1299 follow-up; `.ai` and PDF trim and bleed boxes as artboard and bleed, #1266; SVG knockout groups of opaque art without masks; a `.ai` whose PDF part is only text opens from it, #1387; PDF and `.ai` import keep overprint, #1388; `.ai` editing data: gradients with middle stops, #1390; type of objects with an appearance, hidden layers and later artboards, #1391; area type in a frame too short for the fallback font, #1392; `.ai` editing data: placed (linked) files read, #1264; gradient-filled shapes import as paths, #1304; white constant alpha soft masks, #1286 in part; DXF control-point SPLINE closure read, #1299 follow-up; `.ai` and PDF trim and bleed boxes as artboard and bleed, #1266; `.ai` keeps its RGB numbers; PDF import keeps a stroke apart from a fill masked or faded by its group) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-18 · **Change:** minor (PDF invisible text, as a scanned page's recognized text is, opens as type with no fill or stroke and is written back as invisible text, #2675; DXF circular cubic paths export as native CIRCLE/ARC where stroke semantics permit (R13–2018 for weighted strokes; R12 weighted strokes remain POLYLINE) (#1299); non-circular curves stay SPLINE; scores and hours unchanged; an Illustrator 3 file without layers, as image editors export their paths, opens with its art on one layer, storytold/photocraft#6036; EPS editing data: legacy mesh corners, vector opacity masks and compound member paint retained; raster page comparison filters minification without relaxing limits; scores and hours unchanged; batch exporting, #1935; legacy `.ai` runs as PostScript with a prolog of its own, #868; legacy `.ai` of version 7 saved, with type as text, hidden objects and an artboard picker, and its type read, #868; PDF.R1: shared PDF reader with windowed content scanning and explicit incomplete-content errors; scores and estimates unchanged; PDF.W1: guarded shared PDF writer; output behavior, scores and estimates unchanged; later 2026-10-14 merges: SVG `:not()` selectors, #1557, stacked selectors, #1703, linked files, #1870; DXF VPORT, #1789; nesting caps, #1852; hostile PDF, `.ai`, EPS, Affinity and native data, #1862, #1863, #1871–#1873; failed saves, #1685, #1693, #1694; type in symbols after reopening, #1738; scores unchanged; verified PngSuite downloads, #1729; EPS stitched shadings, #1653; oversized images in WMF/EMF refused from the header, #1776; PDF name trees with shared nodes, #1781; native size limits for files read from memory, #1783; private temporary files on Unix, #1778; ruzstd 0.9.1, #1807; scores unchanged; SVG import: CSS transforms and the `font` shorthand, #1565, percentage lengths in symbols, #1596, Inkscape flowed text and pages, #1568, #1601, filter warnings, #1598; type on a path from PDF and `.ai`, #1585, #1586; ICC tag alignment in JPEG, TIFF and PSD, #1584; saves to folders that refuse the temporary file, #1620 in part; scores unchanged; TIFF is available in Export for Screens and Asset Export with shared format settings; scores and hours unchanged; compact native saves for documents with a lot of path data, #1492; PDF and EPS paste as vector art, #1499; `.ai` gradient stops listed upwards, #1530; SVG text on basic shapes, #1527; PDF soft masks drawn as images, #1551; Type 42 fonts in EPS, #1553; clips that only seem to cover the page, #1542; images too large to decode are reported, #1540; a `.ai` page's art past its artboard no longer lies over the page before it when read as its PDF part; grayscale TIFFs with an alpha channel or extra channels place and open, #1466 in part; a faded or masked fill keeps its stroke apart on PDF and `.ai` import, #1434; SVG knockout groups without masks, #1435; Affinity import: a text frame too short for its first line is made taller, #1423; `.ai` editing data: a compound path takes its last path's paint and keeps paths grouped inside it, #1410; a `.ai` whose PDF part is only text opens from it, #1387; PDF and `.ai` import keep overprint, #1388; `.ai` editing data: gradients with middle stops, #1390; type of objects with an appearance, hidden layers and later artboards, #1391; area type in a frame too short for the fallback font, #1392; `.ai` editing data: placed (linked) files read, #1264; gradient-filled shapes import as paths, #1304; white constant alpha soft masks, #1286 in part; DXF control-point SPLINE closure read, #1299 follow-up; `.ai` and PDF trim and bleed boxes as artboard and bleed, #1266; `.ai` gradient matrices, meshes and artboard names from the editing data; `.ai` art styles, clipping fills and compound looks from the editing data; `editingData: "always"` opens a `.ai` from its editing data; a `.ai` whose PDF part is only text opens from it, #1387; PDF and `.ai` import keep overprint, #1388; `.ai` editing data: gradients with middle stops, #1390; type of objects with an appearance, hidden layers and later artboards, #1391; area type in a frame too short for the fallback font, #1392; `.ai` editing data: placed (linked) files read, #1264; gradient-filled shapes import as paths, #1304; white constant alpha soft masks, #1286 in part; DXF control-point SPLINE closure read, #1299 follow-up; `.ai` and PDF trim and bleed boxes as artboard and bleed, #1266; `.ai` gradient matrices, meshes and artboard names from the editing data; `.ai` art styles, clipping fills and compound looks from the editing data; a `.ai` whose PDF part is only text opens from it, #1387; PDF and `.ai` import keep overprint, #1388; `.ai` editing data: gradients with middle stops, #1390; type of objects with an appearance, hidden layers and later artboards, #1391; area type in a frame too short for the fallback font, #1392; `.ai` editing data: placed (linked) files read, #1264; gradient-filled shapes import as paths, #1304; white constant alpha soft masks, #1286 in part; DXF control-point SPLINE closure read, #1299 follow-up; `.ai` and PDF trim and bleed boxes as artboard and bleed, #1266; `.ai` gradient matrices, meshes and artboard names from the editing data; a `.ai` whose PDF part is only text opens from it, #1387; PDF and `.ai` import keep overprint, #1388; `.ai` editing data: gradients with middle stops, #1390; type of objects with an appearance, hidden layers and later artboards, #1391; area type in a frame too short for the fallback font, #1392; `.ai` editing data: placed (linked) files read, #1264; gradient-filled shapes import as paths, #1304; white constant alpha soft masks, #1286 in part; DXF control-point SPLINE closure read, #1299 follow-up; `.ai` and PDF trim and bleed boxes as artboard and bleed, #1266; SVG knockout groups of opaque art without masks; a `.ai` whose PDF part is only text opens from it, #1387; PDF and `.ai` import keep overprint, #1388; `.ai` editing data: gradients with middle stops, #1390; type of objects with an appearance, hidden layers and later artboards, #1391; area type in a frame too short for the fallback font, #1392; `.ai` editing data: placed (linked) files read, #1264; gradient-filled shapes import as paths, #1304; white constant alpha soft masks, #1286 in part; DXF control-point SPLINE closure read, #1299 follow-up; `.ai` and PDF trim and bleed boxes as artboard and bleed, #1266; `.ai` keeps its RGB numbers; PDF import keeps a stroke apart from a fill masked or faded by its group) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/mod.rs`). Illustrator's list comes from its public @@ -93,11 +93,11 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | VectorCraft `.vectorcraft` / `.vctemplate` | — | yes | yes | lossless JSON, versioned, save down to v1; property-tested round trips (`format/tests/prop_format.rs`); documents with a lot of path data are written as compact JSON, about a fifth of the size (#1492); a save falls back to a plain fsync and to writing elsewhere and copying in when the folder refuses the usual steps (#1625, #1649, part of #1620; not confirmed on a real network share); the size limits on embedded data also apply to files read from memory (#1783), and saving over a private file on Unix leaves no readable temporary copy beside it (#1778) | | Illustrator template `.ait` | open, save | yes | PDF-compatible only, from Save as Template (`.vctemplate` stays its default) | New from Template opens a saved `.ait` untitled with its layers and art (`tests_pdfedit.rs`) | | Illustrator `.ai` | open, save | yes (PDF-compatible + editing-data structure, File Info) | PDF-compatible, or legacy version 7 (layers and groups) | see above; no real-file corpus | -| PDF | open, place, save | yes (layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text placement issues in some files (#722); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781) | +| PDF | open, place, save | yes (layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text placement issues in some files (#722); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675) | | EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CID-keyed CJK type not read; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | | PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` | | SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598) | -| DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). CIRCLE/ARC export fitting, CNC preset and VCarve QA remain open | +| DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). CNC preset and VCarve QA remain open | | DWG | open, export | no | no | no open spec; DXF instead | | EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776) | | PSD | open, place, export | yes (merged image, every mode and depth) | yes (layered, max editability) | placing as layers (Photoshop Import Options) missing; the embedded ICC profile's tags are 4-byte aligned (#1584) | @@ -119,6 +119,10 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | Affinity `.af`, `.afdesign`, `.afpub` | no | yes (beyond Illustrator) | no (#665) | 51 pinned files, [affinity-validation.md](affinity-validation.md) | | Clipboard: PDF, SVG, PNG, EMF, text | yes | yes | yes | copied files paste as art | +## PDF editable imports + +- [x] Place from bytes or unlinked paths, and PDF clipboard paste, keep the selected page's live text. Synthetic two-page regressions in `crates/engine/src/cmd/fileio/tests_pdffidelity.rs` cover both sources, page selection and explicit outlines. The single-page importer honors the same text choice as Open; existing PDF fallback rules are unchanged. + ## Corpus download integrity - [x] PngSuite opt-in downloads are pinned, SHA-256 verified and bounded before publication (#1729); no archive extraction. This secures fixture acquisition and does not raise format-fidelity scores. @@ -127,6 +131,9 @@ the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPri | Date | Change | Summary | |---|---|---| +| 2026-10-18 | minor | PDF import: invisible text (rendering mode 3, which carries a scanned page's recognized text) opens as type with no fill or stroke instead of being dropped without a word; when it can't be type (text opened as outlines, Type 3 fonts) it is left out with a warning. PDF export writes characters with no fill or stroke as invisible text in rendering mode 3, so a scanned PDF opened and saved keeps its searchable text, in PDF/X-1a and PDF/A too (#2675); own-fixture tests; scores and hours unchanged | +| 2026-10-18 | minor | DXF circular cubic paths export as native CIRCLE/ARC where stroke semantics permit (R13–2018 for weighted strokes; R12 weighted strokes remain POLYLINE); R12 stroked circles/arcs retain their POLYLINE width, and ClosePath geometry with an implicit closing chord is not promoted to CIRCLE (#1299); scores and hours unchanged | +| 2026-10-17 | minor | PDF Place and clipboard paste preserve live text; explicit outlines remain supported on Place. Synthetic regressions; scores and hours unchanged. | | 2026-10-16 | minor | An Illustrator 3 file without prolog or layers (an image editor's exported paths) opens with its art on one layer instead of being refused (storytold/photocraft#6036); scores unchanged | | 2026-10-16 | minor | EPS editing data: legacy mesh corners, vector opacity masks and compound member paint retained; raster page comparison filters minification without relaxing limits; scores and hours unchanged. Synthetic EPS/parser/minification regressions; user EPS/SVG/JPG kept local. | | 2026-10-16 | minor | Batch exporting in Export for Screens (#1935): a file name pattern (document and item names, a counter, the date), folders per format, item or both, Layers and Selection tabs with thumbnails, EPS, AI and VectorCraft rows, a PDF row with printer's marks, and export presets (built-in Logo Package and Print-Ready PDF, saved ones); scores and hours unchanged (estimated) | diff --git a/docs/gaps.md b/docs/gaps.md index 3c4f678ebd..90a0c7899f 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-18 · **Change:** minor (on-canvas Mirror Repeat axis, #2877; G12: Background Export progress dialog with Cancel, #2564; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; Blend spine Anchor Point conversions, selection/stacking priority and Shift regression coverage (#2544); scores and hours unchanged; transparency grid visibility saved in native documents, #1968; G6: MCP cancellation, progress notifications and busy answers during long exports, #2165, #2171, #2172; EPS editing data: legacy mesh corners, vector opacity masks and compound member paint retained; raster page comparison filters minification without relaxing limits; scores and hours unchanged; correction: quick Image Trace presets leave the panel as it was, the Image Trace button opens it; batch exporting, #1935; G2: Effect › Sketch › Halftone Pattern; Photoshop filters 30/57, 27 remaining (22–38 h); G5: Symbol Options Export Type (Graphic / Movie Clip); G1: Smart Guides line extension, #2120; G16: Brazilian Portuguese catalog complete under the tests, #1914; Localization 71% → 74%, hours 55–90 → 50–85; G6: image variables landed, estimate 8–14 → 6–12 h; Warp Options controls verified by focused checks and original-image review; estimates unchanged; existing-guide Escape cancellation validated 2026-10-14; scores and hours unchanged; open-path anchor Delete keeps surviving runs separate; estimates unchanged; Artboard tab-switch follow-up historically validated on `a0671777`; scores and hours unchanged; Artboard clean active-tab close/Delete follow-up validated 2026-10-15; G13: Object › Intertwine landed, #1763; no entry closed, estimates unchanged; MCP `add_text` exposes the existing `vertical` option for point, area and path type; horizontal remains the default; scores and hours unchanged; Vertical fullwidth question and exclamation marks keep their nominal glyph upright when the font has no vertical alternate; scores and hours unchanged.; G1: Curvature curve geometry, #1236 in part; Width-point finite-arithmetic follow-up validated; scores and hours unchanged; Image Trace adjustment discovery; G9: legacy `.ai` of version 7 saved with type as text and hidden objects kept, legacy type read, #868; estimate unchanged; Revolve: automatic smooth shading and default-on Cap with continuous rims; later 2026-10-14: G8 untrusted files, #1852, #1862–#1873; G11 anchor X/Y/W/H, #1824, Snap to Grid over Snap to Pixel, #1816, redo during a drag, #1719, Dim Images, #1683, failed-save dialog, #1685; gaps noted for reporters: G1 Warp Options for Effect › Warp, #1760, Color Picker Tab order, #1692, key anchor, #1636; G7 custom toolbars, #1759, workspace panel widths, #1753; G11 Shape Builder gaps between closed shapes, #1691, interior anchor delete; G13 Intertwine, #1763, gradient mesh from an image, #1676, Image Trace radial gradients, #1849; G12 duplicated line removed; no entry closed, estimates unchanged; verified PngSuite downloads, #1729; synthetic control-input budgets, #1709; 2026-10-14 fixes: G11 anchor Align and Distribute, #1636, Delete and selection, #1674, #1666, #1743, #1686, Roughen and Scribble, #1643, #1648; G8 file and input hardening, #1776–#1783, #1786, #1807; G10 Wayland cursors and the Windows title bar, unconfirmed, #1645, #1758; no entry closed, estimates unchanged; later 2026-10-13 fixes, #1570, #1578, #1590, #1613, #1615, #1616, #1620 in part, #1602 in part; no entry closed, estimates unchanged; TIFF is available in Export for Screens and Asset Export with shared format settings; scores and hours unchanged; G1/M11: Artboard deletion and history selection normalization; history regressions and full workspace CI pass; scores and hours unchanged; Character styles retain explicit Auto leading, propagate resets and preserve local leading overrides; scores and hours unchanged; Width Point Edit: Shift-double-click enables adjoining adjustment; plain double-click keeps it off; scores and hours unchanged; G12: Identify Objects By acts, #394; ~16 → ~15 prefs still inert; G12: Appearance of Black › Printing / Exporting acts, #394; ~16 → ~15 prefs still inert; control transport deadlines, #1726; G1: Average and Join in one step with a corner or smooth choice added as missing (it was listed as done in ui-parity.md); Join after Average, #1533; guide objects, #1534; Keyboard Shortcuts, #1539; G9 and G11 fixes, #1528, #1530, #1544, #1553, #1512, #1537; estimates unchanged; Direct Selection anchor precedence, #1508; dialog slider rails, #1483; template layers in Outline view, #1486; Tabs panel stop drags, #1458; type that does not fit its frame is reported, #1471; 3D on outlined type, #1481, Twist range, #1524, twisted walls, #1525; print-size images, #1517; French catalog, #1511; estimates unchanged; G1: Split Into Grid options, #1462, Transform Objects and Reflect's angle, #1448 and #1460, Pathfinder on a group, #1450, value fields, #1457 and #1465 in part; G9: grayscale TIFFs with alpha, #1466 in part; G6: unknown parameter keys refused, #1442; G10: window surfaces past 8192 px, #1459 in part; G15: many-object edits, #1429 in part; estimates unchanged; G16: Vietnamese catalog added, complete under the tests; three key languages remain, 60–100 → 55–90 h; G3: Extrude & Bevel, Inflate and Rotate added, 45–75 → 25–45 h; G9: `.ai` compound path paint, #1410, overprint kept on import, #1388, text-only PDF parts, #1387; G1: Transform dialogs preview, #1412, transforms of direct-selected anchors, #1408, corner drags, #1229; G11: strokes wider than their shape, #1396; estimates unchanged; G9: `.ai` editing-data follow-ups (gradient stops, type placement, short area-type frames), #1390, #1391, #1392; G15: symbol instance art kept between frames, #1386; G1: dialog keyboard focus, #1367 and #1395; estimates unchanged; G9: placed (linked) files read from `.ai` editing data, #1264; G9: gradient shapes import as paths, #1304, and white constant alpha masks, #1286 in part; G15: linear deselect on hide or lock, #1353; estimates unchanged; G7: custom ruler origin done, #1212; G1: Artboard object clicks create a fitted artboard (#1227); remaining interaction pass and estimate unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; DXF control-point SPLINE closure read, #1299 follow-up; G16: Korean catalog added, 70–110 → 60–100 h; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; G11: valid selection after Simplify and Add Anchor Points (#1272); estimates unchanged; G2: Film Grain added; Photoshop effects 29/57; 28 filters remain; G10: RPM runtime dependency metadata (#1275); estimates unchanged; G15: texture-effect distance searches optimized (#1257); idle-machine/platform drag QA still pending; estimate unchanged; G1: Curvature point display improved (#1236, in part); estimates unchanged; G4: full-name font matching (#1258); Windows font-service QA pending; estimate unchanged; G11: no-op anchor Align keeps history and saved state (#1180 follow-up); estimates unchanged; G1: dedicated Eyedropper cursor and precise-cursor checks (#1269); estimates unchanged; G1: Eyedropper reads visible locked and outside-isolation sources (#1251); estimate unchanged; G11: Direct Selection segment Delete (#1278); estimates unchanged; G1: painted strokes regain the existing default after None/zero-width inheritance (#1253); estimate unchanged; G15: large-selection edits, cached live effects and faster Pathfinder, #1173; G4: proportional vertical metrics done, #966; G11: Shape Builder merge seams on grids of lines fixed, #893; scaled text controls corrected, #1034; group font-size preservation deferred; G9: `.ai` gradient matrices and meshes from the editing data; estimate unchanged; G9: `.ai` art styles from the editing data; estimate unchanged; G9: `.ai` editing-data follow-ups (gradient stops, type placement, short area-type frames), #1390, #1391, #1392; G15: symbol instance art kept between frames, #1386; G1: dialog keyboard focus, #1367 and #1395; estimates unchanged; G9: placed (linked) files read from `.ai` editing data, #1264; G9: gradient shapes import as paths, #1304, and white constant alpha masks, #1286 in part; G15: linear deselect on hide or lock, #1353; estimates unchanged; G7: custom ruler origin done, #1212; G1: Artboard object clicks create a fitted artboard (#1227); remaining interaction pass and estimate unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; DXF control-point SPLINE closure read, #1299 follow-up; G16: Korean catalog added, 70–110 → 60–100 h; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; G11: valid selection after Simplify and Add Anchor Points (#1272); estimates unchanged; G2: Film Grain added; Photoshop effects 29/57; 28 filters remain; G10: RPM runtime dependency metadata (#1275); estimates unchanged; G15: texture-effect distance searches optimized (#1257); idle-machine/platform drag QA still pending; estimate unchanged; G1: Curvature point display improved (#1236, in part); estimates unchanged; G4: full-name font matching (#1258); Windows font-service QA pending; estimate unchanged; G11: no-op anchor Align keeps history and saved state (#1180 follow-up); estimates unchanged; G1: dedicated Eyedropper cursor and precise-cursor checks (#1269); estimates unchanged; G1: Eyedropper reads visible locked and outside-isolation sources (#1251); estimate unchanged; G11: Direct Selection segment Delete (#1278); estimates unchanged; G1: painted strokes regain the existing default after None/zero-width inheritance (#1253); estimate unchanged; G15: large-selection edits, cached live effects and faster Pathfinder, #1173; G4: proportional vertical metrics done, #966; G11: Shape Builder merge seams on grids of lines fixed, #893; scaled text controls corrected, #1034; group font-size preservation deferred; G9: `.ai` gradient matrices and meshes from the editing data; estimate unchanged; G9: `.ai` editing-data follow-ups (gradient stops, type placement, short area-type frames), #1390, #1391, #1392; G15: symbol instance art kept between frames, #1386; G1: dialog keyboard focus, #1367 and #1395; estimates unchanged; G9: placed (linked) files read from `.ai` editing data, #1264; G9: gradient shapes import as paths, #1304, and white constant alpha masks, #1286 in part; G15: linear deselect on hide or lock, #1353; estimates unchanged; G7: custom ruler origin done, #1212; G1: Artboard object clicks create a fitted artboard (#1227); remaining interaction pass and estimate unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; DXF control-point SPLINE closure read, #1299 follow-up; G16: Korean catalog added, 70–110 → 60–100 h; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; G11: valid selection after Simplify and Add Anchor Points (#1272); estimates unchanged; G2: Film Grain added; Photoshop effects 29/57; 28 filters remain; G10: RPM runtime dependency metadata (#1275); estimates unchanged; G15: texture-effect distance searches optimized (#1257); idle-machine/platform drag QA still pending; estimate unchanged; G1: Curvature point display improved (#1236, in part); estimates unchanged; G4: full-name font matching (#1258); Windows font-service QA pending; estimate unchanged; G11: no-op anchor Align keeps history and saved state (#1180 follow-up); estimates unchanged; G1: dedicated Eyedropper cursor and precise-cursor checks (#1269); estimates unchanged; G1: Eyedropper reads visible locked and outside-isolation sources (#1251); estimate unchanged; G11: Direct Selection segment Delete (#1278); estimates unchanged; G1: painted strokes regain the existing default after None/zero-width inheritance (#1253); estimate unchanged; G15: large-selection edits, cached live effects and faster Pathfinder, #1173; G4: proportional vertical metrics done, #966; G11: Shape Builder merge seams on grids of lines fixed, #893; scaled text controls corrected, #1034; group font-size preservation deferred; SVG knockout groups of opaque art export without masks; G9: `.ai` editing-data follow-ups (gradient stops, type placement, short area-type frames), #1390, #1391, #1392; G15: symbol instance art kept between frames, #1386; G1: dialog keyboard focus, #1367 and #1395; estimates unchanged; G9: placed (linked) files read from `.ai` editing data, #1264; G9: gradient shapes import as paths, #1304, and white constant alpha masks, #1286 in part; G15: linear deselect on hide or lock, #1353; estimates unchanged; G7: custom ruler origin done, #1212; G1: Artboard object clicks create a fitted artboard (#1227); remaining interaction pass and estimate unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; DXF control-point SPLINE closure read, #1299 follow-up; G16: Korean catalog added, 70–110 → 60–100 h; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; G11: valid selection after Simplify and Add Anchor Points (#1272); estimates unchanged; G2: Film Grain added; Photoshop effects 29/57; 28 filters remain; G10: RPM runtime dependency metadata (#1275); estimates unchanged; G15: texture-effect distance searches optimized (#1257); idle-machine/platform drag QA still pending; estimate unchanged; G1: Curvature point display improved (#1236, in part); estimates unchanged; G4: full-name font matching (#1258); Windows font-service QA pending; estimate unchanged; G11: no-op anchor Align keeps history and saved state (#1180 follow-up); estimates unchanged; G1: dedicated Eyedropper cursor and precise-cursor checks (#1269); estimates unchanged; G1: Eyedropper reads visible locked and outside-isolation sources (#1251); estimate unchanged; G11: Direct Selection segment Delete (#1278); estimates unchanged; G1: painted strokes regain the existing default after None/zero-width inheritance (#1253); estimate unchanged; G15: large-selection edits, cached live effects and faster Pathfinder, #1173; G4: proportional vertical metrics done, #966; G11: Shape Builder merge seams on grids of lines fixed, #893; scaled text controls corrected, #1034; group font-size preservation deferred; G9: `.ai` keeps its RGB numbers, PDF import keeps strokes apart from fills faded or masked by their group; estimates unchanged; interactive Mirror Repeat axis; G12: Background Export progress dialog with Cancel, #2564; no entry closed, estimates unchanged; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; Blend spine Anchor Point conversions, selection/stacking priority and Shift regression coverage (#2544); scores and hours unchanged; transparency grid visibility saved in native documents, #1968; G6: MCP cancellation, progress notifications and busy answers during long exports, #2165, #2171, #2172; EPS editing data: legacy mesh corners, vector opacity masks and compound member paint retained; raster page comparison filters minification without relaxing limits; scores and hours unchanged; correction: quick Image Trace presets leave the panel as it was, the Image Trace button opens it; batch exporting, #1935; G2: Effect › Sketch › Halftone Pattern; Photoshop filters 30/57, 27 remaining (22–38 h); G5: Symbol Options Export Type (Graphic / Movie Clip); G1: Smart Guides line extension, #2120; G16: Brazilian Portuguese catalog complete under the tests, #1914; Localization 71% → 74%, hours 55–90 → 50–85; G6: image variables landed, estimate 8–14 → 6–12 h; Warp Options controls verified by focused checks and original-image review; estimates unchanged; existing-guide Escape cancellation validated 2026-10-14; scores and hours unchanged; open-path anchor Delete keeps surviving runs separate; estimates unchanged; Artboard tab-switch follow-up historically validated on `a0671777`; scores and hours unchanged; Artboard clean active-tab close/Delete follow-up validated 2026-10-15; G13: Object › Intertwine landed, #1763; no entry closed, estimates unchanged; MCP `add_text` exposes the existing `vertical` option for point, area and path type; horizontal remains the default; scores and hours unchanged; Vertical fullwidth question and exclamation marks keep their nominal glyph upright when the font has no vertical alternate; scores and hours unchanged.; G1: Curvature curve geometry, #1236 in part; Width-point finite-arithmetic follow-up validated; scores and hours unchanged; Image Trace adjustment discovery; G9: legacy `.ai` of version 7 saved with type as text and hidden objects kept, legacy type read, #868; estimate unchanged; Revolve: automatic smooth shading and default-on Cap with continuous rims; later 2026-10-14: G8 untrusted files, #1852, #1862–#1873; G11 anchor X/Y/W/H, #1824, Snap to Grid over Snap to Pixel, #1816, redo during a drag, #1719, Dim Images, #1683, failed-save dialog, #1685; gaps noted for reporters: G1 Warp Options for Effect › Warp, #1760, Color Picker Tab order, #1692, key anchor, #1636; G7 custom toolbars, #1759, workspace panel widths, #1753; G11 Shape Builder gaps between closed shapes, #1691, interior anchor delete; G13 Intertwine, #1763, gradient mesh from an image, #1676, Image Trace radial gradients, #1849; G12 duplicated line removed; no entry closed, estimates unchanged; verified PngSuite downloads, #1729; synthetic control-input budgets, #1709; 2026-10-14 fixes: G11 anchor Align and Distribute, #1636, Delete and selection, #1674, #1666, #1743, #1686, Roughen and Scribble, #1643, #1648; G8 file and input hardening, #1776–#1783, #1786, #1807; G10 Wayland cursors and the Windows title bar, unconfirmed, #1645, #1758; no entry closed, estimates unchanged; later 2026-10-13 fixes, #1570, #1578, #1590, #1613, #1615, #1616, #1620 in part, #1602 in part; no entry closed, estimates unchanged; TIFF is available in Export for Screens and Asset Export with shared format settings; scores and hours unchanged; G1/M11: Artboard deletion and history selection normalization; history regressions and full workspace CI pass; scores and hours unchanged; Character styles retain explicit Auto leading, propagate resets and preserve local leading overrides; scores and hours unchanged; Width Point Edit: Shift-double-click enables adjoining adjustment; plain double-click keeps it off; scores and hours unchanged; G12: Identify Objects By acts, #394; ~16 → ~15 prefs still inert; G12: Appearance of Black › Printing / Exporting acts, #394; ~16 → ~15 prefs still inert; control transport deadlines, #1726; G1: Average and Join in one step with a corner or smooth choice added as missing (it was listed as done in ui-parity.md); Join after Average, #1533; guide objects, #1534; Keyboard Shortcuts, #1539; G9 and G11 fixes, #1528, #1530, #1544, #1553, #1512, #1537; estimates unchanged; Direct Selection anchor precedence, #1508; dialog slider rails, #1483; template layers in Outline view, #1486; Tabs panel stop drags, #1458; type that does not fit its frame is reported, #1471; 3D on outlined type, #1481, Twist range, #1524, twisted walls, #1525; print-size images, #1517; French catalog, #1511; estimates unchanged; G1: Split Into Grid options, #1462, Transform Objects and Reflect's angle, #1448 and #1460, Pathfinder on a group, #1450, value fields, #1457 and #1465 in part; G9: grayscale TIFFs with alpha, #1466 in part; G6: unknown parameter keys refused, #1442; G10: window surfaces past 8192 px, #1459 in part; G15: many-object edits, #1429 in part; estimates unchanged; G16: Vietnamese catalog added, complete under the tests; three key languages remain, 60–100 → 55–90 h; G3: Extrude & Bevel, Inflate and Rotate added, 45–75 → 25–45 h; G9: `.ai` compound path paint, #1410, overprint kept on import, #1388, text-only PDF parts, #1387; G1: Transform dialogs preview, #1412, transforms of direct-selected anchors, #1408, corner drags, #1229; G11: strokes wider than their shape, #1396; estimates unchanged; G9: `.ai` editing-data follow-ups (gradient stops, type placement, short area-type frames), #1390, #1391, #1392; G15: symbol instance art kept between frames, #1386; G1: dialog keyboard focus, #1367 and #1395; estimates unchanged; G9: placed (linked) files read from `.ai` editing data, #1264; G9: gradient shapes import as paths, #1304, and white constant alpha masks, #1286 in part; G15: linear deselect on hide or lock, #1353; estimates unchanged; G7: custom ruler origin done, #1212; G1: Artboard object clicks create a fitted artboard (#1227); remaining interaction pass and estimate unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; DXF control-point SPLINE closure read, #1299 follow-up; G16: Korean catalog added, 70–110 → 60–100 h; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; G11: valid selection after Simplify and Add Anchor Points (#1272); estimates unchanged; G2: Film Grain added; Photoshop effects 29/57; 28 filters remain; G10: RPM runtime dependency metadata (#1275); estimates unchanged; G15: texture-effect distance searches optimized (#1257); idle-machine/platform drag QA still pending; estimate unchanged; G1: Curvature point display improved (#1236, in part); estimates unchanged; G4: full-name font matching (#1258); Windows font-service QA pending; estimate unchanged; G11: no-op anchor Align keeps history and saved state (#1180 follow-up); estimates unchanged; G1: dedicated Eyedropper cursor and precise-cursor checks (#1269); estimates unchanged; G1: Eyedropper reads visible locked and outside-isolation sources (#1251); estimate unchanged; G11: Direct Selection segment Delete (#1278); estimates unchanged; G1: painted strokes regain the existing default after None/zero-width inheritance (#1253); estimate unchanged; G15: large-selection edits, cached live effects and faster Pathfinder, #1173; G4: proportional vertical metrics done, #966; G11: Shape Builder merge seams on grids of lines fixed, #893; scaled text controls corrected, #1034; group font-size preservation deferred; G9: `.ai` gradient matrices and meshes from the editing data; estimate unchanged; G9: `.ai` art styles from the editing data; estimate unchanged; G9: `.ai` editing-data follow-ups (gradient stops, type placement, short area-type frames), #1390, #1391, #1392; G15: symbol instance art kept between frames, #1386; G1: dialog keyboard focus, #1367 and #1395; estimates unchanged; G9: placed (linked) files read from `.ai` editing data, #1264; G9: gradient shapes import as paths, #1304, and white constant alpha masks, #1286 in part; G15: linear deselect on hide or lock, #1353; estimates unchanged; G7: custom ruler origin done, #1212; G1: Artboard object clicks create a fitted artboard (#1227); remaining interaction pass and estimate unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; DXF control-point SPLINE closure read, #1299 follow-up; G16: Korean catalog added, 70–110 → 60–100 h; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; G11: valid selection after Simplify and Add Anchor Points (#1272); estimates unchanged; G2: Film Grain added; Photoshop effects 29/57; 28 filters remain; G10: RPM runtime dependency metadata (#1275); estimates unchanged; G15: texture-effect distance searches optimized (#1257); idle-machine/platform drag QA still pending; estimate unchanged; G1: Curvature point display improved (#1236, in part); estimates unchanged; G4: full-name font matching (#1258); Windows font-service QA pending; estimate unchanged; G11: no-op anchor Align keeps history and saved state (#1180 follow-up); estimates unchanged; G1: dedicated Eyedropper cursor and precise-cursor checks (#1269); estimates unchanged; G1: Eyedropper reads visible locked and outside-isolation sources (#1251); estimate unchanged; G11: Direct Selection segment Delete (#1278); estimates unchanged; G1: painted strokes regain the existing default after None/zero-width inheritance (#1253); estimate unchanged; G15: large-selection edits, cached live effects and faster Pathfinder, #1173; G4: proportional vertical metrics done, #966; G11: Shape Builder merge seams on grids of lines fixed, #893; scaled text controls corrected, #1034; group font-size preservation deferred; G9: `.ai` gradient matrices and meshes from the editing data; estimate unchanged; G9: `.ai` editing-data follow-ups (gradient stops, type placement, short area-type frames), #1390, #1391, #1392; G15: symbol instance art kept between frames, #1386; G1: dialog keyboard focus, #1367 and #1395; estimates unchanged; G9: placed (linked) files read from `.ai` editing data, #1264; G9: gradient shapes import as paths, #1304, and white constant alpha masks, #1286 in part; G15: linear deselect on hide or lock, #1353; estimates unchanged; G7: custom ruler origin done, #1212; G1: Artboard object clicks create a fitted artboard (#1227); remaining interaction pass and estimate unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; DXF control-point SPLINE closure read, #1299 follow-up; G16: Korean catalog added, 70–110 → 60–100 h; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; G11: valid selection after Simplify and Add Anchor Points (#1272); estimates unchanged; G2: Film Grain added; Photoshop effects 29/57; 28 filters remain; G10: RPM runtime dependency metadata (#1275); estimates unchanged; G15: texture-effect distance searches optimized (#1257); idle-machine/platform drag QA still pending; estimate unchanged; G1: Curvature point display improved (#1236, in part); estimates unchanged; G4: full-name font matching (#1258); Windows font-service QA pending; estimate unchanged; G11: no-op anchor Align keeps history and saved state (#1180 follow-up); estimates unchanged; G1: dedicated Eyedropper cursor and precise-cursor checks (#1269); estimates unchanged; G1: Eyedropper reads visible locked and outside-isolation sources (#1251); estimate unchanged; G11: Direct Selection segment Delete (#1278); estimates unchanged; G1: painted strokes regain the existing default after None/zero-width inheritance (#1253); estimate unchanged; G15: large-selection edits, cached live effects and faster Pathfinder, #1173; G4: proportional vertical metrics done, #966; G11: Shape Builder merge seams on grids of lines fixed, #893; scaled text controls corrected, #1034; group font-size preservation deferred; SVG knockout groups of opaque art export without masks; G9: `.ai` editing-data follow-ups (gradient stops, type placement, short area-type frames), #1390, #1391, #1392; G15: symbol instance art kept between frames, #1386; G1: dialog keyboard focus, #1367 and #1395; estimates unchanged; G9: placed (linked) files read from `.ai` editing data, #1264; G9: gradient shapes import as paths, #1304, and white constant alpha masks, #1286 in part; G15: linear deselect on hide or lock, #1353; estimates unchanged; G7: custom ruler origin done, #1212; G1: Artboard object clicks create a fitted artboard (#1227); remaining interaction pass and estimate unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; DXF control-point SPLINE closure read, #1299 follow-up; G16: Korean catalog added, 70–110 → 60–100 h; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; G11: valid selection after Simplify and Add Anchor Points (#1272); estimates unchanged; G2: Film Grain added; Photoshop effects 29/57; 28 filters remain; G10: RPM runtime dependency metadata (#1275); estimates unchanged; G15: texture-effect distance searches optimized (#1257); idle-machine/platform drag QA still pending; estimate unchanged; G1: Curvature point display improved (#1236, in part); estimates unchanged; G4: full-name font matching (#1258); Windows font-service QA pending; estimate unchanged; G11: no-op anchor Align keeps history and saved state (#1180 follow-up); estimates unchanged; G1: dedicated Eyedropper cursor and precise-cursor checks (#1269); estimates unchanged; G1: Eyedropper reads visible locked and outside-isolation sources (#1251); estimate unchanged; G11: Direct Selection segment Delete (#1278); estimates unchanged; G1: painted strokes regain the existing default after None/zero-width inheritance (#1253); estimate unchanged; G15: large-selection edits, cached live effects and faster Pathfinder, #1173; G4: proportional vertical metrics done, #966; G11: Shape Builder merge seams on grids of lines fixed, #893; scaled text controls corrected, #1034; group font-size preservation deferred; G9: `.ai` keeps its RGB numbers, PDF import keeps strokes apart from fills faded or masked by their group; estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-20 · **Change:** minor (live-effect plug-ins given their object's fills and strokes and the item they sit on, G17; plug-in parameters: labels, units, groups, help and conditions in their dialogs, text and number-list parameters, up to 256 of them, G17; exporter plug-ins: plug-in file formats in Export As and document.export, G17; G2: Effect › Artistic › Smudge Stick, Sponge and Watercolor; Sketch › Bas Relief, Charcoal, Photocopy and Stamp, #2533; Photoshop filters 45/57, 12 remaining (8–14 h); on-canvas Mirror Repeat axis, #2877; G12: Background Export progress dialog with Cancel, #2564; status-readout sample widths cached by language, document unit and pixels per point; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; cached canvas reprojection preserves scale during resize, rotation and DPI changes; on-canvas Mirror Repeat axis, #2877; G12: Background Export progress dialog with Cancel, #2564; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; Blend spine Anchor Point conversions, selection/stacking priority and Shift regression coverage (#2544); scores and hours unchanged; transparency grid visibility saved in native documents, #1968; G6: MCP cancellation, progress notifications and busy answers during long exports, #2165, #2171, #2172; EPS editing data: legacy mesh corners, vector opacity masks and compound member paint retained; raster page comparison filters minification without relaxing limits; scores and hours unchanged; correction: quick Image Trace presets leave the panel as it was, the Image Trace button opens it; batch exporting, #1935; G2: Effect › Sketch › Halftone Pattern; Photoshop filters 45/57, 12 remaining (8–14 h); G5: Symbol Options Export Type (Graphic / Movie Clip); G1: Smart Guides line extension, #2120; G16: Brazilian Portuguese catalog complete under the tests, #1914; Localization 71% → 74%, hours 55–90 → 50–85; G6: image variables landed, estimate 8–14 → 6–12 h; Warp Options controls verified by focused checks and original-image review; estimates unchanged; existing-guide Escape cancellation validated 2026-10-14; scores and hours unchanged; open-path anchor Delete keeps surviving runs separate; estimates unchanged; Artboard tab-switch follow-up historically validated on `a0671777`; scores and hours unchanged; Artboard clean active-tab close/Delete follow-up validated 2026-10-15; G13: Object › Intertwine landed, #1763; no entry closed, estimates unchanged; MCP `add_text` exposes the existing `vertical` option for point, area and path type; horizontal remains the default; scores and hours unchanged; Vertical fullwidth question and exclamation marks keep their nominal glyph upright when the font has no vertical alternate; scores and hours unchanged.; G1: Curvature curve geometry, #1236 in part; Width-point finite-arithmetic follow-up validated; scores and hours unchanged; Image Trace adjustment discovery; G9: legacy `.ai` of version 7 saved with type as text and hidden objects kept, legacy type read, #868; estimate unchanged; Revolve: automatic smooth shading and default-on Cap with continuous rims; later 2026-10-14: G8 untrusted files, #1852, #1862–#1873; G11 anchor X/Y/W/H, #1824, Snap to Grid over Snap to Pixel, #1816, redo during a drag, #1719, Dim Images, #1683, failed-save dialog, #1685; gaps noted for reporters: G1 Warp Options for Effect › Warp, #1760, Color Picker Tab order, #1692, key anchor, #1636; G7 custom toolbars, #1759, workspace panel widths, #1753; G11 Shape Builder gaps between closed shapes, #1691, interior anchor delete; G13 Intertwine, #1763, gradient mesh from an image, #1676, Image Trace radial gradients, #1849; G12 duplicated line removed; no entry closed, estimates unchanged; verified PngSuite downloads, #1729; synthetic control-input budgets, #1709; 2026-10-14 fixes: G11 anchor Align and Distribute, #1636, Delete and selection, #1674, #1666, #1743, #1686, Roughen and Scribble, #1643, #1648; G8 file and input hardening, #1776–#1783, #1786, #1807; G10 Wayland cursors and the Windows title bar, unconfirmed, #1645, #1758; no entry closed, estimates unchanged; later 2026-10-13 fixes, #1570, #1578, #1590, #1613, #1615, #1616, #1620 in part, #1602 in part; no entry closed, estimates unchanged; TIFF is available in Export for Screens and Asset Export with shared format settings; scores and hours unchanged; G1/M11: Artboard deletion and history selection normalization; history regressions and full workspace CI pass; scores and hours unchanged; Character styles retain explicit Auto leading, propagate resets and preserve local leading overrides; scores and hours unchanged; Width Point Edit: Shift-double-click enables adjoining adjustment; plain double-click keeps it off; scores and hours unchanged; G12: Identify Objects By acts, #394; ~16 → ~15 prefs still inert; G12: Appearance of Black › Printing / Exporting acts, #394; ~16 → ~15 prefs still inert; control transport deadlines, #1726; G1: Average and Join in one step with a corner or smooth choice added as missing (it was listed as done in ui-parity.md); Join after Average, #1533; guide objects, #1534; Keyboard Shortcuts, #1539; G9 and G11 fixes, #1528, #1530, #1544, #1553, #1512, #1537; estimates unchanged; Direct Selection anchor precedence, #1508; dialog slider rails, #1483; template layers in Outline view, #1486; Tabs panel stop drags, #1458; type that does not fit its frame is reported, #1471; 3D on outlined type, #1481, Twist range, #1524, twisted walls, #1525; print-size images, #1517; French catalog, #1511; estimates unchanged; G1: Split Into Grid options, #1462, Transform Objects and Reflect's angle, #1448 and #1460, Pathfinder on a group, #1450, value fields, #1457 and #1465 in part; G9: grayscale TIFFs with alpha, #1466 in part; G6: unknown parameter keys refused, #1442; G10: window surfaces past 8192 px, #1459 in part; G15: many-object edits, #1429 in part; estimates unchanged; G16: Vietnamese catalog added, complete under the tests; three key languages remain, 60–100 → 55–90 h; G3: Extrude & Bevel, Inflate and Rotate added, 45–75 → 25–45 h; G9: `.ai` compound path paint, #1410, overprint kept on import, #1388, text-only PDF parts, #1387; G1: Transform dialogs preview, #1412, transforms of direct-selected anchors, #1408, corner drags, #1229; G11: strokes wider than their shape, #1396; estimates unchanged; G9: `.ai` editing-data follow-ups (gradient stops, type placement, short area-type frames), #1390, #1391, #1392; G15: symbol instance art kept between frames, #1386; G1: dialog keyboard focus, #1367 and #1395; estimates unchanged; G9: placed (linked) files read from `.ai` editing data, #1264; G9: gradient shapes import as paths, #1304, and white constant alpha masks, #1286 in part; G15: linear deselect on hide or lock, #1353; estimates unchanged; G7: custom ruler origin done, #1212; G1: Artboard object clicks create a fitted artboard (#1227); remaining interaction pass and estimate unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; DXF control-point SPLINE closure read, #1299 follow-up; G16: Korean catalog added, 70–110 → 60–100 h; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; G11: valid selection after Simplify and Add Anchor Points (#1272); estimates unchanged; G2: Film Grain added; Photoshop effects 45/57; 28 filters remain; G10: RPM runtime dependency metadata (#1275); estimates unchanged; G15: texture-effect distance searches optimized (#1257); idle-machine/platform drag QA still pending; estimate unchanged; G1: Curvature point display improved (#1236, in part); estimates unchanged; G4: full-name font matching (#1258); Windows font-service QA pending; estimate unchanged; G11: no-op anchor Align keeps history and saved state (#1180 follow-up); estimates unchanged; G1: dedicated Eyedropper cursor and precise-cursor checks (#1269); estimates unchanged; G1: Eyedropper reads visible locked and outside-isolation sources (#1251); estimate unchanged; G11: Direct Selection segment Delete (#1278); estimates unchanged; G1: painted strokes regain the existing default after None/zero-width inheritance (#1253); estimate unchanged; G15: large-selection edits, cached live effects and faster Pathfinder, #1173; G4: proportional vertical metrics done, #966; G11: Shape Builder merge seams on grids of lines fixed, #893; scaled text controls corrected, #1034; group font-size preservation deferred; G9: `.ai` gradient matrices and meshes from the editing data; estimate unchanged; G9: `.ai` art styles from the editing data; estimate unchanged; G9: `.ai` editing-data follow-ups (gradient stops, type placement, short area-type frames), #1390, #1391, #1392; G15: symbol instance art kept between frames, #1386; G1: dialog keyboard focus, #1367 and #1395; estimates unchanged; G9: placed (linked) files read from `.ai` editing data, #1264; G9: gradient shapes import as paths, #1304, and white constant alpha masks, #1286 in part; G15: linear deselect on hide or lock, #1353; estimates unchanged; G7: custom ruler origin done, #1212; G1: Artboard object clicks create a fitted artboard (#1227); remaining interaction pass and estimate unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; DXF control-point SPLINE closure read, #1299 follow-up; G16: Korean catalog added, 70–110 → 60–100 h; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; G11: valid selection after Simplify and Add Anchor Points (#1272); estimates unchanged; G2: Film Grain added; Photoshop effects 45/57; 28 filters remain; G10: RPM runtime dependency metadata (#1275); estimates unchanged; G15: texture-effect distance searches optimized (#1257); idle-machine/platform drag QA still pending; estimate unchanged; G1: Curvature point display improved (#1236, in part); estimates unchanged; G4: full-name font matching (#1258); Windows font-service QA pending; estimate unchanged; G11: no-op anchor Align keeps history and saved state (#1180 follow-up); estimates unchanged; G1: dedicated Eyedropper cursor and precise-cursor checks (#1269); estimates unchanged; G1: Eyedropper reads visible locked and outside-isolation sources (#1251); estimate unchanged; G11: Direct Selection segment Delete (#1278); estimates unchanged; G1: painted strokes regain the existing default after None/zero-width inheritance (#1253); estimate unchanged; G15: large-selection edits, cached live effects and faster Pathfinder, #1173; G4: proportional vertical metrics done, #966; G11: Shape Builder merge seams on grids of lines fixed, #893; scaled text controls corrected, #1034; group font-size preservation deferred; G9: `.ai` gradient matrices and meshes from the editing data; estimate unchanged; G9: `.ai` editing-data follow-ups (gradient stops, type placement, short area-type frames), #1390, #1391, #1392; G15: symbol instance art kept between frames, #1386; G1: dialog keyboard focus, #1367 and #1395; estimates unchanged; G9: placed (linked) files read from `.ai` editing data, #1264; G9: gradient shapes import as paths, #1304, and white constant alpha masks, #1286 in part; G15: linear deselect on hide or lock, #1353; estimates unchanged; G7: custom ruler origin done, #1212; G1: Artboard object clicks create a fitted artboard (#1227); remaining interaction pass and estimate unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; DXF control-point SPLINE closure read, #1299 follow-up; G16: Korean catalog added, 70–110 → 60–100 h; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; G11: valid selection after Simplify and Add Anchor Points (#1272); estimates unchanged; G2: Film Grain added; Photoshop effects 45/57; 28 filters remain; G10: RPM runtime dependency metadata (#1275); estimates unchanged; G15: texture-effect distance searches optimized (#1257); idle-machine/platform drag QA still pending; estimate unchanged; G1: Curvature point display improved (#1236, in part); estimates unchanged; G4: full-name font matching (#1258); Windows font-service QA pending; estimate unchanged; G11: no-op anchor Align keeps history and saved state (#1180 follow-up); estimates unchanged; G1: dedicated Eyedropper cursor and precise-cursor checks (#1269); estimates unchanged; G1: Eyedropper reads visible locked and outside-isolation sources (#1251); estimate unchanged; G11: Direct Selection segment Delete (#1278); estimates unchanged; G1: painted strokes regain the existing default after None/zero-width inheritance (#1253); estimate unchanged; G15: large-selection edits, cached live effects and faster Pathfinder, #1173; G4: proportional vertical metrics done, #966; G11: Shape Builder merge seams on grids of lines fixed, #893; scaled text controls corrected, #1034; group font-size preservation deferred; SVG knockout groups of opaque art export without masks; G9: `.ai` editing-data follow-ups (gradient stops, type placement, short area-type frames), #1390, #1391, #1392; G15: symbol instance art kept between frames, #1386; G1: dialog keyboard focus, #1367 and #1395; estimates unchanged; G9: placed (linked) files read from `.ai` editing data, #1264; G9: gradient shapes import as paths, #1304, and white constant alpha masks, #1286 in part; G15: linear deselect on hide or lock, #1353; estimates unchanged; G7: custom ruler origin done, #1212; G1: Artboard object clicks create a fitted artboard (#1227); remaining interaction pass and estimate unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; DXF control-point SPLINE closure read, #1299 follow-up; G16: Korean catalog added, 70–110 → 60–100 h; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; G11: valid selection after Simplify and Add Anchor Points (#1272); estimates unchanged; G2: Film Grain added; Photoshop effects 45/57; 28 filters remain; G10: RPM runtime dependency metadata (#1275); estimates unchanged; G15: texture-effect distance searches optimized (#1257); idle-machine/platform drag QA still pending; estimate unchanged; G1: Curvature point display improved (#1236, in part); estimates unchanged; G4: full-name font matching (#1258); Windows font-service QA pending; estimate unchanged; G11: no-op anchor Align keeps history and saved state (#1180 follow-up); estimates unchanged; G1: dedicated Eyedropper cursor and precise-cursor checks (#1269); estimates unchanged; G1: Eyedropper reads visible locked and outside-isolation sources (#1251); estimate unchanged; G11: Direct Selection segment Delete (#1278); estimates unchanged; G1: painted strokes regain the existing default after None/zero-width inheritance (#1253); estimate unchanged; G15: large-selection edits, cached live effects and faster Pathfinder, #1173; G4: proportional vertical metrics done, #966; G11: Shape Builder merge seams on grids of lines fixed, #893; scaled text controls corrected, #1034; group font-size preservation deferred; G9: `.ai` keeps its RGB numbers, PDF import keeps strokes apart from fills faded or masked by their group; estimates unchanged; interactive Mirror Repeat axis; G12: Background Export progress dialog with Cancel, #2564; no entry closed, estimates unchanged; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; Blend spine Anchor Point conversions, selection/stacking priority and Shift regression coverage (#2544); scores and hours unchanged; transparency grid visibility saved in native documents, #1968; G6: MCP cancellation, progress notifications and busy answers during long exports, #2165, #2171, #2172; EPS editing data: legacy mesh corners, vector opacity masks and compound member paint retained; raster page comparison filters minification without relaxing limits; scores and hours unchanged; correction: quick Image Trace presets leave the panel as it was, the Image Trace button opens it; batch exporting, #1935; G2: Effect › Sketch › Halftone Pattern; Photoshop filters 45/57, 12 remaining (8–14 h); G5: Symbol Options Export Type (Graphic / Movie Clip); G1: Smart Guides line extension, #2120; G16: Brazilian Portuguese catalog complete under the tests, #1914; Localization 71% → 74%, hours 55–90 → 50–85; G6: image variables landed, estimate 8–14 → 6–12 h; Warp Options controls verified by focused checks and original-image review; estimates unchanged; existing-guide Escape cancellation validated 2026-10-14; scores and hours unchanged; open-path anchor Delete keeps surviving runs separate; estimates unchanged; Artboard tab-switch follow-up historically validated on `a0671777`; scores and hours unchanged; Artboard clean active-tab close/Delete follow-up validated 2026-10-15; G13: Object › Intertwine landed, #1763; no entry closed, estimates unchanged; MCP `add_text` exposes the existing `vertical` option for point, area and path type; horizontal remains the default; scores and hours unchanged; Vertical fullwidth question and exclamation marks keep their nominal glyph upright when the font has no vertical alternate; scores and hours unchanged.; G1: Curvature curve geometry, #1236 in part; Width-point finite-arithmetic follow-up validated; scores and hours unchanged; Image Trace adjustment discovery; G9: legacy `.ai` of version 7 saved with type as text and hidden objects kept, legacy type read, #868; estimate unchanged; Revolve: automatic smooth shading and default-on Cap with continuous rims; later 2026-10-14: G8 untrusted files, #1852, #1862–#1873; G11 anchor X/Y/W/H, #1824, Snap to Grid over Snap to Pixel, #1816, redo during a drag, #1719, Dim Images, #1683, failed-save dialog, #1685; gaps noted for reporters: G1 Warp Options for Effect › Warp, #1760, Color Picker Tab order, #1692, key anchor, #1636; G7 custom toolbars, #1759, workspace panel widths, #1753; G11 Shape Builder gaps between closed shapes, #1691, interior anchor delete; G13 Intertwine, #1763, gradient mesh from an image, #1676, Image Trace radial gradients, #1849; G12 duplicated line removed; no entry closed, estimates unchanged; verified PngSuite downloads, #1729; synthetic control-input budgets, #1709; 2026-10-14 fixes: G11 anchor Align and Distribute, #1636, Delete and selection, #1674, #1666, #1743, #1686, Roughen and Scribble, #1643, #1648; G8 file and input hardening, #1776–#1783, #1786, #1807; G10 Wayland cursors and the Windows title bar, unconfirmed, #1645, #1758; no entry closed, estimates unchanged; later 2026-10-13 fixes, #1570, #1578, #1590, #1613, #1615, #1616, #1620 in part, #1602 in part; no entry closed, estimates unchanged; TIFF is available in Export for Screens and Asset Export with shared format settings; scores and hours unchanged; G1/M11: Artboard deletion and history selection normalization; history regressions and full workspace CI pass; scores and hours unchanged; Character styles retain explicit Auto leading, propagate resets and preserve local leading overrides; scores and hours unchanged; Width Point Edit: Shift-double-click enables adjoining adjustment; plain double-click keeps it off; scores and hours unchanged; G12: Identify Objects By acts, #394; ~16 → ~15 prefs still inert; G12: Appearance of Black › Printing / Exporting acts, #394; ~16 → ~15 prefs still inert; control transport deadlines, #1726; G1: Average and Join in one step with a corner or smooth choice added as missing (it was listed as done in ui-parity.md); Join after Average, #1533; guide objects, #1534; Keyboard Shortcuts, #1539; G9 and G11 fixes, #1528, #1530, #1544, #1553, #1512, #1537; estimates unchanged; Direct Selection anchor precedence, #1508; dialog slider rails, #1483; template layers in Outline view, #1486; Tabs panel stop drags, #1458; type that does not fit its frame is reported, #1471; 3D on outlined type, #1481, Twist range, #1524, twisted walls, #1525; print-size images, #1517; French catalog, #1511; estimates unchanged; G1: Split Into Grid options, #1462, Transform Objects and Reflect's angle, #1448 and #1460, Pathfinder on a group, #1450, value fields, #1457 and #1465 in part; G9: grayscale TIFFs with alpha, #1466 in part; G6: unknown parameter keys refused, #1442; G10: window surfaces past 8192 px, #1459 in part; G15: many-object edits, #1429 in part; estimates unchanged; G16: Vietnamese catalog added, complete under the tests; three key languages remain, 60–100 → 55–90 h; G3: Extrude & Bevel, Inflate and Rotate added, 45–75 → 25–45 h; G9: `.ai` compound path paint, #1410, overprint kept on import, #1388, text-only PDF parts, #1387; G1: Transform dialogs preview, #1412, transforms of direct-selected anchors, #1408, corner drags, #1229; G11: strokes wider than their shape, #1396; estimates unchanged; G9: `.ai` editing-data follow-ups (gradient stops, type placement, short area-type frames), #1390, #1391, #1392; G15: symbol instance art kept between frames, #1386; G1: dialog keyboard focus, #1367 and #1395; estimates unchanged; G9: placed (linked) files read from `.ai` editing data, #1264; G9: gradient shapes import as paths, #1304, and white constant alpha masks, #1286 in part; G15: linear deselect on hide or lock, #1353; estimates unchanged; G7: custom ruler origin done, #1212; G1: Artboard object clicks create a fitted artboard (#1227); remaining interaction pass and estimate unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; DXF control-point SPLINE closure read, #1299 follow-up; G16: Korean catalog added, 70–110 → 60–100 h; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; G11: valid selection after Simplify and Add Anchor Points (#1272); estimates unchanged; G2: Film Grain added; Photoshop effects 45/57; 28 filters remain; G10: RPM runtime dependency metadata (#1275); estimates unchanged; G15: texture-effect distance searches optimized (#1257); idle-machine/platform drag QA still pending; estimate unchanged; G1: Curvature point display improved (#1236, in part); estimates unchanged; G4: full-name font matching (#1258); Windows font-service QA pending; estimate unchanged; G11: no-op anchor Align keeps history and saved state (#1180 follow-up); estimates unchanged; G1: dedicated Eyedropper cursor and precise-cursor checks (#1269); estimates unchanged; G1: Eyedropper reads visible locked and outside-isolation sources (#1251); estimate unchanged; G11: Direct Selection segment Delete (#1278); estimates unchanged; G1: painted strokes regain the existing default after None/zero-width inheritance (#1253); estimate unchanged; G15: large-selection edits, cached live effects and faster Pathfinder, #1173; G4: proportional vertical metrics done, #966; G11: Shape Builder merge seams on grids of lines fixed, #893; scaled text controls corrected, #1034; group font-size preservation deferred; G9: `.ai` gradient matrices and meshes from the editing data; estimate unchanged; G9: `.ai` art styles from the editing data; estimate unchanged; G9: `.ai` editing-data follow-ups (gradient stops, type placement, short area-type frames), #1390, #1391, #1392; G15: symbol instance art kept between frames, #1386; G1: dialog keyboard focus, #1367 and #1395; estimates unchanged; G9: placed (linked) files read from `.ai` editing data, #1264; G9: gradient shapes import as paths, #1304, and white constant alpha masks, #1286 in part; G15: linear deselect on hide or lock, #1353; estimates unchanged; G7: custom ruler origin done, #1212; G1: Artboard object clicks create a fitted artboard (#1227); remaining interaction pass and estimate unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; DXF control-point SPLINE closure read, #1299 follow-up; G16: Korean catalog added, 70–110 → 60–100 h; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; G11: valid selection after Simplify and Add Anchor Points (#1272); estimates unchanged; G2: Film Grain added; Photoshop effects 45/57; 28 filters remain; G10: RPM runtime dependency metadata (#1275); estimates unchanged; G15: texture-effect distance searches optimized (#1257); idle-machine/platform drag QA still pending; estimate unchanged; G1: Curvature point display improved (#1236, in part); estimates unchanged; G4: full-name font matching (#1258); Windows font-service QA pending; estimate unchanged; G11: no-op anchor Align keeps history and saved state (#1180 follow-up); estimates unchanged; G1: dedicated Eyedropper cursor and precise-cursor checks (#1269); estimates unchanged; G1: Eyedropper reads visible locked and outside-isolation sources (#1251); estimate unchanged; G11: Direct Selection segment Delete (#1278); estimates unchanged; G1: painted strokes regain the existing default after None/zero-width inheritance (#1253); estimate unchanged; G15: large-selection edits, cached live effects and faster Pathfinder, #1173; G4: proportional vertical metrics done, #966; G11: Shape Builder merge seams on grids of lines fixed, #893; scaled text controls corrected, #1034; group font-size preservation deferred; G9: `.ai` gradient matrices and meshes from the editing data; estimate unchanged; G9: `.ai` editing-data follow-ups (gradient stops, type placement, short area-type frames), #1390, #1391, #1392; G15: symbol instance art kept between frames, #1386; G1: dialog keyboard focus, #1367 and #1395; estimates unchanged; G9: placed (linked) files read from `.ai` editing data, #1264; G9: gradient shapes import as paths, #1304, and white constant alpha masks, #1286 in part; G15: linear deselect on hide or lock, #1353; estimates unchanged; G7: custom ruler origin done, #1212; G1: Artboard object clicks create a fitted artboard (#1227); remaining interaction pass and estimate unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; DXF control-point SPLINE closure read, #1299 follow-up; G16: Korean catalog added, 70–110 → 60–100 h; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; G11: valid selection after Simplify and Add Anchor Points (#1272); estimates unchanged; G2: Film Grain added; Photoshop effects 45/57; 28 filters remain; G10: RPM runtime dependency metadata (#1275); estimates unchanged; G15: texture-effect distance searches optimized (#1257); idle-machine/platform drag QA still pending; estimate unchanged; G1: Curvature point display improved (#1236, in part); estimates unchanged; G4: full-name font matching (#1258); Windows font-service QA pending; estimate unchanged; G11: no-op anchor Align keeps history and saved state (#1180 follow-up); estimates unchanged; G1: dedicated Eyedropper cursor and precise-cursor checks (#1269); estimates unchanged; G1: Eyedropper reads visible locked and outside-isolation sources (#1251); estimate unchanged; G11: Direct Selection segment Delete (#1278); estimates unchanged; G1: painted strokes regain the existing default after None/zero-width inheritance (#1253); estimate unchanged; G15: large-selection edits, cached live effects and faster Pathfinder, #1173; G4: proportional vertical metrics done, #966; G11: Shape Builder merge seams on grids of lines fixed, #893; scaled text controls corrected, #1034; group font-size preservation deferred; SVG knockout groups of opaque art export without masks; G9: `.ai` editing-data follow-ups (gradient stops, type placement, short area-type frames), #1390, #1391, #1392; G15: symbol instance art kept between frames, #1386; G1: dialog keyboard focus, #1367 and #1395; estimates unchanged; G9: placed (linked) files read from `.ai` editing data, #1264; G9: gradient shapes import as paths, #1304, and white constant alpha masks, #1286 in part; G15: linear deselect on hide or lock, #1353; estimates unchanged; G7: custom ruler origin done, #1212; G1: Artboard object clicks create a fitted artboard (#1227); remaining interaction pass and estimate unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; DXF control-point SPLINE closure read, #1299 follow-up; G16: Korean catalog added, 70–110 → 60–100 h; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; G11: valid selection after Simplify and Add Anchor Points (#1272); estimates unchanged; G2: Film Grain added; Photoshop effects 45/57; 28 filters remain; G10: RPM runtime dependency metadata (#1275); estimates unchanged; G15: texture-effect distance searches optimized (#1257); idle-machine/platform drag QA still pending; estimate unchanged; G1: Curvature point display improved (#1236, in part); estimates unchanged; G4: full-name font matching (#1258); Windows font-service QA pending; estimate unchanged; G11: no-op anchor Align keeps history and saved state (#1180 follow-up); estimates unchanged; G1: dedicated Eyedropper cursor and precise-cursor checks (#1269); estimates unchanged; G1: Eyedropper reads visible locked and outside-isolation sources (#1251); estimate unchanged; G11: Direct Selection segment Delete (#1278); estimates unchanged; G1: painted strokes regain the existing default after None/zero-width inheritance (#1253); estimate unchanged; G15: large-selection edits, cached live effects and faster Pathfinder, #1173; G4: proportional vertical metrics done, #966; G11: Shape Builder merge seams on grids of lines fixed, #893; scaled text controls corrected, #1034; group font-size preservation deferred; G9: `.ai` keeps its RGB numbers, PDF import keeps strokes apart from fills faded or masked by their group; estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) Every known shortfall against Illustrator, one entry each, **ranked by how much it stops a professional from switching**. This is the work list: unless you were given a task, pick the highest-ranked gap you can make @@ -22,7 +22,7 @@ stage ([ROADMAP.md](../ROADMAP.md)). | 5 | [G11 Correctness bugs in core tools](#g11-correctness-bugs-in-core-tools) | 8–15 | yes | [target-app-parity.md](target-app-parity.md) | | 6 | [G4 Advanced type](#g4-advanced-type) | 34–47 | core part | [type-parity.md](type-parity.md) | | 7 | [G12 Preferences and panels that don't act yet](#g12-preferences-and-panels-that-dont-act-yet) | 13–20 | yes | [ui-parity.md](ui-parity.md) | -| 8 | [G2 Photoshop-style raster effects and the Effect Gallery](#g2-photoshop-style-raster-effects-and-the-effect-gallery) | 21–35 | no | [effects-parity.md](effects-parity.md) | +| 8 | [G2 Photoshop-style raster effects and the Effect Gallery](#g2-photoshop-style-raster-effects-and-the-effect-gallery) | 8–14 | no | [effects-parity.md](effects-parity.md) | | 9 | [G13 Illustrator 2026 (30.x) additions](#g13-illustrator-2026-30x-additions) | 15–25 | no | [target-app-parity.md](target-app-parity.md) | | 10 | [G14 Pen hardware beyond Windows pressure](#g14-pen-hardware-beyond-windows-pressure) | 8–16 | macOS pressure | [hardware-parity.md](hardware-parity.md) | | 11 | [G5 Brushes, symbols and libraries](#g5-brushes-symbols-and-libraries) | 16–27 | no | [target-app-parity.md](target-app-parity.md) | @@ -43,6 +43,10 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall ## G1 Interaction fidelity +- **Implemented, regression-tested and contributor-confirmed:** status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates. Original-file acceptance confirmed 2026-10-19; broader G1 scope and estimates unchanged. Sample widths are cached by language, document unit and pixels per point rather than remeasured every frame. + +- **Canvas review follow-up:** Cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission. Controlled-worker regression checks oversized width and height, high DPI and the render transform without allocating oversized images. G1 scope and estimates are unchanged. +- **Done (#3106):** while the window is resized, rotated or moved to a screen of another DPI, the cached canvas frame is redrawn at its own scale until the next render, at most the renderer's largest raster size. Broader G1 scope and estimates unchanged. - **Done (#2877):** a selected Mirror Repeat shows its axis: drag the line or the center handle to move it, an end handle to rotate it (Shift: 45°); each drag is one undo step and Escape cancels it. Bounding-box handles take priority over the axis line; the center and end handles keep their actions. Broader G1 estimates unchanged. - **Existing-guide Escape cancellation:** Selection and Direct/Group Selection clear pending presses and cancel begun guide previews. App-input regressions cover preselected-guide document and interaction-start selection restoration, Undo/Redo and saved state, and later on-canvas motion/release. All eight app-input checks and the Direct Selection Escape control passed in current full CI; [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area). The broader G1 scope and estimate remain unchanged. @@ -76,7 +80,9 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Missing:** Average and Join in one step, with a corner or smooth choice for the joined anchor. `path.average` and `path.join` are separate commands and Join has no such choice (coinciding anchors merge into one since #1533). [ui-parity.md](ui-parity.md) listed "Join with corner/smooth choice" as done until 2026-10-13. About 1–2 h (estimated), inside the estimate below. - **Implemented (#1760):** Effect › Warp has a shared style selector with original previews, orientation buttons and percent sliders. Existing effects retain their stack slot and target. Focused checks passed and original captures were reviewed; optional Properties integration and remembered defaults remain outside this change. - **Done (#2120):** Smart Guides line extension: dragging the end of a straight segment with Direct Selection or Curvature, the point snaps to the segment's own direction at any angle and the guide runs along it from the other end. Inside the estimate below. -- **Missing (noted for reporters, 2026-10-14):** Tab in the Color Picker moves through its fields in order (#1692); aligning anchor points selected with +- **Done (#1692):** Tab in the Color Picker moves through one color model's fields before the next. Completed upstream before the layout change (#2008). +- **Improved (#2008):** Color Picker layout: stacked top-right actions, aligned inputs, less empty space, a distinct header and compact color controls. Narrow windows use stacked sections and vertical scrolling. Pointer/key, warning, layout and mode-switch regressions cover the change; the broader fidelity pass and estimates remain unchanged. +- **Missing (noted for reporters, 2026-10-14):** aligning anchor points selected with Direct Selection to a key anchor (from #1636: they align to their bounds; the current public Align page does not say how the key anchor is chosen, so this waits for the owner). Inside the estimate below. - **Missing:** a tool-by-tool, panel-by-panel pass over modifiers, cursors, the Properties panel per context, @@ -93,7 +99,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Missing:** faithful layer and group structure from the editing data in real files (#951: 109 layers instead of 14), guides and non-printing construction - lines (#779), open speed on large files (#758), live effects, brushes and symbols as live objects (#637; pattern fills and global colours are read since #1025, placed (linked) files since #1264). Writing Illustrator's own editing data is out of scope + lines (#779), open speed on large files (#758), live effects, brushes and symbols as live objects (#637; plain art styles read Drop Shadow, Outer Glow and Feather as live effects; pattern fills and global colours are read since #1025, placed (linked) files since #1264). Writing Illustrator's own editing data is out of scope (undocumented): a PDF-compatible `.ai` opens in Illustrator 2018 without its layers and groups (#868). Save As `.ai` › Version: Legacy (version 7) writes the PostScript form from the published version 7 specification instead, keeping layers (names, order, visibility, lock), groups, compound paths, clipping groups, gradients and @@ -154,7 +160,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Done:** Numeric fields keep a text drag's start when the pointer gains focus and movement exceeds the click threshold (#1326, in part). A completed focus click selects the whole value; keyboard focus, double-click and numeric stepping remain regression-tested. Short movements still classified as clicks can select all; that case remains open. -- **Done:** DXF reads control-point SPLINE closure (#1299 follow-up after #1320); open curves keep their open state. Escape leaves Artboard editing for Selection; during a drag it first cancels the gesture. Headless egui key events cover idle Escape, active-drag cancellation and a subsequent Escape in `tests_distortkeys.rs`. +- **Done:** DXF reads control-point SPLINE closure (#1299 follow-up after #1320); open curves keep their open state. DXF export now recognizes circular cubic paths conservatively and writes native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE, and a non-circular ellipse keeps the existing fallback. CNC preset and VCarve QA remain open. Escape leaves Artboard editing for Selection; during a drag it first cancels the gesture. Headless egui key events cover idle Escape, active-drag cancellation and a subsequent Escape in `tests_distortkeys.rs`. - **Done:** Simplify and Add Anchor Points clear stale component selections on rewritten paths; Simplify previews and reports original/new point counts (#1272). - **Done:** no-op anchor Align preserves Undo, Redo, saved state and path geometry (#1180 follow-up), @@ -217,13 +223,13 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall ## G2 Photoshop-style raster effects and the Effect Gallery -- **Missing:** 24 of 57 filters (the remaining 11 Artistic filters and 13 of Sketch's 14), the Effect Gallery dialog, Load +- **Missing:** 11 of 57 filters (7 Artistic, 3 Sketch and 1 more), the Effect Gallery dialog, Load Texture for Texturizer. Measured in [effects-parity.md](effects-parity.md). -- **Done:** the pixel-filter pipeline and 33 filters (Artistic: Cutout, Film Grain, Neon Glow, Poster Edges, Blur, Brush Strokes, Distort, Pixelate, Sharpen, Sketch: - Halftone Pattern, Stylize, Texture, Video), Brush Strokes on 2026-10-11, Film Grain on 2026-10-12, Halftone Pattern on 2026-10-16, Cutout, Neon Glow and Poster Edges on 2026-10-16, and Smart Blur's Edge Only and Overlay Edge +- **Done:** the pixel-filter pipeline and 45 filters (Artistic: Cutout, Film Grain, Neon Glow, Plastic Wrap, Poster Edges, Smudge Stick, Sponge, Watercolor; Blur, Brush Strokes, Distort, Pixelate, Sharpen; Sketch: + Bas Relief, Chalk & Charcoal, Charcoal, Chrome, Graphic Pen, Halftone Pattern, Photocopy, Plaster, Reticulation, Stamp; Stylize, Texture, Video), with live preview and editable native settings. Smart Blur supports Edge Only and Overlay Edge modes. -- **Estimate:** 21–35 h (measured 0.7–1.2 h per filter); parallelizes well. +- **Estimate:** 8–14 h (measured 0.7–1.2 h per filter); parallelizes well. ## G13 Illustrator 2026 (30.x) additions @@ -288,22 +294,12 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall ## G6 Automation and scripting -- **Missing:** a scripting surface over the command registry (Illustrator: JavaScript), image and graph - variable kinds (dataset CSV import/export and Batch are open as PRs). Actions, Variables (text and - visibility) and full agent control over MCP are done. -- **Estimate:** 6–12 h. -- **Missing:** a scripting surface over the command registry (Illustrator: JavaScript), Batch, image variable kind and dataset import/export (graph variables land separately). Actions, Variables (text, - visibility, graph) and full agent control over MCP are done. -- **Estimate:** 8–14 h. -- **Missing:** a scripting surface over the command registry (Illustrator: JavaScript), Batch, graph variable - kinds. Actions, Variables (text, visibility and image), dataset CSV import/export and full agent control over - kinds, dataset import/export. Actions, Variables (text, visibility and image) and full agent control over +- **Missing:** a scripting surface over the command registry (Illustrator: JavaScript, File › Scripts; + #1183 is open). Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and + export, and full agent control over MCP are done. +- **Estimate:** 4–8 h. - **Done (2026-10-16):** the MCP server hears the client during a long call: `notifications/cancelled` stops a queued or running export (PDF pages, flattening, baking, drawing, artboards) without writing anything or changing the document, `ping` and the list methods answer at once, any other request that would wait behind a call running for two seconds or more is refused as busy (`-32003`, naming the call), and `_meta.progressToken` gets page progress (#2165, #2171, #2172). Reading the document during an export is not served (refused as busy); estimate unchanged. - **Exposed in MCP:** `add_text {vertical: true}` uses the existing vertical point, area and path type commands. Horizontal writing remains the default; the broader automation gap and estimate are unchanged. -- **Missing:** a scripting surface over the command registry (Illustrator: JavaScript), Batch, image and graph - variable kinds, dataset import/export. Actions, Variables (text and visibility) and full agent control over - MCP are done. -- **Estimate:** 4–8 h. ## G15 Performance budgets and a GPU renderer @@ -313,8 +309,6 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall on 2026-10-13, missed all three render budgets at 20k paths), a spatial index for zoomed-in frames, dirty-region rendering, the GPU backend spike (M5). Large-selection edits, cached live effects and Pathfinder Trim, Merge, Crop and Outline landed in #1173. -- **Not redrawn:** the canvas keeps drawing these objects as they were: - in the web build, type with a geometry effect keeps a substitute font's outlines after its own font has loaded. - **Estimate:** 15–25 h (the budget run and fixes block beta). ## G16 Localization: the three missing key languages @@ -329,8 +323,22 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall ## G17 Ecosystem: third-party plug-ins - **Missing:** Illustrator's ecosystem is a C++ plug-in SDK and a large commercial plug-in market. VectorCraft - has sandboxed WebAssembly plug-ins for object filters and live effects ([plugins.md](plugins.md)) and MCP; - missing are tool plug-ins, panel plug-ins, a plug-in directory and any third-party plug-ins (#710). + has sandboxed WebAssembly plug-ins for object filters, live effects and file formats it writes + ([plugins.md](plugins.md)) and MCP; missing are tool plug-ins, panel plug-ins, importers, a plug-in directory and + any third-party plug-ins (#710). +- **Done:** exporter plug-ins (`"kind": "exporter"`). A plug-in adds a write-only file format that File › Export › + Export As lists after the built-in ones and `document.export` writes (`plugin.`, or a path ending in one of its + extensions). It is given the document as the native file's JSON and its parameters, with a larger budget than a + filter's, which Background Export's Cancel stops; the host writes the file it returns, and nothing when it declines + or returns bad data. Engine, ABI and headless Export As regressions. +- **Done:** a plug-in's parameters say how its dialogs show them: `label`, `unit`, `help`, `helpUrl`, `group` + (sections that fold) and `visibleWhen` (shown only while the checkboxes and choices it names have one of the + listed values). `string` and `numberList` parameters join the others, and a plug-in declares up to 256, at most 64 + outside groups. The filter, live-effect and exporter dialogs use them, and the Appearance panel's effect editor the + labels, units, help and conditions; hosts from before the keys ignore them. Manifest unit tests and kittest dialog + regressions. +- **Done:** a live effect is given its object's fills and strokes, read only, as a filter is, and `_context.item` + says which fill or stroke it sits on; a change of paint runs it again. Engine and unit regressions. - **Estimate:** 20–45 h for the APIs; the ecosystem itself isn't agent work. ## G18 Generative AI features @@ -351,6 +359,14 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall | Date | Change | Summary | |---|---|---| +| 2026-10-19 | minor | G17: live-effect plug-ins are given their object's fills and strokes, read only, and the item they sit on; engine and unit regressions. No entry closed, estimates unchanged. | +| 2026-10-19 | minor | G17: plug-in parameters with labels, units, help, groups and conditions (`visibleWhen`), `string` and `numberList` types, up to 256 per plug-in; manifest and kittest dialog regressions. No entry closed, estimates unchanged. | +| 2026-10-19 | minor | G17: exporter plug-ins, plug-in file formats that Export As and `document.export` write; engine, ABI and headless Export As regressions. No entry closed, estimates unchanged. | +| 2026-10-19 | minor | Cache status-readout sample widths per UI, language, document unit and pixels per point; regressions check reuse across live frames and refresh after display-setting changes. Scores and estimates unchanged. | +| 2026-10-19 | minor | Status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates. Contributor original-file acceptance confirmed; scores and estimates unchanged. | +| 2026-10-19 | minor | Cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission. Regression coverage; scores and estimates unchanged. | +| 2026-10-19 | minor | Cached canvas reprojection preserves scale during resize, rotation and DPI changes. Contributor original-file acceptance confirmed; scores and estimates unchanged. | +| 2026-10-19 | minor | Color Picker layout (#2008): compact controls, centered header, stacked actions and aligned inputs; screen-reader channel values, current shared button names and styling, screen sampler and model-by-model Tab order retained. Narrow windows scroll vertically. Documentation correction: #1692 was completed upstream before #2008; the Direct Selection alignment gap remains open. Scores and hours unchanged. | | 2026-10-18 | minor | Mirror Repeat shows its axis when selected (#2877): drag the line or center handle to move it, drag an end handle to rotate it (Shift: 45°), Escape cancels and each drag is one undo step. Engine and headless canvas gesture regressions passed; native move, rotation and Escape screenshots reviewed. Formatting, Clippy, WASM and repository checks passed; the undo label reuses translated Repeat Options. (#2877) Scores and hours unchanged. | | 2026-10-18 | minor | Bounding-box handles take priority where a selected Mirror Repeat axis crosses them; a Top-handle regression confirms scaling of the default repeat. Center and end handles retain their move and rotation behavior. G1 scope and estimate unchanged. | | 2026-10-17 | minor | Blend spine Anchor Point conversions, selection/stacking priority and Shift regression coverage (#2544); scores and hours unchanged. Windows native canvas checks and screenshots reviewed in PR #2643. | @@ -361,6 +377,8 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall | 2026-10-16 | minor | EPS editing data: legacy mesh corners, vector opacity masks and compound member paint retained; raster page comparison filters minification without relaxing limits; scores and hours unchanged. Synthetic EPS/parser/minification regressions; user EPS/SVG/JPG kept local. | | 2026-10-16 | minor | Correction to G12: quick Image Trace presets trace at once and leave the panel as it was; the Image Trace button in the Control bar or Properties opens the controls (). Wording only; no entry opened or closed, estimates unchanged. | | 2026-10-16 | minor | Batch exporting in Export for Screens (#1935): a file name pattern (document and item names, a counter, the date), folders per format, item or both, Layers and Selection tabs with thumbnails, EPS, AI and VectorCraft rows, a PDF row with printer's marks, and export presets (built-in Logo Package and Print-Ready PDF, saved ones); scores and hours unchanged (estimated) | +| 2026-10-16 | minor | G2: Effect › Artistic › Smudge Stick, Sponge and Watercolor (original approximations with their documented options); measured Photoshop filters 36/57 with Cutout, Neon Glow and Poster Edges, 21 remaining (19–31 h). | +| 2026-10-16 | minor | G2: Effect › Sketch › Bas Relief, Charcoal, Photocopy and Stamp (#2527); measured Photoshop filters 37/57 with Cutout, Neon Glow and Poster Edges, 20 remaining (18–30 h). | | 2026-10-16 | minor | G2: Effect › Sketch › Halftone Pattern (Size, Contrast, Pattern Type Circle, Dot or Line; black ink on white paper, Size in points at any Document Raster Effects resolution); measured Photoshop filters 30/57, 27 remaining (22–38 h). | | 2026-10-16 | minor | G1: Smart Guides line extension for a dragged end of a straight segment, at any angle (#2120); estimate unchanged | | 2026-10-15 | minor | G1: no busy cursor during long operations, listed; estimate unchanged | diff --git a/docs/localization-parity.md b/docs/localization-parity.md index aefc1f64ff..d0cdd9d095 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -51,7 +51,7 @@ plus review. Native-speaker review is human work and isn't in the hours. | Ukrainian | `uk` | 4,009 / 4,020 (one/few/many plurals) | full | | Hungarian | `hu` | 4,524 rows: menus, `tl!` literals and messages complete (tests); one plural form | full | | Polish | `pl` | 4,510 rows (counted 2026-10-13): menus, `tl!` literals and messages complete (tests); one/few/many plurals | full; native review pending | -| Finnish | `fi` | 4,770 rows: menus, `tl!` literals and messages complete (tests); one/other plurals, 668 `@msg` rows | full; AI-assisted, native proofreading pending | +| Finnish | `fi` | 5,218 rows: menus, `tl!` literals and messages complete (tests); one/other plurals, 769 `@msg` rows | full; AI-assisted, native proofreading pending | | Czech | `cs` | 4,411 catalog entries, including 636 `@msg` rows (measured locally 2026-10-11); menu, literal and message coverage enforced by tests | catalog complete; render-site gaps reduced; native review pending | | Swedish | `sv` | 4,770 rows, 668 of them `@msg` (counted 2026-10-15): menus, `tl!` literals and messages complete (tests); one/other plurals | full; native review welcome | | Bulgarian | `bg` | 4,910 rows, 703 of them `@msg` (counted 2026-10-16): menus, `tl!` literals and messages complete (tests) | full; AI-drafted, native review pending | diff --git a/docs/mcp.md b/docs/mcp.md index acdc7a6fad..73a332a50a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14,22 +14,42 @@ It has two backends: With no flag, the server tries `127.0.0.1:7979` and falls back to headless. Logs go to stderr; stdout carries only protocol messages. -## Build and register +## Install and register + +From the repository root, with Rust 1.95+ and the platform's source-build prerequisites installed: ```sh -cargo build --release -p vectorcraft-cli -claude mcp add vectorcraft -- "$PWD/target/release/vectorcraft-cli" mcp +cargo install --path apps/vectorcraft-cli --locked +# POSIX shells, for Cargo's default install location: +export PATH="${CARGO_HOME:-$HOME/.cargo}/bin:$PATH" +vectorcraft-cli --help +claude mcp add vectorcraft -- vectorcraft-cli mcp # or pin a mode: -claude mcp add vectorcraft-headless -- "$PWD/target/release/vectorcraft-cli" mcp --headless -claude mcp add vectorcraft-app -- "$PWD/target/release/vectorcraft-cli" mcp --connect 127.0.0.1:7979 +claude mcp add vectorcraft-headless -- vectorcraft-cli mcp --headless +claude mcp add vectorcraft-app -- vectorcraft-cli mcp --connect 127.0.0.1:7979 ``` +Cargo installs a binary, not a symlink into `target/`, so it survives `cargo clean`. +Re-run the install command after updating the checkout. +By default the executable goes in `$CARGO_HOME/bin` (`~/.cargo/bin` when unset), or +`%USERPROFILE%\.cargo\bin` on Windows. If you set `--root`, `CARGO_INSTALL_ROOT`, or +Cargo's `install.root`, use that installation root's `bin` directory instead. Add it +to the `PATH` inherited by the MCP client, not just an interactive shell, and restart +the client after changing its environment. Installing does not start or register a server. + Other clients use the same command in their JSON config: ```json -{"mcpServers": {"vectorcraft": {"command": "/abs/path/target/release/vectorcraft-cli", "args": ["mcp"]}}} +{"mcpServers": {"vectorcraft": {"command": "vectorcraft-cli", "args": ["mcp"]}}} ``` +If a client reports `ENOENT` or "Executable not found in $PATH", verify the install with +`command -v vectorcraft-cli` (PowerShell: `Get-Command vectorcraft-cli`) in the client's +environment. If that environment cannot be changed, set JSON `command` to the absolute +installed binary path, not a literal `~` or `$HOME` expression. Avoid symlinks into +`target/release`: cleaning the build directory breaks them. A source build alone does +not put the CLI on `PATH`. + For a live session, start the app first: `cargo run --release -p vectorcraft -- --control 7979`. ### From an installed release @@ -56,7 +76,7 @@ vectorcraft-cli mcp --automation-read-root /work/project --automation-write-root ``` ```json -{"mcpServers": {"vectorcraft": {"command": "/abs/path/target/release/vectorcraft-cli", +{"mcpServers": {"vectorcraft": {"command": "vectorcraft-cli", "args": ["mcp", "--automation-read-root", "/work/project", "--automation-write-root", "/work/project/out"]}}} ``` @@ -836,9 +856,12 @@ SOURCE_DATE_EPOCH=1791208980 vectorcraft-cli run --cmd file.new --params '{}' -- A command that takes its own date (`file.new {created}`, a save's `modified`) still wins over the variable. A blank, negative or non-numeric value is ignored and the clock decides, so an export is -never refused over the environment. The variable does not reach the recovery heartbeat or the -random seed PDF encryption draws on, which must follow the real clock. SVG output carries no time -and was already reproducible. +never refused over the environment. SVG output carries no time and was already reproducible. + +Two things stay on the real clock and are not pinned by the variable: the recovery heartbeat, and +the random seed PDF encryption draws on. **A PDF exported with a password therefore still differs +between runs** whatever `SOURCE_DATE_EPOCH` says, because that seed supplies its AES +initialisation vectors and its file `/ID`. Reproducible output means an unencrypted export. ### Parameter keys @@ -1079,10 +1102,17 @@ The id must name a selected top-level object. Layers, compound-path members and objects inside another selected object are not top-level objects. Any other id is an error naming that value, and the key is left unchanged. A null `id` is an error too. -A click with the Selection tool on a selected top-level object, while two or more objects are selected, runs `select.key {id}`, and a click on the key object again runs `select.key {}`. -On a single selected object, or on a group selected with only its own members, `select.key` sets no key. -It returns `{key}`, the key object's id or null. -`document.inspect` (the `inspect_document` tool) reports the key object as `key`, null without one. +A click with the Selection tool on a selected top-level object, while two or more objects are selected or ruler guides are selected with it, runs `select.key {id}`, and a click on the key object again runs `select.key {}`. +On a single selected object with no ruler guide selected, or on a group selected with only its own members, `select.key` sets no key. +With a key object (or a key guide), `object.align` moves the other selected ruler guides too: a vertical guide goes to the key's left edge, centre or right edge, a horizontal one to its top, centre or bottom (#2143). +Aligning to the selection or the artboard leaves guides where they are. +`select.key {guide}` makes a selected ruler guide (its `guide.list` index) the key instead, while one or more objects are selected (#2143). +`object.align` then lines the objects up on the guide and the guide stays put: a vertical guide sets where their left edges, centres or right edges go and vertical alignment leaves them where they are, a horizontal guide the other way round. +Selected anchor points align to it the same way. Distribute Spacing doesn't space from a key guide. +A click with the Selection tool on a guide selected with objects runs `select.key {guide}`, and a click on the key guide again runs `select.key {}`. +The key guide goes when it leaves the selection or no object is left selected, and an object key replaces it (and the other way round). +It returns `{key}`, the key object's id or null, with `guide`, the key guide's index, when a guide is the key. +`document.inspect` (the `inspect_document` tool) reports the key object as `key`, null without one, and the key guide as `keyGuide`. The `ui.pointer` and `pointer_gesture` replies list it as `key` beside `selection`. The command palette lists `select.key` as Cancel Key Object and runs it without an id. @@ -1233,6 +1263,12 @@ already walks Image Trace. Short agent entry points: and `livePaint.info` list the gaps up to `size` wide that no path closes, as `[x0, y0, x1, y1]`. `livePaint.merge` keeps the bottom group's options when its Gap Detection is on, and otherwise turns Gap Detection on with `small` when another merged group has it on. When Gap Detection is off in every merged group, it stays off. + The Live Paint Selection tool's options (`tool.setOption {tool: "livePaintSelection", values}`; double-clicking the + tool opens them, dialog `livePaintSelectionOptions`) are `selectFills` and `selectStrokes` (both on), `color` (the + highlight color, `#rrggbb` or a layer color's name; `#ff2a2a`) and `width` (the highlight's width, 1 to 20 screen + pixels; 4). With `selectStrokes` off, Alt-click selects the face under the pointer as a click does; with + `selectFills` off, a click selects the edge nearest the pointer as Alt-click does; with both off, a click selects + no face or edge. `dataset.select`, `dataset.next` and `dataset.prev` reply `{name, applied, skipped}`. They add `overflow: [id…]` when area type or type on a path whose text they rewrote doesn't fit, as `text.setText` does (see @@ -1254,6 +1290,12 @@ defined. Of two variables of the same kind on one object, the one defined last w {"name":"run_command","arguments":{"command":"command.batch","params":{"label":"Offset","commands":[{"command":"object.move","params":{"dx":10,"dy":10,"copy":true}}]}}} ``` +When no object is bound to a variable that the data set has a value for, for example after `dataset.import` defines +new variables without binding them, `dataset.select`, `dataset.next` and `dataset.prev` apply nothing and add +`warning`, which the app's status bar shows: "nothing in data set A was applied: no object is bound to a variable it +has a value for". A data set with a value for a bound variable gives no warning even when every object bound to it is +locked; `skipped` counts those objects. + `dataset.update {all?}` writes what the bound objects hold now into the active data set, for each variable that the data set holds. A variable whose objects report no value, because they are locked, inside a locked layer or group, or deleted, keeps the data set's value. With `all: true` it also adds every other variable that the @@ -1408,7 +1450,8 @@ group together. Groups and layers carry fills, strokes and effects of their own, as in the reference app: their fills and strokes paint every member's geometry, and their effects apply to the members as one piece (one combined drop shadow; a Transform or Warp moves or bends the whole group). Their Contents row (type: Characters) is a slot in the stack: -fills and strokes above it paint over the members (characters), those below under them; new items go above it. +fills and strokes above it paint over the members (characters), those below under them; new items go above it +(on an image, below it). `appearance.moveItem {"from": "contents", "to": n}` puts the row above the bottom `n` items, and an item move takes `contents` to say where the row ends up in the same undo step; `document.node` shows the slot as `appearance.contents_index`. The `appearance.*`, `effect.*` and `graphicStyle.apply` commands edit the selected @@ -1420,6 +1463,13 @@ A geometry effect on one of type's own fills or strokes (`effect.apply` with `it the fill or stroke paints, and SVG, PDF, EPS and the other vector exports write such type as paths. On type that holds inline graphics, those effects are drawn and exported only when the type has a geometry effect or perspective of its own. +An image's own fills and strokes draw only when they carry a visible Convert to Shape or Outline Object effect: Convert +to Shape sizes its shape from the image's box, Outline Object gives the image's frame, the effects after it reshape +that shape, and the effects before it are left out. Its Contents row stands for the image; `appearance.addFill` and +`appearance.addStroke` put a new item right below that row, so it paints under the image. SVG, PDF, EPS and the other +vector exports write those items as paths, and `effect.expandAppearance` turns them into objects in a group with the +image. +Use Preview Bounds measures an image by its frame. ```json {"name":"run_command","arguments":{"command":"appearance.addFill","params":{"ids":[7]}}} @@ -1541,9 +1591,13 @@ Items can be put in user-named groups, which the panel shows as collapsible sect search field filters every item by name; `library.get` lists them all to filter). `library.createGroup {library?, name?, items?: [{kind, item}]}` makes one (a name another group has, ignoring case, gets a number) with those items moved into it; `library.renameGroup {library?, group, name}` renames one; `library.deleteGroup {library?, group}` -deletes one, its items staying in the library ungrouped; and `library.moveItem {library?, kind, item, group?}` moves -an item into a group (without `group`, out of its group). An item is in one group at most; `library.get` lists the -groups as `groups: [{name, items: [{kind: "color"|"charStyle"|"paraStyle"|"graphic", item}]}]` (a graphic by its id). +deletes one, its items staying in the library ungrouped; and `library.moveItem {library?, kind, item, group?, before? +| after?}` moves an item into a group (without `group`, out of its group) and, with `before` or `after` (another item +of its kind), just before or after that item in the order its kind is listed and shown in. `library.moveGroup +{library?, group, to}` moves a group to place `to` of the list (0: first; past the end: last). Dragging items and +group headers in the panel runs these. An item is in one group at most; `library.get` lists the groups as `groups: +[{name, items: [{kind: "color"|"charStyle"|"paraStyle"|"graphic", item}]}]` (a graphic by its id), and each kind's +items in the order the panel shows them. `library.export {library?, path?}` writes a library (its colours, styles, graphics with their art and thumbnails, and its groups) as a `.vclibrary` file, the JSON the library folder keeps (without `path`: `{data}`, the file's text). @@ -1690,8 +1744,13 @@ and `layerRows`, the rows highlighted in the panel. - **Dialogs and panel state** (control channel and the app's MCP): `ui.layerOptions {ids?}` and `ui.newLayer {sublayer?}` open Layer Options (dialog `layerOptions`: name, color, template, locked, visible, printable, preview, dimImages, dimPercent; OK is one undo step), `ui.layersPanelOptions` opens Panel Options (`layersPanelOptions`: - layersOnly, rowSize small|medium|large|other, otherSize, thumbLayers, thumbGroups, thumbObjects), and + layersOnly, locateSelected, rowSize small|medium|large|other, otherSize, thumbLayers, thumbGroups, thumbObjects), and `ui.layersExpand {ids?, open?}` opens or closes rows as their triangles do (Alt-click: everything inside). + With `locateSelected` on (Locate Selected Objects, off by default), when the last selected object changes on the canvas + or by a command, the panel opens the layers and groups around it and scrolls to its row, as after `layer.locate`, but + does not highlight the row. When Show Layers Only, a search or the filter leaves the object without a row, the panel + opens no rows for it and scrolls as with the option off. A change made with the panel's own rows, buttons or menu is + not located, and a change made during a drag is located when the drag ends. A document opens with only its top-level layers open; the open rows are saved in the native file and reopen that way. - **Search and filter** (control channel and the app's MCP): the Search All field keeps the rows whose names hold the text typed, and `ui.layersFilter {objects?, layers?}` sets the choices of the Filter button beside it. `objects` (By @@ -1983,7 +2042,7 @@ path by its control points when one of them has an x or y that is infinite or la (about 1.1e307), so an edit that leaves such a path selected, `path.create` included, fails with "result would exceed the canvas (coordinates out of range)". `path.curvatureEdit`, `path.removeAnchor`, `path.convertAnchor`, `path.reshapeSegment`, `path.split`, -`path.setHandle` and `path.insertAnchor` edit subpath 0 when `subpath` is absent or null, and refuse a `subpath` that +`path.setHandle`, `path.moveAnchor` and `path.insertAnchor` edit subpath 0 when `subpath` is absent or null, and refuse a `subpath` that is not a whole number of 0 or more, such as 1.5, -1 or "1" ("missing integer `subpath`"); `path.split` refuses such an `anchor` or `segment` in the same way. The document does not change and no undo step is recorded. @@ -2004,6 +2063,23 @@ the path it had begun while that stays selected. Its reply's `tool` is the tool {"name":"run_command","arguments":{"command":"path.moveAnchors","params":{"dx":0,"dy":40}}} ``` +## Simplify + +`object.path.simplify` takes the amount as `tolerance` (points, 1 by default) or as the Simplify slider's `level`, a whole +number from 0 (the fewest anchor points) to 100 (the closest fit). Level 50 is a tolerance of 1 pt, and every 10 levels +halve or double it, so level 0 is 32 pt and level 100 is 1/32 pt. `auto: true` (Auto-Simplify) uses the lowest level +whose tolerance is at most 1/400 of the selection's longer side, or level 100 when that side is under 12.5 pt. With +`level` or `auto`, the reply also has the `level` used: + +```json +{"name":"run_command","arguments":{"command":"object.path.simplify","params":{"auto":true}}} +``` + +In the desktop app, Object › Path › Simplify opens the slider (`ui.menuDialog {command: "object.path.simplify"}`, +dialog `simplifySlider` with field `level`) and previews the result until `ui.dialog.confirm`. `ui.simplifyAuto` moves +the open slider to the Auto-Simplify level, and `ui.simplifyMoreOptions` opens the Simplify dialog at the slider's +tolerance. When OK confirms the dialog with `retain` ticked, the menu item opens the dialog on those settings next time. + ## Editing a path with the Curvature tool The Curvature tool edits any selected path, whatever drew it, keeping its shape except where edited (#798). Each edit @@ -2626,6 +2702,26 @@ value: true}`; the Control bar's and Properties' Scale Artwork with Artboard che Artboard) makes its handle drags proportional and passes `scaleArt`, as do Properties' and the Transform panel's artboard size fields while the tool is in use. +`artboard.setProps {artboards: [{index, name?, x?, y?, width?, height?}…], scaleArt?, moveArt?, …}` sets several +artboards in one undo step, each with its own fields; the other params apply to all of them. The art that moves or +scales with each artboard is the art inside it before any of them changes, and an object inside several of them goes +with the first one listed that moves or scales its art. An empty list and a list that names an artboard twice are +refused. + +With several artboards selected with the Artboard tool, the desktop app gives a new size to each of them in one such +call. Properties' W and H and the Transform panel's W and H do this, and so do Properties' Preset and orientation +buttons, the Control bar's preset, orientation, W and H, and a new Width or Height in Artboard Options. The W and H of +the Transform panel and the Control bar resize each artboard about its own reference point, and with the proportions +linked they keep each artboard's own proportions. Artboard Options resizes each artboard about the reference point its +form used for the new Width or Height. Properties' W and H and the preset and orientation buttons keep each artboard's +top-left corner. A preset sizes each artboard in its own orientation, and an orientation +swaps the width and height of each artboard that is not square and not already in it. A new X or Y moves the active +artboard only, and Artboard Options' Name renames only the artboard it shows. + +```json +{"name":"run_command","arguments":{"command":"artboard.setProps","params":{"artboards":[{"index":0,"width":300},{"index":2,"width":300}],"scaleArt":true}}} +``` + ```json {"name":"run_command","arguments":{"command":"artboard.copy","params":{"index":0}}} {"name":"run_command","arguments":{"command":"edit.paste","params":{}}} @@ -2826,7 +2922,8 @@ They are kept across restarts, in the desktop app and in `vectorcraft-cli` alike Besides SVG, Copy offers other apps PNG and PDF of the copied objects, and their text when they are all type. `clipboard.flavours` lists what Copy offers for the current clipboard, best first, by the Clipboard Handling -preferences: `text/plain` (the text of a type-only copy, else the SVG markup with `copyAsSvg`), `image/svg+xml` +preferences: `text/plain` (the text of a type-only copy, else the SVG markup with `copyAsSvg` when the images it +embeds total at most 1 MiB, so a paste never reads a photo back as text, #2213), `image/svg+xml` (`copyAsSvg`), `application/pdf` (`copyAsPdf`) and `image/png` (always; PDF and PNG need objects with an area). Each one has a query command: `clipboard.exportSvg`, `clipboard.exportText` (null unless every copied object is type), `clipboard.exportPdf` @@ -2836,9 +2933,12 @@ transparent around them). As in `document.export`, the PDF's and the PNG's repli shows the first note of the PDF and PNG it offers in the status bar. What other apps copied goes into the clipboard with `clipboard.importSvg`, `clipboard.importPdf {dataBase64, page?, -password?}` (the page's objects), `clipboard.importEps {dataBase64}` (an EPS or other PostScript picture's objects, -as `document.open` reads one), `clipboard.importImage {dataBase64, mime?}` (an embedded image at 100% of its -physical size) or `clipboard.importText {text}` (point text in the default type style), each centred on `center` +password?, editingData?}` (the page's objects; with `editingData: true` the data is a `.ai` or `.ait` file, and every +object of its editing data comes in as `document.open` reads it, each layer's objects in stacking order and a hidden +layer's objects hidden, or the page's objects when `document.open` would not use that copy), `clipboard.importEps +{dataBase64}` (an EPS or other PostScript picture's objects, as `document.open` reads one, a hidden layer's objects +hidden), `clipboard.importImage {dataBase64, mime?}` (an embedded image at 100% of its physical size) or +`clipboard.importText {text}` (point text in the default type style), each centred on `center` (default: the first artboard); then any `edit.paste*` command pastes it. The desktop app does this itself: Copy and Cut publish the formats to the system clipboard, and a Paste outside text editing first reads what another app copied (SVG, then PDF, then text, then a bitmap; SVG markup in text counts as SVG). A background thread makes the @@ -2850,7 +2950,9 @@ them. Windows carries every format both ways and pastes a bitmap from PNG, else from the device-independent bitmap screenshots copy (`CF_DIBV5`, then `CF_DIB`; alpha kept, opaque when it is zero throughout, at most 32768 px a side); macOS and Linux carry one format (the text, else the PNG) and paste text and bitmaps (macOS the pasteboard's PNG, else TIFF, as screenshots copy them). On the web Copy publishes SVG text, and -Paste takes SVG text and the pictures and files a paste carries (a screenshot pastes as an embedded image). +Paste takes SVG text and the pictures and files a paste carries (a screenshot pastes as an embedded image). A `.ai` +or `.ait` file that holds a PDF, copied in a file manager or carried by a paste, is loaded with `clipboard.importPdf +{editingData: true}`, and its objects go into the active layer. The `pasteTextFormatting` preference (`keep` or `plain`): with `plain`, text the Type tool copied pastes into type without its formatting, taking the style at the caret. @@ -3163,8 +3265,8 @@ or in `options` (`file.formatOptions {format}` lists them with their values): (default true) with false write blank pages around the native document (smaller; other apps show empty pages). - `.ai` only: `compress` (default true) is the PDF option `compression.compressText`. -File → Save As asks for these in the save options dialog (VectorCraft Options) after the save panel; Save, Save a Copy -and Save as Template reuse the options as last saved (or Use Compression). +File → Save As asks for these in the save options dialog (VectorCraft Options) after the save panel, and Save a Copy +does too for a `.ai` file; Save, Save a Copy to a native file and Save as Template reuse the options as last saved (or Use Compression). ```json {"name":"run_command","arguments":{"command":"file.saveAs","params":{"path":"/tmp/set.vectorcraft","separateArtboards":true,"range":"2-3","includeLinked":true}}} @@ -3910,7 +4012,10 @@ them again at startup (`plugin.remove` deletes them there): schema, defaults). An object filter runs on the selected paths and compound paths with `plugin.run {id, params}` (one undo step; it may change, delete or add objects, and the result is selected). A live-effect plug-in is an effect with id `plugin.`: `effect.apply`, `effect.setParams` and `effect.expandAppearance` work as for built-in effects, and -`effect.list` lists it. A failing plug-in returns an error and leaves the document as it was. +`effect.list` lists it. An exporter adds a write-only file format `plugin.` (listed by `document.formats`): +`document.export {format: "plugin.", params?, path?}` writes it, as does a `path` ending in one of its extensions +that no built-in format has. A failing plug-in returns an error and leaves the document as it was (an export writes +no file). ```json {"name":"run_command","arguments":{"command":"plugin.install","params":{"path":"/plugins/desaturate.wasm"}}} @@ -4264,6 +4369,35 @@ canvas as they export. `object.blend.expand` and `object.blend.release` keep the opacity mask and appearance (Release on a group around the keys and spine when the blend has any), and `object.expand` with `object: true` expands the blends in the selection. +## Objects on Path + +`object.objectsOnPath.attach {path?, ids?, pivot?, rotate?}` attaches the selected objects (or `ids`) to the path +`path`: the objects and the path go into an Objects on Path group, with the path at its bottom. The objects go along +the path in their order on the canvas, column by column from left to right and top to bottom in each column. The first +one sits on the path's first anchor, the last one sits on the end of an open path, and the others are spread evenly +between them by length; on a closed path the gaps run all the way round. The attachment point of each object (`pivot`, +0 to 8 row by row from the top left of its bounds without strokes; default 4, the center) sits on the path, and the +object is turned to the path's direction there. An object rotated by other than a multiple of 90° is first turned to +the nearest multiple. `rotate` tilts every object by that many degrees counter-clockwise. Without `path`, the command +chooses the Objects on Path tool (`objectsOnPath`), whose click on a path sends `{path}`. As the path, the command +refuses a guide, a compound path, type, a path without length and a path already in an Objects on Path group. As +objects, it refuses graphs, layers and objects already in an Objects on Path group. + +The group stays live: after every edit its objects go back on its path. Editing the path moves them, an object moved +on its own goes back to its place, an object moved into the group (`layer.move` with `place: "inside"`) joins the end +of the path, an object moved out of it leaves, and art that replaces an object (`symbol.breakLink`) keeps its place. +`object.objectsOnPath.options {ids?, pivot?, rotate?}` changes Pivot and Rotate, and +`object.objectsOnPath.expand {ids?}` makes the groups plain groups. Both act on the groups that `ids` names (Objects +on Path groups or objects in them), or on the groups of the selection when `ids` is not given. The native file keeps +the group with an `objects_on_path` record; SVG, PDF and the other exports write the path and the objects as plain +art. + +```json +{"name":"run_command","arguments":{"command":"object.objectsOnPath.attach","params":{"path":30,"ids":[12,15,18]}}} +{"name":"run_command","arguments":{"command":"object.objectsOnPath.options","params":{"pivot":7,"rotate":15}}} +{"name":"run_command","arguments":{"command":"object.objectsOnPath.expand","params":{}}} +``` + ## Paragraph composer `text.setFormat {ids?, composer: "singleLine"|"everyLine"}` sets how a text object's lines are broken (the Paragraph diff --git a/docs/plugins.md b/docs/plugins.md index 8a34dd7a9a..2d430b3e14 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -5,13 +5,16 @@ arbitrary machine code and cannot work in the browser build. Instead, plug-ins a run in a sandbox. One `.wasm` file works on macOS, Windows, Linux and the web. The design follows PhotoCraft's plug-in API (same sandbox, same manifest and parameter schema), extended for vector documents. -There are two kinds of plug-in: +There are three kinds of plug-in: - **Object filters** read the selected paths and compound paths (geometry, fills, strokes, gradients, opacity) and return the objects to keep, change or add. A run is one undo step. Use them for recolouring, path clean-up, halftones, generative patterns and the like. - **Live effects** rewrite one object's geometry each time it is drawn, from its appearance stack, like the built-in Distort & Transform effects. The art stays editable: move or reshape it and the effect follows. +- **Exporters** write the whole document in a file format of their own, for pen plotters, cutting machines, + laser cutters and the like. File › Export › Export As lists them after the built-in formats, and the host writes the + bytes they return: a plug-in still never touches a file. This page is the contract for plug-in authors and the reference for the host (`crates/plugins`, the `plugin.*` commands in `crates/engine/src/cmd/plugin.rs`). @@ -20,7 +23,7 @@ This page is the contract for plug-in authors and the reference for the host (`c | Command | Params | What it does | |---|---|---| -| `plugin.list` | `{}` | `{"plugins": [{id, name, version, kind, author, description, params, paramsSchema, effect?, size, source}], "folder": report}` | +| `plugin.list` | `{}` | `{"plugins": [{id, name, version, kind, author, description, params, paramsSchema, effect?, format?, extensions?, size, source}], "folder": report}` | | `plugin.info` | `{"id"}` | One plug-in: the `plugin.list` entry plus `manifest`, `defaults` and `lastError` (a live effect's last failure). | | `plugin.run` | `{"id", "params"?: {…}, "ids"?: [...]}` (plug-in params may also be top-level keys) | Runs an object filter on the selection (or `ids`). One undo step; the result is selected. | | `plugin.install` | `{"path": "/x/y.wasm"}` (desktop) or `{"dataBase64": "…", "name"?}`, `"replace": bool = true` | Validates and installs a module; returns its `plugin.list` entry. The desktop app and `vectorcraft-cli` keep it in the `Plug-ins` folder next to the preferences, so it is installed again after a restart (#2541). | @@ -30,12 +33,19 @@ This page is the contract for plug-in authors and the reference for the host (`c Live effects are applied like any effect: `effect.apply {"effect": "plugin.", "params": {…}}`, edited with `effect.setParams`, listed by `effect.list` (menu `Effect › Plug-ins`) and baked by Object › Expand Appearance. +An exporter adds a write-only format, `plugin.`, which `document.formats` lists with its `plugin` id. +`document.export {"format": "plugin.", "params"?: {…}, "path"?}` writes it, and so does a `path` ending in one of +its extensions that no built-in format has; `selectedOnly` hands it the selection, as for the built-in formats. + In the app, installed filters appear under **Object › Plug-ins**, next to **Install Plug-in…** and **Reload Plug-ins**; live effects under **Effect › Plug-ins** and in the Appearance panel's effect menu. A plug-in with -parameters gets a dialog generated from its schema (numbers, whole numbers, checkboxes, dropdowns) with a live -preview; without parameters it runs at once. Parameters too many for the window's height scroll inside the dialog, -which keeps its heading and buttons in view. **File › Open** of a `.wasm` file installs it too (on the web this is -how plug-ins get in). +parameters gets a dialog generated from its schema (numbers, whole numbers, checkboxes, dropdowns, text and lists +of numbers, labelled, explained and sorted into sections as its manifest says) with a live preview; without +parameters it runs at once. Parameters too many for the window's height scroll inside the dialog, which keeps its +heading and buttons in view. Exporters are formats of **File › Export › Export As**, where Use +Artboards is greyed out (the plug-in writes the whole document); one with parameters asks for them in a dialog of the +same kind once the file is picked, and its Export button writes the file. **File › Open** of a `.wasm` file installs +a plug-in too (on the web this is how plug-ins get in). **Preference folder.** Edit › Preferences › Performance & Storage › *Additional Plug-ins Folder*: when set, every `*.wasm` in that folder (not recursive) is installed at startup and whenever the preference changes (desktop builds; @@ -57,11 +67,14 @@ The host is [`wasmi`](https://github.com/wasmi-labs/wasmi), a pure-Rust WebAssem | Module size | 32 MiB | rejected | | Linear memory | 512 MiB per instance (input and parameters: at most half) | `memory.grow` returns -1; oversized input or initial memory fails | | Output | 64 MiB of JSON | `Limit("output size")` | -| Instructions (fuel) | 50 M per call + 4,000 per input byte for `vc_run` | `Limit("instruction budget")` | -| Wall clock | 60 s per filter run, 5 s per live-effect run (desktop; checked every 20 M instructions) | `Limit("time budget")` | +| Instructions (fuel) | 50 M per call + 4,000 per input byte for `vc_run`; an export 10 G + 4,000 per byte | `Limit("instruction budget")` | +| Wall clock | 60 s per filter run, 5 s per live-effect run, 300 s per export (desktop; checked every 20 M instructions) | `Limit("time budget")` | | Call depth | 1,024 frames | trap | | Module shape | wasmi's strict limits (≤ 10,000 functions, 1 memory, …) | rejected | +An export runs where the export runs: with Background Export on, on the export's worker, whose Cancel stops the +plug-in between two of those 20 M-instruction slices; nothing is written then. + Every run gets a **fresh instance**, so no state survives between calls. Traps, exhausted budgets, malformed modules, bad manifests, out-of-range pointers, negative return codes and invalid output all become errors, and the document is left untouched: a filter's output is checked completely before one edit applies it. A live effect that @@ -99,21 +112,48 @@ pointers are offsets into the module's memory. "author": "Example", "description": "What it does.", "params": { - "amount": {"type": "number", "min": 0, "max": 100, "default": 50}, - "steps": {"type": "int", "min": 1, "max": 16, "default": 4}, + "amount": {"type": "number", "min": 0, "max": 100, "default": 50, "unit": "%"}, + "steps": {"type": "int", "min": 1, "max": 16, "default": 4, "label": "Steps per curve"}, "closed": {"type": "bool", "default": false}, - "mode": {"type": "choice", "options": ["soft", "hard"], "default": "soft"} + "mode": {"type": "choice", "options": ["soft", "hard"], "default": "soft", + "help": "Soft keeps the corners round; hard keeps them sharp."} } } ``` - `id`: 1–64 characters from `A-Z a-z 0-9 . _ -` (reverse-DNS recommended). Installing a module with the same id replaces the old one. A live effect's effect id is `plugin.`. -- `name`: the menu label (1–64 printable characters). `kind`: `"filter"` (object filter) or `"effect"` (live effect). +- `name`: the menu label, or an exporter's format name in Export As (1–64 printable characters). `kind`: `"filter"` + (object filter), `"effect"` (live effect) or `"exporter"`. Exporters came after the first ABI v1 hosts, which refuse + the kind when the plug-in is installed. +- `extensions` (exporters only, and required): 1–8 file extensions, lower-case letters and digits without the dot + (`["plt"]`); the first is the one Export As gives the file. A built-in format keeps an extension both list (`svg`): + `document.export` then writes the exporter's format only when asked for by its format id. - `params`: in dialog order. Names are `[A-Za-z0-9_]`, not starting with `_`, and not `id`, `ids`, `params` or `preview`. The host validates the user's values before calling: missing values take the default, numbers are clamped to `min..max` (ints rounded), a wrong type or an unknown choice is an error. Numeric defaults - are also clamped to their range, including the implicit zero default of an `int` parameter. + are also clamped to their range, including the implicit zero default of an `int` parameter. Besides `number`, + `int`, `bool` and `choice` there are `string` (`{"type": "string", "default": "", "maxLength": 256}`: a text field; + longer text is cut to `maxLength`, at most 4,096 characters) and `numberList` (`{"type": "numberList", "min": 0, + "max": 360, "default": [45, 135], "minItems": 1, "maxItems": 16}`: numbers typed separated by commas or spaces, + each clamped to `min..max`; a list of too few or too many is an error, and `maxItems` is at most 256). A plug-in + declares up to 256 parameters, at most 64 of them outside groups. + +Each parameter may also say how dialogs show it. Hosts from before these keys ignore them, so a plug-in that +declares them still installs there: + +| Key | What the dialog does with it | +|---|---| +| `label` | Labels the field (1–64 characters). Without one, the label is the name spaced out (`rowSpacing` → Row Spacing). | +| `unit` | Shows the unit the value is in after it (1–16 characters, such as `mm` or `°`). Nothing is converted: the plug-in gets the number as typed. | +| `group` | Puts the parameter in a section that folds (1–64 characters). Parameters outside any group come first, then each group in the order it first appears. | +| `help` | Shows what the parameter does when the pointer rests on its label (1–1,000 characters; line breaks allowed). | +| `helpUrl` | Opens this `https://` page (at most 512 bytes) from a button after the field. | +| `visibleWhen` | `{"pattern": ["lines", "crosshatch"], "outline": [true]}` shows the parameter only while each parameter it names (a checkbox or a choice declared before it) has one of the values listed and is shown itself. | + +A hidden parameter still goes to the plug-in with its value: what the dialog showed never changes a run. The +filter, live-effect and exporter dialogs use all of these keys. The Appearance panel's editor of a plug-in effect's +parameters uses `label`, `unit`, `help` and `visibleWhen`, and lists the parameters without sections or help buttons. ### Input @@ -121,7 +161,15 @@ pointers are offsets into the module's memory. order (bottom first): the selected ones and those inside selected groups and layers; hidden, locked, guide and clipping paths are left out, and so are other kinds of object (type, images, symbols, live blends…), which a filter never touches. With nothing selected the list is empty (a generator then adds its own objects). A live effect gets one -object, holding only geometry (`type`, `path`, `fillRule`, `bounds`). +object: its geometry (`type`, `path`, `fillRule`, `bounds`) and its `fills` and `strokes`, as a filter gets them (hosts +from before these give geometry only). The paints are read only: an effect may draw as wide as a stroke or use a +fill's colour to decide its shape, but it changes only the geometry. + +An **exporter** gets something else: the document as a native `.vectorcraft` file's JSON, as `document.save` writes it +but without indentation (the format is documented in [`crates/format/src/lib.rs`](../crates/format/src/lib.rs)). That is every layer, object, +appearance and effect record, artboard, swatch and symbol, so an exporter reads whatever the document holds; it checks +`version`, since a later host may write a newer one. Images of 8 KiB or more are listed in `images` with their MIME +type and `blob` but without their data, which follows the JSON in a saved file; smaller ones keep their base64 `data`. ```json {"objects": [ @@ -161,9 +209,13 @@ object, holding only geometry (`type`, `path`, `fillRule`, `bounds`). "_context": {"mode": "filter", "bounds": [10, 0, 75, 60], "artboard": [0, 0, 612, 792]}} ``` -`mode` is `"filter"` or `"effect"`; `bounds` the selection's geometric bounds (a live effect: the reference box of the -effect, the object's bounds or those of the previous effect's result); `artboard` (filters) the artboard under the -selection's centre, else the first. +`mode` is `"filter"`, `"effect"` or `"export"`; `bounds` the selection's geometric bounds (a live effect: the reference +box of the effect, the object's bounds or those of the previous effect's result); `artboard` (filters) the artboard +under the selection's centre, else the first. A live effect's `item` says where it sits: `"object"` (one of the +object's effects), or `{"fill": i}` / `{"stroke": i}` (in the own effects of the object's `i`th fill or stroke, +counted from the bottom as in `fills` and `strokes`). An export's `_context` is `{"mode": "export", "extension": "plt", +"name": "Poster"}` instead: the extension of the file being written (one the exporter lists) and its name without the +extension (the document's name when the export is not given a path), which some formats keep in their header. ### Output @@ -189,6 +241,10 @@ keeps its swatch link; any other paint is unlinked. For a **live effect**, the geometry of every returned object's `path` (their subpaths, in order) replaces the object's; the rest is ignored (the object keeps its own appearance). An empty list removes the geometry. +An **exporter** returns `{"dataBase64": "…", "warnings"?: ["…"]}`: the file, in base64, which the host writes as it +is, and what the export left out or changed, for the user (at most 100 warnings of at most 500 characters each, shown +with the export's own). A decline (`{"error": …}`), a missing `dataBase64` or data that isn't base64 writes nothing. + ## Writing a plug-in in Rust [`crates/plugins/example`](../crates/plugins/example) is a complete object filter, **Desaturate**: it moves every @@ -204,18 +260,22 @@ The script also refreshes `crates/plugins/tests/fixtures/desaturate.wasm`, the t The crate is not a workspace member. Any language that targets core WebAssembly works (C, Zig, AssemblyScript, WAT…), as long as the module has no imports: in Rust, `std` on `wasm32-unknown-unknown` is fine as long as it never touches WASI. `vectorcraft_plugins::wat::module` is the skeleton of a plug-in in WebAssembly text, which the tests -build their plug-ins from. +build their plug-ins from; `wat::echo_exporter` is an exporter whose file is its input or its parameters (with a +base64 encoder written out in WebAssembly text), which the tests read back what the host hands a plug-in with, and +`wat::when_given` a plug-in whose output depends on whether its input or parameters hold a given text, which shows in a +live effect's geometry. ## Performance The interpreter costs roughly 10–100× native speed per instruction. Filters handle a selection in one call, so a plug-in that parses and writes JSON with `serde_json` takes milliseconds for hundreds of paths. Live effects run once -per change of their input (results are cached), not per frame. +per change of their input, parameters or paints (results are cached), not per frame. ## Not in v1 - Tool plug-ins (pointer events on the canvas, a guide line or rectangle, geometry back), panel plug-ins, host - callbacks (progress, cancel), plug-in file formats. + callbacks (a plug-in reporting progress or asking whether it was cancelled), importers (plug-in formats that open + files). - Live effects that change paint (they reshape geometry; an object filter recolours), and filters on type, images or symbols. - Apply Last Effect and Last Effect work for plug-in effects; there is no "last filter" for object filters yet. diff --git a/docs/print-tiling.md b/docs/print-tiling.md new file mode 100644 index 0000000000..fabb037904 --- /dev/null +++ b/docs/print-tiling.md @@ -0,0 +1,125 @@ +# Print a large poster across multiple pages + +## Overview + +Use tiled printing to spread a large poster, sign or sewing pattern across several sheets of A4, +Letter or other paper. VectorCraft divides the drawing into numbered tiles at the scale you choose. +Overlap repeats part of the drawing on adjacent sheets to help you align them after printing. + +## Print a poster on multiple sheets + +1. Open your drawing in VectorCraft. For a full-size pattern, check that the drawing has the intended + dimensions before printing. +2. Choose **File → Print…** to open VectorCraft's **Print** dialog. In **Printer**, select your printer + or **PDF File** to save the tiled job as a PDF. +3. In **General**, under **Artboards**, choose **All** or **Range:** to select the artboards to print. + For example, use **Range:** `1` for the first artboard. Choose **Ignore Artboards (all the art as + one page)** only if you want to tile the bounds of all the artwork instead of individual artboards. +4. Under **Media**, set **Size** to the paper loaded in the printer, such as **A4** or **Letter**. + Choose **Custom** to enter **Width** and **Height**. **Auto-Rotate (turn the paper to each artboard)** + is on by default; turn it off to choose a fixed **Orientation**, such as **Portrait** or **Landscape**. +5. In **Advanced**, set **Unprintable margin** to allow for the edges your printer cannot print. + VectorCraft uses one value for all four edges; use a value that covers the printer's largest + required margin. The default is zero, and VectorCraft does not read this value from the printer. +6. Return to **General**. Under **Options**, set **Scaling** to **Tile Imageable Areas** or + **Tile Full Pages** (see [Choose a tiling mode](#choose-a-tiling-mode)). Set **Scale**, both **W** + and **H**, to `100%` to keep the drawing's size. Use the same percentage in both fields to keep + its proportions; larger percentages enlarge the drawing and can require more sheets. +7. Set **Overlap** to repeat a strip along adjoining tiles. For example, `10 mm` gives room for + alignment. Length fields accept units such as `mm` and `in`. Overlap must be less than half + the smaller tile dimension; increasing it can increase the sheet count. +8. Leave **Tile Range** empty initially. Use the **Previous page** and **Next page** arrows beneath + the preview to inspect each sheet. The label identifies its artboard and tile; the preview also + shows the paper size and scale. Check **Summary** for warnings or invalid settings. +9. Keep **Tile Range** empty to print every tile, or enter a range such as `1-3, 5` to print a subset. + Check the preview again after changing the range. +10. Click **Print**. With a printer selected, VectorCraft sends the laid-out job to the system's print + service. With **PDF File** selected, it asks where to save the PDF, with one page per printed + tile for each copy in composite output. **Done** keeps the print settings with the document + without printing; save the document to retain them for next time. + +The tiling controls belong to VectorCraft's **Print** dialog on Windows, macOS and Linux. +**Setup…**, beside **Printer**, opens the system's printer settings, whose interface varies by +platform. Set tiling in VectorCraft's **Scaling** list. Keep the printer's paper settings consistent +with **Media**. In the web app, printing goes through the browser's print dialog; **PDF File** +downloads the PDF. + +For a paper proof, select **PDF File** and click **Print**, then open the saved PDF to inspect its +pages before sending it to a printer. When printing that PDF, keep its page size and scale rather +than applying another fit-to-page reduction. For a sewing pattern, measure a known length on a +printed sheet before printing the full job. + +## Choose a tiling mode + +| Scaling | How it divides the drawing | When to use it | +|---|---|---| +| **Tile Full Pages** | Each tile uses the full paper width and height. Adjacent tiles advance by that size minus **Overlap**. | Use when you need a grid based on whole sheets, such as with a printer that supports the required borderless paper setting. On a printer with unprintable edges, artwork near tile edges can be lost unless sufficient overlap covers those gaps. | +| **Tile Imageable Areas** | Each tile uses the paper area inside **Unprintable margin**. Adjacent tiles advance by that smaller size minus **Overlap**. | Use for printers with unprintable edges. Set the margin in **Advanced** so the tiles account for those edges; this can require more sheets than full-page tiling. | + +With **Unprintable margin** set to zero, the two modes use the same tile dimensions. Neither mode +makes a printer capable of borderless printing. **Fit to Page** scales an artboard onto a single +sheet; choose a tile mode to keep a large drawing spread across sheets. + +## Check the layout on the canvas + +1. Set up tiling in **File → Print…**, then click **Done** to keep the settings. +2. Choose **View → Show Print Tiling**. The canvas shows each sheet's paper edge and a dashed, + numbered imageable area. Tiles excluded by **Tile Range** appear dimmer. The overlay uses the + saved print settings; it does not print anything. +3. Select the **Print Tiling Tool**. In the default toolbar, press and hold the **Hand Tool** button + in the **Navigate** group to open its tool list, then choose **Print Tiling Tool**. The tool also + shows the overlay while it is active. +4. Drag on the canvas to position the grid. The pointer places the top-left corner of a page's + imageable area and snaps near artboard edges. Tiles extend left and up as needed to cover the + drawing, so that page may not be tile 1 after the move. Reopen **File → Print…** to check the + resulting pages and tile numbers. Dragging the dialog's preview does not reposition tiled pages. + +To restore the default grid position, double-click on the canvas with **Print Tiling Tool** active, +or double-click the tool's toolbar button. Alternatively, reopen **File → Print…** and click +**Reset** beneath **Placement** when the dialog says **The Print Tiling tool placed the pages.** +Click **Done** to keep that change. **View → Hide Print Tiling** hides the overlay after switching +to another tool. + +## Print only selected tiles + +**Tile Range** uses numbers starting at 1, across each row from left to right, then down. +For a grid with three columns and two rows, the first row is `1, 2, 3` and the second is `4, 5, 6`. +Enter `2, 5` to print the middle column, or `1-3, 5` to print the first row and tile 5. +Leave the field empty to print all tiles. + +**Range:** under **Artboards** selects drawings; **Tile Range** selects sheets within each chosen +drawing. Tile numbering restarts for each artboard, and the same tile range applies to each one. +To reprint one damaged sheet of one artboard, select that artboard with **Range:** and its tile +with **Tile Range**. A tile number must exist on every selected artboard. Changing paper, scale, +margin, overlap or grid position can change the grid and its numbering; check again before reprinting. + +## Assemble the printed sheets + +Lay out the sheets in tile order. Align repeated artwork in the overlap, trim unprinted edges as +needed, and tape or glue the sheets together. Print a pair of adjacent tiles first to check the +scale, margins and overlap before committing to a large job. + +## Troubleshooting + +- **The preview shows only one page.** It displays one sheet at a time. Use the arrows and check + the count beneath it. If the count is one, check **Tile Range**, the chosen artboards, paper size + and scale: the drawing may fit on one tile. +- **The image shrinks to one sheet.** Change **Scaling** from **Fit to Page** to a tile mode and + check both scale percentages. Also check for another fit-to-page setting when printing a saved PDF. +- **Artwork is missing along sheet edges.** Check the printer's unprintable margins. Use + **Tile Imageable Areas** with a suitable **Advanced → Unprintable margin**, or allow enough + overlap in full-page tiling to cover the missing edges. Check that the physical paper matches + **Media**; a zero margin does not remove a printer's hardware limits. +- **No tiling boundaries appear on the canvas.** Keep the settings with **Done**, then enable + **View → Show Print Tiling** or select **Print Tiling Tool**. If the settings are invalid, the + overlay has no pages to draw; reopen **Print** and check **Summary**. +- **The job has the wrong number of pages.** Check **Artboards**, **Tile Range**, **Copies** and + **Skip Blank Artboards**. Paper size, orientation, scale, margins and overlap affect the grid. + Under **Output**, **Mode → Separations** produces a page per enabled ink; use **Composite** for + an ordinary poster. The dialog preview shows one copy; the saved PDF includes all copies. + +## Related documentation + +- [Printing and PDF file output](mcp.md#printing) — command reference. +- [Print tiling](mcp.md#print-tiling) — overlay and positioning command reference. +- [Print settings](mcp.md#print) — paper, scaling and output settings reference. diff --git a/docs/releasing.md b/docs/releasing.md index 6c3400908a..f3bcac6572 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -159,6 +159,13 @@ to the target triple, so host build scripts aren't affected. `.tar.gz` tree (`bin/`, `share/`). The packages install both programs, the desktop entry, the AppStream metainfo, the MIME type for VectorCraft documents, the icons and the licence files. +**Document types.** The desktop entry's `MimeType` lists every format File › Open reads but PSD, +PSB, `.ps` PostScript and Targa, so file managers list VectorCraft under Open With for them. +`ai.storyteller.vectorcraft.mime.xml` declares the types that shared-mime-info lacks: VectorCraft +documents and templates, `.ait` templates and Affinity files (`application/x-affinity`). An `.af` +file gets the Affinity type by its content, and `.afdesign` and `.afpub` files by their extension. +A test keeps both files in step with the engine's `OPEN_EXTS`. + The jobs run on `ubuntu-22.04`, the oldest GitHub-hosted image, so the binaries only need glibc 2.35 or newer: Ubuntu 22.04+, Debian 12+, Fedora 36+ and RHEL 10. Moving the job to a newer image raises that floor, so do it deliberately. After packaging, the job prints the `.deb`'s diff --git a/docs/roadmap.md b/docs/roadmap.md index afa338ca48..2e915f21f5 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-18 · **Change:** minor (interactive Mirror Repeat axis; bounding-box handles take priority over the axis body while the center and end handles retain their move and rotation actions; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; Blend spine Anchor Point conversions, selection/stacking priority and Shift regression coverage (#2544); scores and hours unchanged; Image Trace: Auto Color keeps rare but distinct colours; Image Trace: large images trace with a warning; anchor limit raised to 8,000,000; Image Trace: Raster::new returns an error for a buffer of the wrong length; M12 graph pruning and junction merging measured; M12 exact crop EDT and Guo–Hall thinning measured; M12 centre-lines baseline measured; scores and hours unchanged; Image Trace: a higher Paths never gives fewer segments on collapsed loops; Image Trace: the notch rule reads only its own piece; Image Trace: an edge's sub-pixel shift is the same from either side; Image Trace: a simpler contour walk with no precomputed direction table; transparency grid visibility saved in native documents, #1968; EPS editing data: legacy mesh corners, vector opacity masks and compound member paint retained; raster page comparison filters minification without relaxing limits; scores and hours unchanged; correction: M12's Image Trace quick presets leave the panel as it was, the Image Trace button opens it; batch exporting, #1935; G2: Effect › Sketch › Halftone Pattern; Photoshop filters 30/57, 27 remaining (22–38 h); Warp Options controls verified by focused checks and original-image review; estimates unchanged; existing-guide Escape cancellation validated 2026-10-14; scores and hours unchanged; open-path anchor Delete keeps surviving runs separate; estimates unchanged; PDF.R1: shared PDF reader with windowed content scanning and explicit incomplete-content errors; scores and estimates unchanged; PDF.W1: guarded shared PDF writer; output behavior, scores and estimates unchanged; Artboard tab-switch follow-up historically validated on `a0671777`; scores and hours unchanged; Artboard clean active-tab close/Delete follow-up validated 2026-10-15; later 2026-10-14 merges: per-corner radius, #1682; Width Point Edit from the Width tool, #1814, #1630; guides, #1782, #1836; anchor X/Y/W/H, #1824; toolbar and All Tools, #1751; macOS save sheets, #1855; rendering caches, #1667–#1792; untrusted files, #1852, #1862–#1873; failed-save dialog, #1685; Dim Images, #1683; estimates unchanged; M12 row: Image Trace's enhanced presets; verified PngSuite downloads, #1729; synthetic control-input budgets, #1709; 2026-10-14 merges: anchor Align and Distribute, #1636; Direct Selection and Delete fixes, #1674, #1666, #1743; Expand on repeats, #1756; file and input hardening, #1776–#1783, #1786, #1807; MCP limits and envelope, #1727, #1728; Image Trace #1647, #1657; estimates unchanged; later 2026-10-13 merges: SVG import, #1565, #1596, #1568, #1601; Warp Arc, #1578; Pathfinder strokes, #1570; saves, #1620 in part; OpenType features, #1607; intersect Smart Guides, #1602 in part; estimates unchanged; TIFF is available in Export for Screens and Asset Export with shared format settings; scores and hours unchanged; G1/M11: Artboard deletion and history selection normalization; history regressions and full workspace CI pass; scores and hours unchanged; Character styles retain explicit Auto leading, propagate resets and preserve local leading overrides; scores and hours unchanged; Width Point Edit: Shift-double-click enables adjoining adjustment; plain double-click keeps it off; scores and hours unchanged; per-corner radius fields with a link toggle, split from #1594; control transport deadlines, #1726; M12 row: Image Trace's presets and options as they are now; Polish interface, #1498; compact native saves, #1492; PDF and EPS paste as vector art, #1499; import fixes, #1528, #1530, #1531, #1544, #1551, #1553; guide objects, #1534; Join after Average, #1533; Keyboard Shortcuts, #1539; estimates unchanged; Direct Selection anchor precedence, #1508; dialog slider rails, #1483; template layers in Outline view, #1486; type that does not fit its frame is reported, #1471; 3D on outlined type, #1481; print-size images, #1517; French catalog, #1511; estimates unchanged; Split Into Grid options, #1462; Transform Objects and Reflect's angle, #1448 and #1460; Pathfinder on a group, #1450; unknown parameter keys refused, #1442; grayscale TIFFs with alpha, #1466 in part; estimates unchanged; M9: Extrude & Bevel, Inflate and Rotate; `.ai` compound path paint, #1410, overprint on import, #1388, text-only PDF parts, #1387; Transform dialogs preview, #1412, and transforms of direct-selected anchors, #1408; strokes wider than their shape, #1396; estimates unchanged; `.ai` editing-data follow-ups, #1390, #1391, #1392; dialog keyboard focus, #1367 and #1395; symbol instance redraw cache, #1386; font rescan, #1376; estimates unchanged; gradient shapes import as paths, #1304; white constant alpha masks, #1286 in part; Live Corners widget click, #1239; custom ruler origin, #1212; M11: Artboard object clicks create a fitted artboard (#1227); estimate unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; DXF control-point SPLINE closure read, #1299 follow-up; desktop print transport adopts craft-print, Windows 7 fallback retained, scores unchanged; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; M6: Simplify preview/counts and valid topology selection (#1272); estimates unchanged; G2: Film Grain added; Photoshop effects 29/57; 28 filters remain; M14: RPM runtime metadata (#1275); estimates unchanged; M5: squared-distance texture redraws (#1257); clean-machine/platform drag measurements still pending; estimates unchanged; M2: Curvature point display improved (#1236, in part); estimates unchanged; M7: full-name font matching (#1258); Windows font-service QA pending; estimates unchanged; M1: no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); estimates unchanged; M14: dedicated Eyedropper cursor (#1269); estimates unchanged; M3: Eyedropper reads visible locked and outside-isolation sources (#1251); estimates unchanged; M2: Direct Selection segment picks and Delete (#1278); estimates unchanged; M3: adding paint to an unpainted zero-width stroke restores 1 pt (#1253); estimates unchanged; M12: graph designs, graph data, Graph Type and label options; M14: native macOS save Format menu, #866; M6: compound appearance and member fill-rule fixes, #1197; estimates unchanged; M9: PDF raster-effect cap warnings; G11: #893 fixed, #937 open; M7: accurate character controls after scaling, #1034; estimates unchanged; MCP `add_text` exposes the existing `vertical` option for point, area and path type; horizontal remains the default; scores and hours unchanged; Vertical fullwidth question and exclamation marks keep their nominal glyph upright when the font has no vertical alternate; scores and hours unchanged.; M2: Curvature curve geometry, #1236 in part; Width-point finite-arithmetic follow-up validated; scores and hours unchanged; Image Trace adjustment discovery; legacy `.ai` of version 7 saved, #868; estimates unchanged; Revolve: automatic smooth shading and default-on Cap with continuous rims; PDF.R1: shared PDF reader with windowed content scanning and explicit incomplete-content errors; scores and estimates unchanged; PDF.W1: guarded shared PDF writer; output behavior, scores and estimates unchanged; later 2026-10-14 merges: per-corner radius, #1682; Width Point Edit from the Width tool, #1814, #1630; guides, #1782, #1836; anchor X/Y/W/H, #1824; toolbar and All Tools, #1751; macOS save sheets, #1855; rendering caches, #1667–#1792; untrusted files, #1852, #1862–#1873; failed-save dialog, #1685; Dim Images, #1683; estimates unchanged; M12 row: Image Trace's enhanced presets; verified PngSuite downloads, #1729; synthetic control-input budgets, #1709; 2026-10-14 merges: anchor Align and Distribute, #1636; Direct Selection and Delete fixes, #1674, #1666, #1743; Expand on repeats, #1756; file and input hardening, #1776–#1783, #1786, #1807; MCP limits and envelope, #1727, #1728; Image Trace #1647, #1657; estimates unchanged; later 2026-10-13 merges: SVG import, #1565, #1596, #1568, #1601; Warp Arc, #1578; Pathfinder strokes, #1570; saves, #1620 in part; OpenType features, #1607; intersect Smart Guides, #1602 in part; estimates unchanged; TIFF is available in Export for Screens and Asset Export with shared format settings; scores and hours unchanged; G1/M11: Artboard deletion and history selection normalization; history regressions and full workspace CI pass; scores and hours unchanged; Character styles retain explicit Auto leading, propagate resets and preserve local leading overrides; scores and hours unchanged; Width Point Edit: Shift-double-click enables adjoining adjustment; plain double-click keeps it off; scores and hours unchanged; per-corner radius fields with a link toggle, split from #1594; control transport deadlines, #1726; M12 row: Image Trace's presets and options as they are now; Polish interface, #1498; compact native saves, #1492; PDF and EPS paste as vector art, #1499; import fixes, #1528, #1530, #1531, #1544, #1551, #1553; guide objects, #1534; Join after Average, #1533; Keyboard Shortcuts, #1539; estimates unchanged; Direct Selection anchor precedence, #1508; dialog slider rails, #1483; template layers in Outline view, #1486; type that does not fit its frame is reported, #1471; 3D on outlined type, #1481; print-size images, #1517; French catalog, #1511; estimates unchanged; Split Into Grid options, #1462; Transform Objects and Reflect's angle, #1448 and #1460; Pathfinder on a group, #1450; unknown parameter keys refused, #1442; grayscale TIFFs with alpha, #1466 in part; estimates unchanged; M9: Extrude & Bevel, Inflate and Rotate; `.ai` compound path paint, #1410, overprint on import, #1388, text-only PDF parts, #1387; Transform dialogs preview, #1412, and transforms of direct-selected anchors, #1408; strokes wider than their shape, #1396; estimates unchanged; `.ai` editing-data follow-ups, #1390, #1391, #1392; dialog keyboard focus, #1367 and #1395; symbol instance redraw cache, #1386; font rescan, #1376; estimates unchanged; gradient shapes import as paths, #1304; white constant alpha masks, #1286 in part; Live Corners widget click, #1239; custom ruler origin, #1212; M11: Artboard object clicks create a fitted artboard (#1227); estimate unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; DXF control-point SPLINE closure read, #1299 follow-up; desktop print transport adopts craft-print, Windows 7 fallback retained, scores unchanged; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; M6: Simplify preview/counts and valid topology selection (#1272); estimates unchanged; G2: Film Grain added; Photoshop effects 29/57; 28 filters remain; M14: RPM runtime metadata (#1275); estimates unchanged; M5: squared-distance texture redraws (#1257); clean-machine/platform drag measurements still pending; estimates unchanged; M2: Curvature point display improved (#1236, in part); estimates unchanged; M7: full-name font matching (#1258); Windows font-service QA pending; estimates unchanged; M1: no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); estimates unchanged; M14: dedicated Eyedropper cursor (#1269); estimates unchanged; M3: Eyedropper reads visible locked and outside-isolation sources (#1251); estimates unchanged; M2: Direct Selection segment picks and Delete (#1278); estimates unchanged; M3: adding paint to an unpainted zero-width stroke restores 1 pt (#1253); estimates unchanged; M12: graph designs, graph data, Graph Type and label options; M14: native macOS save Format menu, #866; M6: compound appearance and member fill-rule fixes, #1197; estimates unchanged; M9: PDF raster-effect cap warnings; G11: #893 fixed, #937 open; M7: accurate character controls after scaling, #1034; estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-20 · **Change:** minor (G2: Effect › Artistic › Smudge Stick, Sponge and Watercolor; Sketch › Bas Relief, Charcoal, Photocopy and Stamp, #2533; Photoshop filters 45/57, 12 remaining (8–14 h); interactive Mirror Repeat axis; bounding-box handles take priority over the axis body while the center and end handles retain their move and rotation actions; status-readout sample widths cached by language, document unit and pixels per point; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; DXF circular cubic paths export as native CIRCLE/ARC with R12 weighted strokes kept as POLYLINE and closing-chord safeguards (#1299); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; cached canvas reprojection preserves scale during resize, rotation and DPI changes; interactive Mirror Repeat axis; bounding-box handles take priority over the axis body while the center and end handles retain their move and rotation actions; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; Blend spine Anchor Point conversions, selection/stacking priority and Shift regression coverage (#2544); scores and hours unchanged; Image Trace: Auto Color keeps rare but distinct colours; Image Trace: large images trace with a warning; anchor limit raised to 8,000,000; Image Trace: Raster::new returns an error for a buffer of the wrong length; M12 graph pruning and junction merging measured; M12 exact crop EDT and Guo–Hall thinning measured; M12 centre-lines baseline measured; scores and hours unchanged; Image Trace: a higher Paths never gives fewer segments on collapsed loops; Image Trace: the notch rule reads only its own piece; Image Trace: an edge's sub-pixel shift is the same from either side; Image Trace: a simpler contour walk with no precomputed direction table; transparency grid visibility saved in native documents, #1968; EPS editing data: legacy mesh corners, vector opacity masks and compound member paint retained; raster page comparison filters minification without relaxing limits; scores and hours unchanged; correction: M12's Image Trace quick presets leave the panel as it was, the Image Trace button opens it; batch exporting, #1935; G2: Effect › Sketch › Halftone Pattern; Photoshop filters 45/57, 12 remaining (8–14 h); Warp Options controls verified by focused checks and original-image review; estimates unchanged; existing-guide Escape cancellation validated 2026-10-14; scores and hours unchanged; open-path anchor Delete keeps surviving runs separate; estimates unchanged; PDF.R1: shared PDF reader with windowed content scanning and explicit incomplete-content errors; scores and estimates unchanged; PDF.W1: guarded shared PDF writer; output behavior, scores and estimates unchanged; Artboard tab-switch follow-up historically validated on `a0671777`; scores and hours unchanged; Artboard clean active-tab close/Delete follow-up validated 2026-10-15; later 2026-10-14 merges: per-corner radius, #1682; Width Point Edit from the Width tool, #1814, #1630; guides, #1782, #1836; anchor X/Y/W/H, #1824; toolbar and All Tools, #1751; macOS save sheets, #1855; rendering caches, #1667–#1792; untrusted files, #1852, #1862–#1873; failed-save dialog, #1685; Dim Images, #1683; estimates unchanged; M12 row: Image Trace's enhanced presets; verified PngSuite downloads, #1729; synthetic control-input budgets, #1709; 2026-10-14 merges: anchor Align and Distribute, #1636; Direct Selection and Delete fixes, #1674, #1666, #1743; Expand on repeats, #1756; file and input hardening, #1776–#1783, #1786, #1807; MCP limits and envelope, #1727, #1728; Image Trace #1647, #1657; estimates unchanged; later 2026-10-13 merges: SVG import, #1565, #1596, #1568, #1601; Warp Arc, #1578; Pathfinder strokes, #1570; saves, #1620 in part; OpenType features, #1607; intersect Smart Guides, #1602 in part; estimates unchanged; TIFF is available in Export for Screens and Asset Export with shared format settings; scores and hours unchanged; G1/M11: Artboard deletion and history selection normalization; history regressions and full workspace CI pass; scores and hours unchanged; Character styles retain explicit Auto leading, propagate resets and preserve local leading overrides; scores and hours unchanged; Width Point Edit: Shift-double-click enables adjoining adjustment; plain double-click keeps it off; scores and hours unchanged; per-corner radius fields with a link toggle, split from #1594; control transport deadlines, #1726; M12 row: Image Trace's presets and options as they are now; Polish interface, #1498; compact native saves, #1492; PDF and EPS paste as vector art, #1499; import fixes, #1528, #1530, #1531, #1544, #1551, #1553; guide objects, #1534; Join after Average, #1533; Keyboard Shortcuts, #1539; estimates unchanged; Direct Selection anchor precedence, #1508; dialog slider rails, #1483; template layers in Outline view, #1486; type that does not fit its frame is reported, #1471; 3D on outlined type, #1481; print-size images, #1517; French catalog, #1511; estimates unchanged; Split Into Grid options, #1462; Transform Objects and Reflect's angle, #1448 and #1460; Pathfinder on a group, #1450; unknown parameter keys refused, #1442; grayscale TIFFs with alpha, #1466 in part; estimates unchanged; M9: Extrude & Bevel, Inflate and Rotate; `.ai` compound path paint, #1410, overprint on import, #1388, text-only PDF parts, #1387; Transform dialogs preview, #1412, and transforms of direct-selected anchors, #1408; strokes wider than their shape, #1396; estimates unchanged; `.ai` editing-data follow-ups, #1390, #1391, #1392; dialog keyboard focus, #1367 and #1395; symbol instance redraw cache, #1386; font rescan, #1376; estimates unchanged; gradient shapes import as paths, #1304; white constant alpha masks, #1286 in part; Live Corners widget click, #1239; custom ruler origin, #1212; M11: Artboard object clicks create a fitted artboard (#1227); estimate unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; DXF control-point SPLINE closure read, #1299 follow-up; desktop print transport adopts craft-print, Windows 7 fallback retained, scores unchanged; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; M6: Simplify preview/counts and valid topology selection (#1272); estimates unchanged; G2: Film Grain added; Photoshop effects 45/57; 28 filters remain; M14: RPM runtime metadata (#1275); estimates unchanged; M5: squared-distance texture redraws (#1257); clean-machine/platform drag measurements still pending; estimates unchanged; M2: Curvature point display improved (#1236, in part); estimates unchanged; M7: full-name font matching (#1258); Windows font-service QA pending; estimates unchanged; M1: no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); estimates unchanged; M14: dedicated Eyedropper cursor (#1269); estimates unchanged; M3: Eyedropper reads visible locked and outside-isolation sources (#1251); estimates unchanged; M2: Direct Selection segment picks and Delete (#1278); estimates unchanged; M3: adding paint to an unpainted zero-width stroke restores 1 pt (#1253); estimates unchanged; M12: graph designs, graph data, Graph Type and label options; M14: native macOS save Format menu, #866; M6: compound appearance and member fill-rule fixes, #1197; estimates unchanged; M9: PDF raster-effect cap warnings; G11: #893 fixed, #937 open; M7: accurate character controls after scaling, #1034; estimates unchanged; MCP `add_text` exposes the existing `vertical` option for point, area and path type; horizontal remains the default; scores and hours unchanged; Vertical fullwidth question and exclamation marks keep their nominal glyph upright when the font has no vertical alternate; scores and hours unchanged.; M2: Curvature curve geometry, #1236 in part; Width-point finite-arithmetic follow-up validated; scores and hours unchanged; Image Trace adjustment discovery; legacy `.ai` of version 7 saved, #868; estimates unchanged; Revolve: automatic smooth shading and default-on Cap with continuous rims; PDF.R1: shared PDF reader with windowed content scanning and explicit incomplete-content errors; scores and estimates unchanged; PDF.W1: guarded shared PDF writer; output behavior, scores and estimates unchanged; later 2026-10-14 merges: per-corner radius, #1682; Width Point Edit from the Width tool, #1814, #1630; guides, #1782, #1836; anchor X/Y/W/H, #1824; toolbar and All Tools, #1751; macOS save sheets, #1855; rendering caches, #1667–#1792; untrusted files, #1852, #1862–#1873; failed-save dialog, #1685; Dim Images, #1683; estimates unchanged; M12 row: Image Trace's enhanced presets; verified PngSuite downloads, #1729; synthetic control-input budgets, #1709; 2026-10-14 merges: anchor Align and Distribute, #1636; Direct Selection and Delete fixes, #1674, #1666, #1743; Expand on repeats, #1756; file and input hardening, #1776–#1783, #1786, #1807; MCP limits and envelope, #1727, #1728; Image Trace #1647, #1657; estimates unchanged; later 2026-10-13 merges: SVG import, #1565, #1596, #1568, #1601; Warp Arc, #1578; Pathfinder strokes, #1570; saves, #1620 in part; OpenType features, #1607; intersect Smart Guides, #1602 in part; estimates unchanged; TIFF is available in Export for Screens and Asset Export with shared format settings; scores and hours unchanged; G1/M11: Artboard deletion and history selection normalization; history regressions and full workspace CI pass; scores and hours unchanged; Character styles retain explicit Auto leading, propagate resets and preserve local leading overrides; scores and hours unchanged; Width Point Edit: Shift-double-click enables adjoining adjustment; plain double-click keeps it off; scores and hours unchanged; per-corner radius fields with a link toggle, split from #1594; control transport deadlines, #1726; M12 row: Image Trace's presets and options as they are now; Polish interface, #1498; compact native saves, #1492; PDF and EPS paste as vector art, #1499; import fixes, #1528, #1530, #1531, #1544, #1551, #1553; guide objects, #1534; Join after Average, #1533; Keyboard Shortcuts, #1539; estimates unchanged; Direct Selection anchor precedence, #1508; dialog slider rails, #1483; template layers in Outline view, #1486; type that does not fit its frame is reported, #1471; 3D on outlined type, #1481; print-size images, #1517; French catalog, #1511; estimates unchanged; Split Into Grid options, #1462; Transform Objects and Reflect's angle, #1448 and #1460; Pathfinder on a group, #1450; unknown parameter keys refused, #1442; grayscale TIFFs with alpha, #1466 in part; estimates unchanged; M9: Extrude & Bevel, Inflate and Rotate; `.ai` compound path paint, #1410, overprint on import, #1388, text-only PDF parts, #1387; Transform dialogs preview, #1412, and transforms of direct-selected anchors, #1408; strokes wider than their shape, #1396; estimates unchanged; `.ai` editing-data follow-ups, #1390, #1391, #1392; dialog keyboard focus, #1367 and #1395; symbol instance redraw cache, #1386; font rescan, #1376; estimates unchanged; gradient shapes import as paths, #1304; white constant alpha masks, #1286 in part; Live Corners widget click, #1239; custom ruler origin, #1212; M11: Artboard object clicks create a fitted artboard (#1227); estimate unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; DXF control-point SPLINE closure read, #1299 follow-up; desktop print transport adopts craft-print, Windows 7 fallback retained, scores unchanged; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; M6: Simplify preview/counts and valid topology selection (#1272); estimates unchanged; G2: Film Grain added; Photoshop effects 45/57; 28 filters remain; M14: RPM runtime metadata (#1275); estimates unchanged; M5: squared-distance texture redraws (#1257); clean-machine/platform drag measurements still pending; estimates unchanged; M2: Curvature point display improved (#1236, in part); estimates unchanged; M7: full-name font matching (#1258); Windows font-service QA pending; estimates unchanged; M1: no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); estimates unchanged; M14: dedicated Eyedropper cursor (#1269); estimates unchanged; M3: Eyedropper reads visible locked and outside-isolation sources (#1251); estimates unchanged; M2: Direct Selection segment picks and Delete (#1278); estimates unchanged; M3: adding paint to an unpainted zero-width stroke restores 1 pt (#1253); estimates unchanged; M12: graph designs, graph data, Graph Type and label options; M14: native macOS save Format menu, #866; M6: compound appearance and member fill-rule fixes, #1197; estimates unchanged; M9: PDF raster-effect cap warnings; G11: #893 fixed, #937 open; M7: accurate character controls after scaling, #1034; estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) Forward-looking plan. Where VectorCraft stands is in [`ROADMAP.md`](../ROADMAP.md) and [target-app-parity.md](target-app-parity.md); the ranked work list is [gaps.md](gaps.md). Hours are Opus 5.5 @@ -33,7 +33,7 @@ Checked 2026-10-10 from the code, tests and open issues; no workflow fails, so V 2. **`.ai` files from real users** (G9): layer structure (#951), guides (#779). 10–20 h. 3. **Launch and stability** (G10): the Windows and Linux start-up reports. 20–35 h. 4. **Core-tool bugs** (G11): Shape Builder regions (#937). Asset Export ghost borders closed (#983 / #1037). 8–15 h. -5. **Raster effects** (G2) continue alongside: Artistic (Cutout, Film Grain, Neon Glow and Poster Edges done; 11 left), Sketch (Halftone Pattern done; 13 left), then the Effect Gallery. 21–35 h. +5. **Raster effects** (G2) alongside: 12 filters (7 Artistic, 4 Sketch, 1 more) and the Effect Gallery, 8–14 h. ## Next @@ -53,23 +53,24 @@ Checked 2026-10-10 from the code, tests and open issues; no workflow fails, so V | M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending) | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending) | 12–18 | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork; gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries. Left: freeform and mixed spot/process gradients export as stops or process colours to SVG/PDF; confirm the Scale Strokes & Effects default | 4–8 | -| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish | 3–6 (existing scope; Affinity export unestimated) | +| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish | 3–6 (existing scope; Affinity export unestimated) | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork; gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries. Left: freeform and mixed spot/process gradients export as stops or process colours to SVG/PDF; confirm the Scale Strokes & Effects default | 4–8 | | M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; auto/slider/advanced UI remains open); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open) | 3–6 | | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel, Find Font, installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | -| M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Cutout, Film Grain, Neon Glow and Poster Edges and Sketch › Halftone Pattern done (33/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | +| M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Cutout, Film Grain, Neon Glow, Poster Edges, Smudge Stick, Sponge and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Photocopy and Stamp done (46/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); brushes/symbols in progress | 23–37 | -| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; multiple windows, presentation polish) | 🟡 | 15–25 | +| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged) | 🟡 | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending | 6–10 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; broader scripting and batch work remains | 18–27 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets reveal adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending | 6–10 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; quick presets trace at once and the Image Trace button opens the adjustment controls; tiny fitted contours retain islands and holes; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color, Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending | 6–10 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 | 18–27 | -| M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) | 🟡 Numeric-field pointer selection and focus regression-tested (#1326, in part; short movements still select all); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces, a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); an experimental, unsupported Windows 7 x64 portable OpenGL build (not verified by maintainers); accessibility and broader Windows/Linux packaging/QA pending | 18–28 | +| M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Numeric-field pointer selection and focus regression-tested (#1326, in part; short movements still select all); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces, a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); an experimental, unsupported Windows 7 x64 portable OpenGL build (not verified by maintainers); accessibility and broader Windows/Linux packaging/QA pending | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | +| M14 follow-up | Color Picker layout (#2008) | ✅ Compact controls, centered header, stacked actions, aligned fields and screen sampling; narrow windows scroll vertically | Included above | | | **Total to full parity** (one agent; from [target-app-parity.md](target-app-parity.md)) | | **~360–590** | Milestone estimates predate the 2026-10-10 re-measure for M1–M14; the area table in @@ -87,6 +88,13 @@ M3 follow-up (#1968): native saves retain the per-document transparency grid set | Date | Change | Summary | |---|---|---| +| 2026-10-19 | minor | Cache status-readout sample widths per UI, language, document unit and pixels per point; regressions check reuse across live frames and refresh after display-setting changes. Scores and estimates unchanged. | +| 2026-10-19 | minor | Status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates. Contributor original-file acceptance confirmed; scores and estimates unchanged. | +| 2026-10-18 | minor | M4/DXF #1299: circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes retain POLYLINE width and closed partial arcs with an implicit closing chord are not promoted to CIRCLE. Scores and hours unchanged. | +| 2026-10-19 | minor | Cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission. Regression coverage; scores and estimates unchanged. | +| 2026-10-19 | minor | Cached canvas reprojection preserves scale during resize, rotation and DPI changes. Contributor original-file acceptance confirmed; scores and estimates unchanged. | +| 2026-10-19 | minor | Color Picker layout (#2008): compact controls, centered header, stacked actions and aligned inputs; screen-reader channel values, current shared button names and styling, screen sampler and model-by-model Tab order retained. Narrow windows scroll vertically; scores and hours unchanged. | +| 2026-10-18 | minor | M4: PDF Place and clipboard paste preserve live text by default; explicit outlines on Place remain available. Synthetic regressions; estimates unchanged. | | 2026-10-18 | minor | Mirror Repeat shows its axis when selected (#2877): drag the line or center handle to move it, drag an end handle to rotate it (Shift: 45°), Escape cancels and each drag is one undo step. Engine and headless canvas gesture regressions passed; native move, rotation and Escape screenshots reviewed. Formatting, Clippy, WASM and repository checks passed; the undo label reuses translated Repeat Options. (#2877) Scores and hours unchanged. | | 2026-10-18 | minor | Selected Mirror Repeat bounding-box handles take priority over the axis line; a Top-handle regression confirms the default repeat scales vertically, while center and end handles retain their move and rotation behavior. Headline scores and estimates unchanged. | | 2026-10-17 | minor | Blend spine Anchor Point conversions, selection/stacking priority and Shift regression coverage (#2544); scores and hours unchanged. Windows native canvas checks and screenshots reviewed in PR #2643. | @@ -105,6 +113,8 @@ M3 follow-up (#1968): native saves retain the per-document transparency grid set | 2026-10-16 | minor | Correction to M12: quick Image Trace presets trace at once; the Image Trace button opens the adjustment controls (). Wording only; status unchanged. | | 2026-10-16 | minor | Batch exporting in Export for Screens (#1935): a file name pattern (document and item names, a counter, the date), folders per format, item or both, Layers and Selection tabs with thumbnails, EPS, AI and VectorCraft rows, a PDF row with printer's marks, and export presets (built-in Logo Package and Print-Ready PDF, saved ones); scores and hours unchanged (estimated) | | 2026-10-15 | minor | Image Trace retains nonzero positioned boundaries when a fixed-end returning piece has fewer than two fitted cubics. Source-generated tests check survival, winding, shared-edge reversal and Noise controls; see `image-trace-quality.md`. Scores and hours unchanged. | +| 2026-10-16 | minor | G2: Effect › Artistic › Smudge Stick, Sponge and Watercolor (original approximations with their documented options); measured Photoshop filters 36/57 with Cutout, Neon Glow and Poster Edges, 21 remaining (19–31 h). | +| 2026-10-16 | minor | G2: Effect › Sketch › Bas Relief, Charcoal, Photocopy and Stamp (#2527); measured Photoshop filters 37/57 with Cutout, Neon Glow and Poster Edges, 20 remaining (18–30 h). | | 2026-10-16 | minor | G2: Effect › Sketch › Halftone Pattern (Size, Contrast, Pattern Type Circle, Dot or Line; black ink on white paper, Size in points at any Document Raster Effects resolution); measured Photoshop filters 30/57, 27 remaining (22–38 h). | | 2026-10-17 | minor | Colored Inflate: shared membrane normals and smooth RGB vector ramps replace flat polygon bands; channel groups are batched per solid-fill surface. White-light Inflate retains its original polygons, paint composition and seam joins; the 0.05 seam minimum is restored. Scores and hour estimates unchanged. | | 2026-10-16 | minor | 3D lighting: one to ten directional lights, a selectable light list, Add Light and Delete Light, independent settings and artboard gestures; ambient applied once and smooth RGB vector export; scores and hour estimates unchanged | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 080c8527dd..0388bef625 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-18 · **Change:** minor (interactive Mirror Repeat axis; bounding-box handles take priority over the axis body while the center and end handles retain their move and rotation actions; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; Blend spine Anchor Point conversions, selection/stacking priority and Shift regression coverage (#2544); scores and hours unchanged; Artboard Options' X and Y with a reference point, #1876; Image Trace: Auto Color keeps rare but distinct colours; Image Trace: large images trace with a warning; anchor limit raised to 8,000,000; Image Trace: Raster::new returns an error for a buffer of the wrong length; M12 maximal-disc graph pruning and junction merging measured; M12 crop EDT and Guo–Hall thinning measured; M12 centre-lines baseline measured; scores and hours unchanged; installed plug-ins stay installed after a restart, #2541; Group Selection picks and moves one path of a compound path, #2441 in part; the Move dialog opens on the last move and its last checkboxes; Image Trace: a higher Paths never gives fewer segments on collapsed loops; Image Trace: the notch rule reads only its own piece; Image Trace: an edge's sub-pixel shift is the same from either side; Image Trace Flat Logo traces line art on white paper instead of a blank result; score and hours unchanged; Image Trace: a simpler contour walk with no precomputed direction table; transparency grid visibility saved in native documents, #1968; MCP cancellation, progress and busy answers during long exports, #2165, #2171, #2172; EPS editing data: legacy mesh corners, vector opacity masks and compound member paint retained; raster page comparison filters minification without relaxing limits; scores and hours unchanged; native family-name fallback from English-only typographic names, #2208; scores unchanged; batch exporting, #1935; G2: Effect › Sketch › Halftone Pattern; Photoshop filters 30/57, 27 remaining (22–38 h); G5: Symbol Options Export Type (Graphic / Movie Clip); Localization: Brazilian Portuguese complete under the tests, #1914, 71% → 74%; G6 image variables: Automation ~60% → ~62% / detail ~65% → ~68%, hours lowered; Warp Options controls verified by focused checks and original-image review; estimates unchanged; G11: Asset Export Art Optimized seam (#983 / #1037) and supersampled thumbs; Export for Screens 85% → 90%; existing-guide Escape cancellation validated 2026-10-14; scores and hours unchanged; open-path anchor Delete keeps surviving runs separate; estimates unchanged; PDF.R1: shared PDF reader with windowed content scanning and explicit incomplete-content errors; scores and estimates unchanged; PDF.W1: guarded shared PDF writer; output behavior, scores and estimates unchanged; Artboard tab-switch follow-up historically validated on `a0671777`; scores and hours unchanged; Artboard clean active-tab close/Delete follow-up validated 2026-10-15; later 2026-10-14 merges: anchor X/Y/W/H, #1824; Snap to Grid over Snap to Pixel, #1816; toolbar and All Tools, #1751; Actions panel selection, #1629 in part; redo during a drag, #1719; preferences written on OK, #1747; type in symbols after reopening, #1738; macOS save sheets, #1855, the Format menu withdrawn; stroke outlines shared, #1667; untrusted files, #1852, #1862–#1873; failed-save dialog, #1685; effects, #1864, Dim Images, #1683; duplicated rows of the 2026-10-05 table noted for the owner; scores unchanged; Image Trace: Shapes rework, stroke caps, enhanced presets, gradients over noise, measured in `image-trace-quality.md`, score unchanged; verified PngSuite downloads, #1729; synthetic control-input budgets, #1709; 2026-10-14 merges: anchor Align and Distribute, #1636; Direct Selection and Delete fixes, #1674, #1666, #1743; Escape while typing, #1686; Pen clicks, #1663; Expand on repeats, #1756; Roughen and Scribble, #1643, #1648; file and input hardening, #1776–#1783, #1786, #1807; MCP limits and envelope, #1727, #1728; Image Trace levelling and Flat Logo on scans, #1647, #1657; scores unchanged; later 2026-10-13 merges: SVG import, #1565, #1596, #1568, #1598, #1601; type on a path from PDF and `.ai`, #1585, #1586; ICC tag alignment, #1584; saves, #1620 in part; Warp Arc, #1578; Zig Zag, #1558; Pathfinder strokes, #1570; OpenType features, #1607; intersect Smart Guides, #1602 in part; a guide's position in the Transform panel, #1597 in part, a convenience with no parity claim; scores unchanged; TIFF is available in Export for Screens and Asset Export with shared format settings; scores and hours unchanged; G1/M11: Artboard deletion and history selection normalization; history regressions and full workspace CI pass; scores and hours unchanged; Character styles retain explicit Auto leading, propagate resets and preserve local leading overrides; scores and hours unchanged; Width Point Edit: Shift-double-click enables adjoining adjustment; plain double-click keeps it off; scores and hours unchanged; Units › Identify Objects By (`identifyObjectsBy`) acts on Layers, Variables and Layer Options, #394, scores unchanged; Appearance of Black › Printing / Exporting (`blackOutput`) acts on RGB raster export and Print as Bitmap, #394, scores unchanged; per-corner radius fields with a link toggle, split from #1594; control transport deadlines, #1726; Color panel: the mode picked last comes back after a restart, #1675; Image Trace: shared edges, memory, thin lines, strokes, corners, and the Shapes, Auto Grouping and Gradients options, measured in `image-trace-quality.md`, score unchanged; 2026-10-13 merges: Polish interface, #1498; compact native saves, #1492; PDF and EPS paste as vector art, #1499; import fixes for `.ai`, PDF, EPS and SVG, #1528, #1530, #1531, #1544, #1551, #1553; guide objects, #1534; Join after Average, #1533; Keyboard Shortcuts lists commands outside the menus, #1539; correction: Average and Join with a corner or smooth choice is missing; scores unchanged; late 2026-10-12 merges: type that does not fit its frame is reported, #1471; Tabs panel drags, #1458; template layers in Outline view, #1486; dialog slider rails, #1483; Direct Selection anchor precedence, #1508; print-size images, #1517; 3D on outlined type, #1481; French catalog, #1511; scores unchanged; Split Into Grid options, #1462; Transform Objects and Reflect across an angle, #1448 and #1460; Pathfinder panel on a group, #1450; unknown parameter keys refused, #1442; grayscale TIFFs with alpha, #1466 in part; Localization: Vietnamese catalog added, 63% → 71%, hours 60–100 → 55–90, full readiness unchanged at ~62%; scores and hours unchanged; Image Trace places edges to a fraction of a pixel in every mode, measured in `image-trace-quality.md`, score unchanged; 3D and Materials: Extrude & Bevel, Inflate and Rotate added, 3D ~8% → ~25% (estimated), menu stubs 25 → 22; Affinity text frames too short for their first line show it, #1423; Transform dialogs preview, #1412, and the transform tools and commands act on direct-selected anchors, #1408; `.ai` compound path paint, #1410; strokes wider than their shape, #1396; corner drags hide the bounding box, #1229; scores and hours unchanged; PDF and `.ai` import keep overprint, #1388, scores unchanged; `.ai` editing-data follow-ups: gradient stops, type of objects with an appearance, short area-type frames (#1390, #1391, #1392); dialog keyboard focus on every open (#1382, #1395); art flush with an artboard (#1375); font rescan (#1376); symbol instance redraw cache (#1386); scores and hours unchanged; grid tool options, #1377 in part, scores unchanged; `.ai` placed (linked) files read from the editing data, #1264, scores unchanged; gradient shapes import as paths, #1304; white constant alpha masks, #1286 in part; Live Corners widget click selects its corner, #1239; scores and hours unchanged; custom ruler origin, #1212; Artboard click-to-fit verified for objects, groups, visible bounds, undo and cancellation (#1227); scores and hours unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; Localization: Korean catalog added, 54% → 63%, full readiness unchanged at ~62%; desktop print transport adopts craft-print, Windows 7 fallback retained, scores unchanged; Image Trace: an image over 64 megapixels traces scaled down instead of being refused, scores unchanged; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; Path operations: Simplify preview/counts and component selection (#1272); scores unchanged; G2: Film Grain added; Photoshop effects 29/57; 28 filters remain; Platforms: RPM runtime capabilities and glibc floor (#1275); scores unchanged; Raster effects: squared-distance texture redraws (#1257); pixels unchanged; scores and hours unchanged; Drawing: Curvature point display improved (#1236, in part); scores unchanged; Type core: full-name font matching (#1258), scores and hours unchanged; Selection: no-op anchor Align preserves history and saved state (#1180 follow-up); scores unchanged; UI chrome: Eyedropper cursor and precise-setting regressions (#1269); scores unchanged; Colour: Eyedropper reads visible locked and outside-isolation sources (#1251); scores and hours unchanged; Selection: segment click/Delete preserves neighboring edges (#1278); scores unchanged; Colour: unpainted zero-width strokes regain 1 pt when painted (#1253); scores and hours unchanged; graphs: designs and markers, data, Graph Type and label options; UI chrome: native macOS save Format menu, #866, scores unchanged; compound paths inherit the backmost appearance and member fill-rule edits reach their owner, #1197; scores unchanged; Type core: Middle Eastern digit types done, Character panel menu › Digits; PDF export warns when the pixel cap lowers raster-effect resolution; Drawing tools: Live Corners round corners between curved sides, #1144; Type advanced: proportional vertical metrics (`vpal`) done, #966; Shape Builder: #893 fixed, merged regions of crossing lines no longer keep seams; scores unchanged while #937 is open; #1034: document-point character controls after object/group scaling; full readiness recomputed as the standard's additive weighted sum, ~62%; per-audience hours; essentials-user score ~75% added; ready-for-real-work re-examined: 50% → 55%, mainstream 65% added; earlier the same day: full re-measure against Illustrator 2026 30.x; merged the ROADMAP's parity estimate, honest assessment and "Shipped so far" into this file; SVG knockout groups of opaque art export without masks; Image Trace: colour presets no longer shatter noisy flat art and photos trace into smooth tones, measured in `image-trace-quality.md`, score unchanged; Split Into Grid options, #1462; Transform Objects and Reflect across an angle, #1448 and #1460; Pathfinder panel on a group, #1450; unknown parameter keys refused, #1442; grayscale TIFFs with alpha, #1466 in part; scores and hours unchanged; Image Trace places edges to a fraction of a pixel in every mode, measured in `image-trace-quality.md`, score unchanged; 3D and Materials: Extrude & Bevel, Inflate and Rotate added, 3D ~8% → ~25% (estimated), menu stubs 25 → 22; Affinity text frames too short for their first line show it, #1423; Transform dialogs preview, #1412, and the transform tools and commands act on direct-selected anchors, #1408; `.ai` compound path paint, #1410; strokes wider than their shape, #1396; corner drags hide the bounding box, #1229; scores and hours unchanged; PDF and `.ai` import keep overprint, #1388, scores unchanged; `.ai` editing-data follow-ups: gradient stops, type of objects with an appearance, short area-type frames (#1390, #1391, #1392); dialog keyboard focus on every open (#1382, #1395); art flush with an artboard (#1375); font rescan (#1376); symbol instance redraw cache (#1386); scores and hours unchanged; grid tool options, #1377 in part, scores unchanged; `.ai` placed (linked) files read from the editing data, #1264, scores unchanged; gradient shapes import as paths, #1304; white constant alpha masks, #1286 in part; Live Corners widget click selects its corner, #1239; scores and hours unchanged; custom ruler origin, #1212; Artboard click-to-fit verified for objects, groups, visible bounds, undo and cancellation (#1227); scores and hours unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; Localization: Korean catalog added, 54% → 63%, full readiness unchanged at ~62%; desktop print transport adopts craft-print, Windows 7 fallback retained, scores unchanged; Image Trace: an image over 64 megapixels traces scaled down instead of being refused, scores unchanged; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; Path operations: Simplify preview/counts and component selection (#1272); scores unchanged; G2: Film Grain added; Photoshop effects 29/57; 28 filters remain; Platforms: RPM runtime capabilities and glibc floor (#1275); scores unchanged; Raster effects: squared-distance texture redraws (#1257); pixels unchanged; scores and hours unchanged; Drawing: Curvature point display improved (#1236, in part); scores unchanged; Type core: full-name font matching (#1258), scores and hours unchanged; Selection: no-op anchor Align preserves history and saved state (#1180 follow-up); scores unchanged; UI chrome: Eyedropper cursor and precise-setting regressions (#1269); scores unchanged; Colour: Eyedropper reads visible locked and outside-isolation sources (#1251); scores and hours unchanged; Selection: segment click/Delete preserves neighboring edges (#1278); scores unchanged; Colour: unpainted zero-width strokes regain 1 pt when painted (#1253); scores and hours unchanged; graphs: designs and markers, data, Graph Type and label options; UI chrome: native macOS save Format menu, #866, scores unchanged; compound paths inherit the backmost appearance and member fill-rule edits reach their owner, #1197; scores unchanged; Type core: Middle Eastern digit types done, Character panel menu › Digits; PDF export warns when the pixel cap lowers raster-effect resolution; Drawing tools: Live Corners round corners between curved sides, #1144; Type advanced: proportional vertical metrics (`vpal`) done, #966; Shape Builder: #893 fixed, merged regions of crossing lines no longer keep seams; scores unchanged while #937 is open; #1034: document-point character controls after object/group scaling; full readiness recomputed as the standard's additive weighted sum, ~62%; per-audience hours; essentials-user score ~75% added; ready-for-real-work re-examined: 50% → 55%, mainstream 65% added; earlier the same day: full re-measure against Illustrator 2026 30.x; merged the ROADMAP's parity estimate, honest assessment and "Shipped so far" into this file; SVG knockout groups of opaque art export without masks; MCP `add_text` exposes the existing `vertical` option for point, area and path type; horizontal remains the default; scores and hours unchanged; Vertical fullwidth question and exclamation marks keep their nominal glyph upright when the font has no vertical alternate; scores and hours unchanged.; Curvature curve geometry, #1236 in part; Width-point finite-arithmetic follow-up validated; scores and hours unchanged; Image Trace adjustment discovery; File interop: legacy `.ai` of version 7 saved with type as text, hidden objects kept and an artboard picker, #868, scores unchanged; Revolve: automatic smooth shading and default-on Cap with continuous rims; PDF.R1: shared PDF reader with windowed content scanning and explicit incomplete-content errors; scores and estimates unchanged; PDF.W1: guarded shared PDF writer; output behavior, scores and estimates unchanged; later 2026-10-14 merges: anchor X/Y/W/H, #1824; Snap to Grid over Snap to Pixel, #1816; toolbar and All Tools, #1751; Actions panel selection, #1629 in part; redo during a drag, #1719; preferences written on OK, #1747; type in symbols after reopening, #1738; macOS save sheets, #1855, the Format menu withdrawn; stroke outlines shared, #1667; untrusted files, #1852, #1862–#1873; failed-save dialog, #1685; effects, #1864, Dim Images, #1683; duplicated rows of the 2026-10-05 table noted for the owner; scores unchanged; Image Trace: Shapes rework, stroke caps, enhanced presets, gradients over noise, measured in `image-trace-quality.md`, score unchanged; verified PngSuite downloads, #1729; synthetic control-input budgets, #1709; 2026-10-14 merges: anchor Align and Distribute, #1636; Direct Selection and Delete fixes, #1674, #1666, #1743; Escape while typing, #1686; Pen clicks, #1663; Expand on repeats, #1756; Roughen and Scribble, #1643, #1648; file and input hardening, #1776–#1783, #1786, #1807; MCP limits and envelope, #1727, #1728; Image Trace levelling and Flat Logo on scans, #1647, #1657; scores unchanged; later 2026-10-13 merges: SVG import, #1565, #1596, #1568, #1598, #1601; type on a path from PDF and `.ai`, #1585, #1586; ICC tag alignment, #1584; saves, #1620 in part; Warp Arc, #1578; Zig Zag, #1558; Pathfinder strokes, #1570; OpenType features, #1607; intersect Smart Guides, #1602 in part; a guide's position in the Transform panel, #1597 in part, a convenience with no parity claim; scores unchanged; TIFF is available in Export for Screens and Asset Export with shared format settings; scores and hours unchanged; G1/M11: Artboard deletion and history selection normalization; history regressions and full workspace CI pass; scores and hours unchanged; Character styles retain explicit Auto leading, propagate resets and preserve local leading overrides; scores and hours unchanged; Width Point Edit: Shift-double-click enables adjoining adjustment; plain double-click keeps it off; scores and hours unchanged; Units › Identify Objects By (`identifyObjectsBy`) acts on Layers, Variables and Layer Options, #394, scores unchanged; Appearance of Black › Printing / Exporting (`blackOutput`) acts on RGB raster export and Print as Bitmap, #394, scores unchanged; per-corner radius fields with a link toggle, split from #1594; control transport deadlines, #1726; Color panel: the mode picked last comes back after a restart, #1675; Image Trace: shared edges, memory, thin lines, strokes, corners, and the Shapes, Auto Grouping and Gradients options, measured in `image-trace-quality.md`, score unchanged; 2026-10-13 merges: Polish interface, #1498; compact native saves, #1492; PDF and EPS paste as vector art, #1499; import fixes for `.ai`, PDF, EPS and SVG, #1528, #1530, #1531, #1544, #1551, #1553; guide objects, #1534; Join after Average, #1533; Keyboard Shortcuts lists commands outside the menus, #1539; correction: Average and Join with a corner or smooth choice is missing; scores unchanged; late 2026-10-12 merges: type that does not fit its frame is reported, #1471; Tabs panel drags, #1458; template layers in Outline view, #1486; dialog slider rails, #1483; Direct Selection anchor precedence, #1508; print-size images, #1517; 3D on outlined type, #1481; French catalog, #1511; scores unchanged; Split Into Grid options, #1462; Transform Objects and Reflect across an angle, #1448 and #1460; Pathfinder panel on a group, #1450; unknown parameter keys refused, #1442; grayscale TIFFs with alpha, #1466 in part; Localization: Vietnamese catalog added, 63% → 71%, hours 60–100 → 55–90, full readiness unchanged at ~62%; scores and hours unchanged; Image Trace places edges to a fraction of a pixel in every mode, measured in `image-trace-quality.md`, score unchanged; 3D and Materials: Extrude & Bevel, Inflate and Rotate added, 3D ~8% → ~25% (estimated), menu stubs 25 → 22; Affinity text frames too short for their first line show it, #1423; Transform dialogs preview, #1412, and the transform tools and commands act on direct-selected anchors, #1408; `.ai` compound path paint, #1410; strokes wider than their shape, #1396; corner drags hide the bounding box, #1229; scores and hours unchanged; PDF and `.ai` import keep overprint, #1388, scores unchanged; `.ai` editing-data follow-ups: gradient stops, type of objects with an appearance, short area-type frames (#1390, #1391, #1392); dialog keyboard focus on every open (#1382, #1395); art flush with an artboard (#1375); font rescan (#1376); symbol instance redraw cache (#1386); scores and hours unchanged; grid tool options, #1377 in part, scores unchanged; `.ai` placed (linked) files read from the editing data, #1264, scores unchanged; gradient shapes import as paths, #1304; white constant alpha masks, #1286 in part; Live Corners widget click selects its corner, #1239; scores and hours unchanged; custom ruler origin, #1212; Artboard click-to-fit verified for objects, groups, visible bounds, undo and cancellation (#1227); scores and hours unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; Localization: Korean catalog added, 54% → 63%, full readiness unchanged at ~62%; desktop print transport adopts craft-print, Windows 7 fallback retained, scores unchanged; Image Trace: an image over 64 megapixels traces scaled down instead of being refused, scores unchanged; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; Path operations: Simplify preview/counts and component selection (#1272); scores unchanged; G2: Film Grain added; Photoshop effects 29/57; 28 filters remain; Platforms: RPM runtime capabilities and glibc floor (#1275); scores unchanged; Raster effects: squared-distance texture redraws (#1257); pixels unchanged; scores and hours unchanged; Drawing: Curvature point display improved (#1236, in part); scores unchanged; Type core: full-name font matching (#1258), scores and hours unchanged; Selection: no-op anchor Align preserves history and saved state (#1180 follow-up); scores unchanged; UI chrome: Eyedropper cursor and precise-setting regressions (#1269); scores unchanged; Colour: Eyedropper reads visible locked and outside-isolation sources (#1251); scores and hours unchanged; Selection: segment click/Delete preserves neighboring edges (#1278); scores unchanged; Colour: unpainted zero-width strokes regain 1 pt when painted (#1253); scores and hours unchanged; graphs: designs and markers, data, Graph Type and label options; UI chrome: native macOS save Format menu, #866, scores unchanged; compound paths inherit the backmost appearance and member fill-rule edits reach their owner, #1197; scores unchanged; Type core: Middle Eastern digit types done, Character panel menu › Digits; PDF export warns when the pixel cap lowers raster-effect resolution; Drawing tools: Live Corners round corners between curved sides, #1144; Type advanced: proportional vertical metrics (`vpal`) done, #966; Shape Builder: #893 fixed, merged regions of crossing lines no longer keep seams; scores unchanged while #937 is open; #1034: document-point character controls after object/group scaling; full readiness recomputed as the standard's additive weighted sum, ~62%; per-audience hours; essentials-user score ~75% added; ready-for-real-work re-examined: 50% → 55%, mainstream 65% added; earlier the same day: full re-measure against Illustrator 2026 30.x; merged the ROADMAP's parity estimate, honest assessment and "Shipped so far" into this file; SVG knockout groups of opaque art export without masks; Image Trace: colour presets no longer shatter noisy flat art and photos trace into smooth tones, measured in `image-trace-quality.md`, score unchanged; Split Into Grid options, #1462; Transform Objects and Reflect across an angle, #1448 and #1460; Pathfinder panel on a group, #1450; unknown parameter keys refused, #1442; grayscale TIFFs with alpha, #1466 in part; scores and hours unchanged; Image Trace places edges to a fraction of a pixel in every mode, measured in `image-trace-quality.md`, score unchanged; 3D and Materials: Extrude & Bevel, Inflate and Rotate added, 3D ~8% → ~25% (estimated), menu stubs 25 → 22; Affinity text frames too short for their first line show it, #1423; Transform dialogs preview, #1412, and the transform tools and commands act on direct-selected anchors, #1408; `.ai` compound path paint, #1410; strokes wider than their shape, #1396; corner drags hide the bounding box, #1229; scores and hours unchanged; PDF and `.ai` import keep overprint, #1388, scores unchanged; `.ai` editing-data follow-ups: gradient stops, type of objects with an appearance, short area-type frames (#1390, #1391, #1392); dialog keyboard focus on every open (#1382, #1395); art flush with an artboard (#1375); font rescan (#1376); symbol instance redraw cache (#1386); scores and hours unchanged; grid tool options, #1377 in part, scores unchanged; `.ai` placed (linked) files read from the editing data, #1264, scores unchanged; gradient shapes import as paths, #1304; white constant alpha masks, #1286 in part; Live Corners widget click selects its corner, #1239; scores and hours unchanged; custom ruler origin, #1212; Artboard click-to-fit verified for objects, groups, visible bounds, undo and cancellation (#1227); scores and hours unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; Localization: Korean catalog added, 54% → 63%, full readiness unchanged at ~62%; desktop print transport adopts craft-print, Windows 7 fallback retained, scores unchanged; Image Trace: an image over 64 megapixels traces scaled down instead of being refused, scores unchanged; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; Path operations: Simplify preview/counts and component selection (#1272); scores unchanged; G2: Film Grain added; Photoshop effects 29/57; 28 filters remain; Platforms: RPM runtime capabilities and glibc floor (#1275); scores unchanged; Raster effects: squared-distance texture redraws (#1257); pixels unchanged; scores and hours unchanged; Drawing: Curvature point display improved (#1236, in part); scores unchanged; Type core: full-name font matching (#1258), scores and hours unchanged; Selection: no-op anchor Align preserves history and saved state (#1180 follow-up); scores unchanged; UI chrome: Eyedropper cursor and precise-setting regressions (#1269); scores unchanged; Colour: Eyedropper reads visible locked and outside-isolation sources (#1251); scores and hours unchanged; Selection: segment click/Delete preserves neighboring edges (#1278); scores unchanged; Colour: unpainted zero-width strokes regain 1 pt when painted (#1253); scores and hours unchanged; graphs: designs and markers, data, Graph Type and label options; UI chrome: native macOS save Format menu, #866, scores unchanged; compound paths inherit the backmost appearance and member fill-rule edits reach their owner, #1197; scores unchanged; Type core: Middle Eastern digit types done, Character panel menu › Digits; PDF export warns when the pixel cap lowers raster-effect resolution; Drawing tools: Live Corners round corners between curved sides, #1144; Type advanced: proportional vertical metrics (`vpal`) done, #966; Shape Builder: #893 fixed, merged regions of crossing lines no longer keep seams; scores unchanged while #937 is open; #1034: document-point character controls after object/group scaling; full readiness recomputed as the standard's additive weighted sum, ~62%; per-audience hours; essentials-user score ~75% added; ready-for-real-work re-examined: 50% → 55%, mainstream 65% added; earlier the same day: full re-measure against Illustrator 2026 30.x; merged the ROADMAP's parity estimate, honest assessment and "Shipped so far" into this file; SVG knockout groups of opaque art export without masks) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-20 · **Change:** minor (live-effect plug-ins given their object's fills and strokes and the item they sit on, G17; plug-in parameters: labels, units, groups, help and conditions in their dialogs, text and number-list parameters, up to 256 of them, G17; exporter plug-ins: plug-in file formats in Export As and document.export, G17; G2: Effect › Artistic › Smudge Stick, Sponge and Watercolor; Sketch › Bas Relief, Charcoal, Photocopy and Stamp, #2533; Photoshop filters 45/57, 12 remaining (8–14 h); interactive Mirror Repeat axis; bounding-box handles take priority over the axis body while the center and end handles retain their move and rotation actions; Libraries panel: the list scrolls, items and groups reorder by dragging, items drag into and out of groups (`library.moveItem` before/after, `library.moveGroup`); scores unchanged; PDF invisible text opens as type with no fill or stroke and is written back invisible, #2675; status-readout sample widths cached by language, document unit and pixels per point; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; cached canvas reprojection preserves scale during resize, rotation and DPI changes; interactive Mirror Repeat axis; bounding-box handles take priority over the axis body while the center and end handles retain their move and rotation actions; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; Blend spine Anchor Point conversions, selection/stacking priority and Shift regression coverage (#2544); scores and hours unchanged; Artboard Options' X and Y with a reference point, #1876; Image Trace: Auto Color keeps rare but distinct colours; Image Trace: large images trace with a warning; anchor limit raised to 8,000,000; Image Trace: Raster::new returns an error for a buffer of the wrong length; M12 maximal-disc graph pruning and junction merging measured; M12 crop EDT and Guo–Hall thinning measured; M12 centre-lines baseline measured; scores and hours unchanged; installed plug-ins stay installed after a restart, #2541; Group Selection picks and moves one path of a compound path, #2441 in part; the Move dialog opens on the last move and its last checkboxes; Image Trace: a higher Paths never gives fewer segments on collapsed loops; Image Trace: the notch rule reads only its own piece; Image Trace: an edge's sub-pixel shift is the same from either side; Image Trace Flat Logo traces line art on white paper instead of a blank result; score and hours unchanged; Image Trace: a simpler contour walk with no precomputed direction table; transparency grid visibility saved in native documents, #1968; MCP cancellation, progress and busy answers during long exports, #2165, #2171, #2172; EPS editing data: legacy mesh corners, vector opacity masks and compound member paint retained; raster page comparison filters minification without relaxing limits; scores and hours unchanged; native family-name fallback from English-only typographic names, #2208; scores unchanged; batch exporting, #1935; G2: Effect › Sketch › Halftone Pattern; Photoshop filters 45/57, 12 remaining (8–14 h); G5: Symbol Options Export Type (Graphic / Movie Clip); Localization: Brazilian Portuguese complete under the tests, #1914, 71% → 74%; G6 image variables: Automation ~60% → ~62% / detail ~65% → ~68%, hours lowered; Warp Options controls verified by focused checks and original-image review; estimates unchanged; G11: Asset Export Art Optimized seam (#983 / #1037) and supersampled thumbs; Export for Screens 85% → 90%; existing-guide Escape cancellation validated 2026-10-14; scores and hours unchanged; open-path anchor Delete keeps surviving runs separate; estimates unchanged; PDF.R1: shared PDF reader with windowed content scanning and explicit incomplete-content errors; scores and estimates unchanged; PDF.W1: guarded shared PDF writer; output behavior, scores and estimates unchanged; Artboard tab-switch follow-up historically validated on `a0671777`; scores and hours unchanged; Artboard clean active-tab close/Delete follow-up validated 2026-10-15; later 2026-10-14 merges: anchor X/Y/W/H, #1824; Snap to Grid over Snap to Pixel, #1816; toolbar and All Tools, #1751; Actions panel selection, #1629 in part; redo during a drag, #1719; preferences written on OK, #1747; type in symbols after reopening, #1738; macOS save sheets, #1855, the Format menu withdrawn; stroke outlines shared, #1667; untrusted files, #1852, #1862–#1873; failed-save dialog, #1685; effects, #1864, Dim Images, #1683; duplicated rows of the 2026-10-05 table noted for the owner; scores unchanged; Image Trace: Shapes rework, stroke caps, enhanced presets, gradients over noise, measured in `image-trace-quality.md`, score unchanged; verified PngSuite downloads, #1729; synthetic control-input budgets, #1709; 2026-10-14 merges: anchor Align and Distribute, #1636; Direct Selection and Delete fixes, #1674, #1666, #1743; Escape while typing, #1686; Pen clicks, #1663; Expand on repeats, #1756; Roughen and Scribble, #1643, #1648; file and input hardening, #1776–#1783, #1786, #1807; MCP limits and envelope, #1727, #1728; Image Trace levelling and Flat Logo on scans, #1647, #1657; scores unchanged; later 2026-10-13 merges: SVG import, #1565, #1596, #1568, #1598, #1601; type on a path from PDF and `.ai`, #1585, #1586; ICC tag alignment, #1584; saves, #1620 in part; Warp Arc, #1578; Zig Zag, #1558; Pathfinder strokes, #1570; OpenType features, #1607; intersect Smart Guides, #1602 in part; a guide's position in the Transform panel, #1597 in part, a convenience with no parity claim; scores unchanged; TIFF is available in Export for Screens and Asset Export with shared format settings; scores and hours unchanged; G1/M11: Artboard deletion and history selection normalization; history regressions and full workspace CI pass; scores and hours unchanged; Character styles retain explicit Auto leading, propagate resets and preserve local leading overrides; scores and hours unchanged; Width Point Edit: Shift-double-click enables adjoining adjustment; plain double-click keeps it off; scores and hours unchanged; Units › Identify Objects By (`identifyObjectsBy`) acts on Layers, Variables and Layer Options, #394, scores unchanged; Appearance of Black › Printing / Exporting (`blackOutput`) acts on RGB raster export and Print as Bitmap, #394, scores unchanged; per-corner radius fields with a link toggle, split from #1594; control transport deadlines, #1726; Color panel: the mode picked last comes back after a restart, #1675; Image Trace: shared edges, memory, thin lines, strokes, corners, and the Shapes, Auto Grouping and Gradients options, measured in `image-trace-quality.md`, score unchanged; 2026-10-13 merges: Polish interface, #1498; compact native saves, #1492; PDF and EPS paste as vector art, #1499; import fixes for `.ai`, PDF, EPS and SVG, #1528, #1530, #1531, #1544, #1551, #1553; guide objects, #1534; Join after Average, #1533; Keyboard Shortcuts lists commands outside the menus, #1539; correction: Average and Join with a corner or smooth choice is missing; scores unchanged; late 2026-10-12 merges: type that does not fit its frame is reported, #1471; Tabs panel drags, #1458; template layers in Outline view, #1486; dialog slider rails, #1483; Direct Selection anchor precedence, #1508; print-size images, #1517; 3D on outlined type, #1481; French catalog, #1511; scores unchanged; Split Into Grid options, #1462; Transform Objects and Reflect across an angle, #1448 and #1460; Pathfinder panel on a group, #1450; unknown parameter keys refused, #1442; grayscale TIFFs with alpha, #1466 in part; Localization: Vietnamese catalog added, 63% → 71%, hours 60–100 → 55–90, full readiness unchanged at ~62%; scores and hours unchanged; Image Trace places edges to a fraction of a pixel in every mode, measured in `image-trace-quality.md`, score unchanged; 3D and Materials: Extrude & Bevel, Inflate and Rotate added, 3D ~8% → ~25% (estimated), menu stubs 25 → 22; Affinity text frames too short for their first line show it, #1423; Transform dialogs preview, #1412, and the transform tools and commands act on direct-selected anchors, #1408; `.ai` compound path paint, #1410; strokes wider than their shape, #1396; corner drags hide the bounding box, #1229; scores and hours unchanged; PDF and `.ai` import keep overprint, #1388, scores unchanged; `.ai` editing-data follow-ups: gradient stops, type of objects with an appearance, short area-type frames (#1390, #1391, #1392); dialog keyboard focus on every open (#1382, #1395); art flush with an artboard (#1375); font rescan (#1376); symbol instance redraw cache (#1386); scores and hours unchanged; grid tool options, #1377 in part, scores unchanged; `.ai` placed (linked) files read from the editing data, #1264, scores unchanged; gradient shapes import as paths, #1304; white constant alpha masks, #1286 in part; Live Corners widget click selects its corner, #1239; scores and hours unchanged; custom ruler origin, #1212; Artboard click-to-fit verified for objects, groups, visible bounds, undo and cancellation (#1227); scores and hours unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; Localization: Korean catalog added, 54% → 63%, full readiness unchanged at ~62%; desktop print transport adopts craft-print, Windows 7 fallback retained, scores unchanged; Image Trace: an image over 64 megapixels traces scaled down instead of being refused, scores unchanged; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; Path operations: Simplify preview/counts and component selection (#1272); scores unchanged; G2: Film Grain added; Photoshop effects 45/57; 28 filters remain; Platforms: RPM runtime capabilities and glibc floor (#1275); scores unchanged; Raster effects: squared-distance texture redraws (#1257); pixels unchanged; scores and hours unchanged; Drawing: Curvature point display improved (#1236, in part); scores unchanged; Type core: full-name font matching (#1258), scores and hours unchanged; Selection: no-op anchor Align preserves history and saved state (#1180 follow-up); scores unchanged; UI chrome: Eyedropper cursor and precise-setting regressions (#1269); scores unchanged; Colour: Eyedropper reads visible locked and outside-isolation sources (#1251); scores and hours unchanged; Selection: segment click/Delete preserves neighboring edges (#1278); scores unchanged; Colour: unpainted zero-width strokes regain 1 pt when painted (#1253); scores and hours unchanged; graphs: designs and markers, data, Graph Type and label options; UI chrome: native macOS save Format menu, #866, scores unchanged; compound paths inherit the backmost appearance and member fill-rule edits reach their owner, #1197; scores unchanged; Type core: Middle Eastern digit types done, Character panel menu › Digits; PDF export warns when the pixel cap lowers raster-effect resolution; Drawing tools: Live Corners round corners between curved sides, #1144; Type advanced: proportional vertical metrics (`vpal`) done, #966; Shape Builder: #893 fixed, merged regions of crossing lines no longer keep seams; scores unchanged while #937 is open; #1034: document-point character controls after object/group scaling; full readiness recomputed as the standard's additive weighted sum, ~62%; per-audience hours; essentials-user score ~75% added; ready-for-real-work re-examined: 50% → 55%, mainstream 65% added; earlier the same day: full re-measure against Illustrator 2026 30.x; merged the ROADMAP's parity estimate, honest assessment and "Shipped so far" into this file; SVG knockout groups of opaque art export without masks; Image Trace: colour presets no longer shatter noisy flat art and photos trace into smooth tones, measured in `image-trace-quality.md`, score unchanged; Split Into Grid options, #1462; Transform Objects and Reflect across an angle, #1448 and #1460; Pathfinder panel on a group, #1450; unknown parameter keys refused, #1442; grayscale TIFFs with alpha, #1466 in part; scores and hours unchanged; Image Trace places edges to a fraction of a pixel in every mode, measured in `image-trace-quality.md`, score unchanged; 3D and Materials: Extrude & Bevel, Inflate and Rotate added, 3D ~8% → ~25% (estimated), menu stubs 25 → 22; Affinity text frames too short for their first line show it, #1423; Transform dialogs preview, #1412, and the transform tools and commands act on direct-selected anchors, #1408; `.ai` compound path paint, #1410; strokes wider than their shape, #1396; corner drags hide the bounding box, #1229; scores and hours unchanged; PDF and `.ai` import keep overprint, #1388, scores unchanged; `.ai` editing-data follow-ups: gradient stops, type of objects with an appearance, short area-type frames (#1390, #1391, #1392); dialog keyboard focus on every open (#1382, #1395); art flush with an artboard (#1375); font rescan (#1376); symbol instance redraw cache (#1386); scores and hours unchanged; grid tool options, #1377 in part, scores unchanged; `.ai` placed (linked) files read from the editing data, #1264, scores unchanged; gradient shapes import as paths, #1304; white constant alpha masks, #1286 in part; Live Corners widget click selects its corner, #1239; scores and hours unchanged; custom ruler origin, #1212; Artboard click-to-fit verified for objects, groups, visible bounds, undo and cancellation (#1227); scores and hours unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; Localization: Korean catalog added, 54% → 63%, full readiness unchanged at ~62%; desktop print transport adopts craft-print, Windows 7 fallback retained, scores unchanged; Image Trace: an image over 64 megapixels traces scaled down instead of being refused, scores unchanged; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; Path operations: Simplify preview/counts and component selection (#1272); scores unchanged; G2: Film Grain added; Photoshop effects 45/57; 28 filters remain; Platforms: RPM runtime capabilities and glibc floor (#1275); scores unchanged; Raster effects: squared-distance texture redraws (#1257); pixels unchanged; scores and hours unchanged; Drawing: Curvature point display improved (#1236, in part); scores unchanged; Type core: full-name font matching (#1258), scores and hours unchanged; Selection: no-op anchor Align preserves history and saved state (#1180 follow-up); scores unchanged; UI chrome: Eyedropper cursor and precise-setting regressions (#1269); scores unchanged; Colour: Eyedropper reads visible locked and outside-isolation sources (#1251); scores and hours unchanged; Selection: segment click/Delete preserves neighboring edges (#1278); scores unchanged; Colour: unpainted zero-width strokes regain 1 pt when painted (#1253); scores and hours unchanged; graphs: designs and markers, data, Graph Type and label options; UI chrome: native macOS save Format menu, #866, scores unchanged; compound paths inherit the backmost appearance and member fill-rule edits reach their owner, #1197; scores unchanged; Type core: Middle Eastern digit types done, Character panel menu › Digits; PDF export warns when the pixel cap lowers raster-effect resolution; Drawing tools: Live Corners round corners between curved sides, #1144; Type advanced: proportional vertical metrics (`vpal`) done, #966; Shape Builder: #893 fixed, merged regions of crossing lines no longer keep seams; scores unchanged while #937 is open; #1034: document-point character controls after object/group scaling; full readiness recomputed as the standard's additive weighted sum, ~62%; per-audience hours; essentials-user score ~75% added; ready-for-real-work re-examined: 50% → 55%, mainstream 65% added; earlier the same day: full re-measure against Illustrator 2026 30.x; merged the ROADMAP's parity estimate, honest assessment and "Shipped so far" into this file; SVG knockout groups of opaque art export without masks; MCP `add_text` exposes the existing `vertical` option for point, area and path type; horizontal remains the default; scores and hours unchanged; Vertical fullwidth question and exclamation marks keep their nominal glyph upright when the font has no vertical alternate; scores and hours unchanged.; Curvature curve geometry, #1236 in part; Width-point finite-arithmetic follow-up validated; scores and hours unchanged; Image Trace adjustment discovery; File interop: legacy `.ai` of version 7 saved with type as text, hidden objects kept and an artboard picker, #868, scores unchanged; Revolve: automatic smooth shading and default-on Cap with continuous rims; PDF.R1: shared PDF reader with windowed content scanning and explicit incomplete-content errors; scores and estimates unchanged; PDF.W1: guarded shared PDF writer; output behavior, scores and estimates unchanged; later 2026-10-14 merges: anchor X/Y/W/H, #1824; Snap to Grid over Snap to Pixel, #1816; toolbar and All Tools, #1751; Actions panel selection, #1629 in part; redo during a drag, #1719; preferences written on OK, #1747; type in symbols after reopening, #1738; macOS save sheets, #1855, the Format menu withdrawn; stroke outlines shared, #1667; untrusted files, #1852, #1862–#1873; failed-save dialog, #1685; effects, #1864, Dim Images, #1683; duplicated rows of the 2026-10-05 table noted for the owner; scores unchanged; Image Trace: Shapes rework, stroke caps, enhanced presets, gradients over noise, measured in `image-trace-quality.md`, score unchanged; verified PngSuite downloads, #1729; synthetic control-input budgets, #1709; 2026-10-14 merges: anchor Align and Distribute, #1636; Direct Selection and Delete fixes, #1674, #1666, #1743; Escape while typing, #1686; Pen clicks, #1663; Expand on repeats, #1756; Roughen and Scribble, #1643, #1648; file and input hardening, #1776–#1783, #1786, #1807; MCP limits and envelope, #1727, #1728; Image Trace levelling and Flat Logo on scans, #1647, #1657; scores unchanged; later 2026-10-13 merges: SVG import, #1565, #1596, #1568, #1598, #1601; type on a path from PDF and `.ai`, #1585, #1586; ICC tag alignment, #1584; saves, #1620 in part; Warp Arc, #1578; Zig Zag, #1558; Pathfinder strokes, #1570; OpenType features, #1607; intersect Smart Guides, #1602 in part; a guide's position in the Transform panel, #1597 in part, a convenience with no parity claim; scores unchanged; TIFF is available in Export for Screens and Asset Export with shared format settings; scores and hours unchanged; G1/M11: Artboard deletion and history selection normalization; history regressions and full workspace CI pass; scores and hours unchanged; Character styles retain explicit Auto leading, propagate resets and preserve local leading overrides; scores and hours unchanged; Width Point Edit: Shift-double-click enables adjoining adjustment; plain double-click keeps it off; scores and hours unchanged; Units › Identify Objects By (`identifyObjectsBy`) acts on Layers, Variables and Layer Options, #394, scores unchanged; Appearance of Black › Printing / Exporting (`blackOutput`) acts on RGB raster export and Print as Bitmap, #394, scores unchanged; per-corner radius fields with a link toggle, split from #1594; control transport deadlines, #1726; Color panel: the mode picked last comes back after a restart, #1675; Image Trace: shared edges, memory, thin lines, strokes, corners, and the Shapes, Auto Grouping and Gradients options, measured in `image-trace-quality.md`, score unchanged; 2026-10-13 merges: Polish interface, #1498; compact native saves, #1492; PDF and EPS paste as vector art, #1499; import fixes for `.ai`, PDF, EPS and SVG, #1528, #1530, #1531, #1544, #1551, #1553; guide objects, #1534; Join after Average, #1533; Keyboard Shortcuts lists commands outside the menus, #1539; correction: Average and Join with a corner or smooth choice is missing; scores unchanged; late 2026-10-12 merges: type that does not fit its frame is reported, #1471; Tabs panel drags, #1458; template layers in Outline view, #1486; dialog slider rails, #1483; Direct Selection anchor precedence, #1508; print-size images, #1517; 3D on outlined type, #1481; French catalog, #1511; scores unchanged; Split Into Grid options, #1462; Transform Objects and Reflect across an angle, #1448 and #1460; Pathfinder panel on a group, #1450; unknown parameter keys refused, #1442; grayscale TIFFs with alpha, #1466 in part; Localization: Vietnamese catalog added, 63% → 71%, hours 60–100 → 55–90, full readiness unchanged at ~62%; scores and hours unchanged; Image Trace places edges to a fraction of a pixel in every mode, measured in `image-trace-quality.md`, score unchanged; 3D and Materials: Extrude & Bevel, Inflate and Rotate added, 3D ~8% → ~25% (estimated), menu stubs 25 → 22; Affinity text frames too short for their first line show it, #1423; Transform dialogs preview, #1412, and the transform tools and commands act on direct-selected anchors, #1408; `.ai` compound path paint, #1410; strokes wider than their shape, #1396; corner drags hide the bounding box, #1229; scores and hours unchanged; PDF and `.ai` import keep overprint, #1388, scores unchanged; `.ai` editing-data follow-ups: gradient stops, type of objects with an appearance, short area-type frames (#1390, #1391, #1392); dialog keyboard focus on every open (#1382, #1395); art flush with an artboard (#1375); font rescan (#1376); symbol instance redraw cache (#1386); scores and hours unchanged; grid tool options, #1377 in part, scores unchanged; `.ai` placed (linked) files read from the editing data, #1264, scores unchanged; gradient shapes import as paths, #1304; white constant alpha masks, #1286 in part; Live Corners widget click selects its corner, #1239; scores and hours unchanged; custom ruler origin, #1212; Artboard click-to-fit verified for objects, groups, visible bounds, undo and cancellation (#1227); scores and hours unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; Localization: Korean catalog added, 54% → 63%, full readiness unchanged at ~62%; desktop print transport adopts craft-print, Windows 7 fallback retained, scores unchanged; Image Trace: an image over 64 megapixels traces scaled down instead of being refused, scores unchanged; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; Path operations: Simplify preview/counts and component selection (#1272); scores unchanged; G2: Film Grain added; Photoshop effects 45/57; 28 filters remain; Platforms: RPM runtime capabilities and glibc floor (#1275); scores unchanged; Raster effects: squared-distance texture redraws (#1257); pixels unchanged; scores and hours unchanged; Drawing: Curvature point display improved (#1236, in part); scores unchanged; Type core: full-name font matching (#1258), scores and hours unchanged; Selection: no-op anchor Align preserves history and saved state (#1180 follow-up); scores unchanged; UI chrome: Eyedropper cursor and precise-setting regressions (#1269); scores unchanged; Colour: Eyedropper reads visible locked and outside-isolation sources (#1251); scores and hours unchanged; Selection: segment click/Delete preserves neighboring edges (#1278); scores unchanged; Colour: unpainted zero-width strokes regain 1 pt when painted (#1253); scores and hours unchanged; graphs: designs and markers, data, Graph Type and label options; UI chrome: native macOS save Format menu, #866, scores unchanged; compound paths inherit the backmost appearance and member fill-rule edits reach their owner, #1197; scores unchanged; Type core: Middle Eastern digit types done, Character panel menu › Digits; PDF export warns when the pixel cap lowers raster-effect resolution; Drawing tools: Live Corners round corners between curved sides, #1144; Type advanced: proportional vertical metrics (`vpal`) done, #966; Shape Builder: #893 fixed, merged regions of crossing lines no longer keep seams; scores unchanged while #937 is open; #1034: document-point character controls after object/group scaling; full readiness recomputed as the standard's additive weighted sum, ~62%; per-audience hours; essentials-user score ~75% added; ready-for-real-work re-examined: 50% → 55%, mainstream 65% added; earlier the same day: full re-measure against Illustrator 2026 30.x; merged the ROADMAP's parity estimate, honest assessment and "Shipped so far" into this file; SVG knockout groups of opaque art export without masks; Image Trace: colour presets no longer shatter noisy flat art and photos trace into smooth tones, measured in `image-trace-quality.md`, score unchanged; Split Into Grid options, #1462; Transform Objects and Reflect across an angle, #1448 and #1460; Pathfinder panel on a group, #1450; unknown parameter keys refused, #1442; grayscale TIFFs with alpha, #1466 in part; scores and hours unchanged; Image Trace places edges to a fraction of a pixel in every mode, measured in `image-trace-quality.md`, score unchanged; 3D and Materials: Extrude & Bevel, Inflate and Rotate added, 3D ~8% → ~25% (estimated), menu stubs 25 → 22; Affinity text frames too short for their first line show it, #1423; Transform dialogs preview, #1412, and the transform tools and commands act on direct-selected anchors, #1408; `.ai` compound path paint, #1410; strokes wider than their shape, #1396; corner drags hide the bounding box, #1229; scores and hours unchanged; PDF and `.ai` import keep overprint, #1388, scores unchanged; `.ai` editing-data follow-ups: gradient stops, type of objects with an appearance, short area-type frames (#1390, #1391, #1392); dialog keyboard focus on every open (#1382, #1395); art flush with an artboard (#1375); font rescan (#1376); symbol instance redraw cache (#1386); scores and hours unchanged; grid tool options, #1377 in part, scores unchanged; `.ai` placed (linked) files read from the editing data, #1264, scores unchanged; gradient shapes import as paths, #1304; white constant alpha masks, #1286 in part; Live Corners widget click selects its corner, #1239; scores and hours unchanged; custom ruler origin, #1212; Artboard click-to-fit verified for objects, groups, visible bounds, undo and cancellation (#1227); scores and hours unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; Localization: Korean catalog added, 54% → 63%, full readiness unchanged at ~62%; desktop print transport adopts craft-print, Windows 7 fallback retained, scores unchanged; Image Trace: an image over 64 megapixels traces scaled down instead of being refused, scores unchanged; Czech render-site localization follow-up; scores and estimates unchanged; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; Path operations: Simplify preview/counts and component selection (#1272); scores unchanged; G2: Film Grain added; Photoshop effects 45/57; 28 filters remain; Platforms: RPM runtime capabilities and glibc floor (#1275); scores unchanged; Raster effects: squared-distance texture redraws (#1257); pixels unchanged; scores and hours unchanged; Drawing: Curvature point display improved (#1236, in part); scores unchanged; Type core: full-name font matching (#1258), scores and hours unchanged; Selection: no-op anchor Align preserves history and saved state (#1180 follow-up); scores unchanged; UI chrome: Eyedropper cursor and precise-setting regressions (#1269); scores unchanged; Colour: Eyedropper reads visible locked and outside-isolation sources (#1251); scores and hours unchanged; Selection: segment click/Delete preserves neighboring edges (#1278); scores unchanged; Colour: unpainted zero-width strokes regain 1 pt when painted (#1253); scores and hours unchanged; graphs: designs and markers, data, Graph Type and label options; UI chrome: native macOS save Format menu, #866, scores unchanged; compound paths inherit the backmost appearance and member fill-rule edits reach their owner, #1197; scores unchanged; Type core: Middle Eastern digit types done, Character panel menu › Digits; PDF export warns when the pixel cap lowers raster-effect resolution; Drawing tools: Live Corners round corners between curved sides, #1144; Type advanced: proportional vertical metrics (`vpal`) done, #966; Shape Builder: #893 fixed, merged regions of crossing lines no longer keep seams; scores unchanged while #937 is open; #1034: document-point character controls after object/group scaling; full readiness recomputed as the standard's additive weighted sum, ~62%; per-audience hours; essentials-user score ~75% added; ready-for-real-work re-examined: 50% → 55%, mainstream 65% added; earlier the same day: full re-measure against Illustrator 2026 30.x; merged the ROADMAP's parity estimate, honest assessment and "Shipped so far" into this file; SVG knockout groups of opaque art export without masks) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) The authoritative parity assessment. [`ROADMAP.md`](../ROADMAP.md) summarizes it; [`gaps.md`](gaps.md) is the work list made from it. Deep areas have their own checklists: [UI and interaction](ui-parity.md), @@ -12,7 +12,7 @@ the work list made from it. Deep areas have their own checklists: [UI and intera | Number | Value | Kind | |---|---|---| | 2026-10-15 | minor | Image Trace retains nonzero positioned boundaries when a fixed-end returning piece has fewer than two fitted cubics. Source-generated tests check survival, winding, shared-edge reversal and Noise controls; see `image-trace-quality.md`. Scores and hours unchanged. | -| **Feature breadth** (does each Illustrator menu item, tool, effect and format exist?) | **~88%** | measured in part: menu tree 353 of 375 items wired (94.1%), tools 89 of 92 (97%), vector effects 44 of 50 (88%), Photoshop-style effects 33 of 57 (58%), 3D 4 of 4 (initial: Extrude & Bevel, Revolve, Inflate, Rotate); blended by the area weights below | +| **Feature breadth** (does each Illustrator menu item, tool, effect and format exist?) | **~88%** | measured in part: menu tree 353 of 375 items wired (94.1%), tools 89 of 92 (97%), vector effects 44 of 50 (88%), Photoshop-style effects 46 of 57 (81%), 3D 4 of 4 (initial: Extrude & Bevel, Revolve, Inflate, Rotate); blended by the area weights below | | **Feature depth** (each area scored by behaviour, weighted) | **~75%** | estimated, area table below | | **Ready for real work, mainstream illustrator** | **~65%** (60–70%) | estimated, see [Ready for real work](#ready-for-real-work) | | **Ready for real work, full Illustrator** (decides the stage) | **~62%** (57–67%) | estimated: additive weighted sum over the dimensions, see [Ready for real work](#ready-for-real-work) | @@ -75,7 +75,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; remaining: Art brush Overlap, Pattern brush auto corners, brush libraries, pen pressure on macOS, tilt/bearing/rotation | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard Mix/Soft Mix/Trap, SVG Filters, the Transform effect's missing options (#885) | 6–10 | measured count 46/50, depth estimated; Warp Options controls verified by focused checks and original-image review | -| Raster effects (Effect Gallery) | 4 | 49% | 24 Photoshop-style filters (11 Artistic, 13 Sketch), the Effect Gallery dialog, Load Texture | 21–35 | measured count 33/57; texture redraw distances optimized (#1257), pixels verified; depth estimated | +| Raster effects (Effect Gallery) | 4 | 49% | 11 Photoshop-style filters (7 Artistic, 3 Sketch, 1 more), the Effect Gallery dialog, Load Texture | 8–14 | measured count 46/57; texture redraw distances optimized (#1257), pixels verified; depth estimated | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, 3D Classic, Turntable views, 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | | Type core | 9 | 80% | Auto-leading style resets are implemented; remaining: hyphenation and justification options, Optical Margin Alignment, Middle Eastern features beyond bidi layout, optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208) | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), variable font axes, tab leaders, spell check, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | @@ -84,14 +84,16 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Symbols, blends, envelopes, Repeat, perspective | 5 | 87% | 30.7's Blend panel with ease in/out, dynamic symbols, symbol libraries, Start Global Edit, envelope Anti-Alias/Preserve Shape; Symbol Options › Registration and Export Type (Graphic / Movie Clip) are done | 5–9 | estimated | | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | | Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers panel row context menus and Collect for Export (click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set | +| View & navigation | 3 | 70% | New View/Edit Views, multiple windows and Arrange, Snap to Glyph | 9–14 | estimated; cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), guides lost (#779), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC/JPEG 2000 import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests_reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions) | +| View & navigation | 3 | 70% | New View/Edit Views, multiple windows and Arrange, Snap to Glyph | 9–14 | estimated; cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | | View & navigation | 3 | 70% | New View/Edit Views, multiple windows and Arrange, Snap to Glyph | 9–14 | estimated | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), guides lost (#779), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC/JPEG 2000 import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified | 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests_reader_streaming.rs` and `xtask/src/pdf_deps.rs` | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | 30.0's tangent and perpendicular snapping and its snapping panel, "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), video rulers, distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | 30.0's tangent and perpendicular snapping and its snapping panel, "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658), global/artboard ruler mode switch and video rulers, distance readouts while drawing | 4–7 | estimated (lowered from 85%: target moved); new ruler-guide Alt orientation implemented | | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | anti-aliasing ghost borders (#983); TIFF choices and settings are implemented | 2–4 | estimated | | Print, colour management, separations, flattener | 3 | 80% | print preview fidelity | 2–4 | estimated | | Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | -| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, ~16 Preferences options stored but unused (#394), panels outside the window, SVG Interactivity, context menus beyond the canvas, accessibility | 13–20 | estimated; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; numeric-field focus and normal text drags regression-tested (#1326, in part); movements below the click threshold still select all; artboard navigation synchronizes the tool selection before destructive actions | +| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, ~16 Preferences options stored but unused (#394), panels outside the window, SVG Interactivity, context menus beyond the canvas, accessibility | 13–20 | estimated; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; numeric-field focus and normal text drags regression-tested (#1326, in part); movements below the click threshold still select all; artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged) | | Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated | | Generative AI (Text to Vector, Generative Recolor, Shape Fill, Concept to Vector, Prompt to Edit, Rewrite Text) | 2 | 0% | a pluggable provider and the panels; needs an owner decision on models | 30–60 | measured (absent) | | **Feature depth** | **105** | **~75%** | | **~250–420** | | @@ -298,7 +300,11 @@ Cutout, Neon Glow and Poster Edges (G2, 2026-10-16) follow as original Artistic preview, undo, appearance editing and save/reopen, keeping coverage at any Document Raster Effects resolution. Evidence: `crates/effects/src/pixel/artistic.rs`, its `cutout_*`, `neon_glow_*` and `poster_edges_*` tests, and `artistic_settings_survive_a_save_and_open` in -`crates/engine/src/tests_rasterfilters.rs`. Measured Photoshop filter count 33/57; depth unchanged. +`crates/engine/src/tests_rasterfilters.rs`. Smudge Stick, Sponge and Watercolor follow (G2, 2026-10-16) as original Artistic filters with the same +live preview, undo, appearance editing and save/reopen; evidence: `crates/effects/src/pixel/paint.rs`, +its `pixel::tests_paint::*` tests and `tests_rasterfilters`. Measured Photoshop filter count 36/57; depth unchanged. +`crates/engine/src/tests_rasterfilters.rs`. Bas Relief, Charcoal, Photocopy and Stamp (G2, 2026-10-16, #2527) follow as original Sketch filters +(`crates/effects/src/pixel/sketch_ink.rs`, `pixel::tests_sketch::*`). Measured Photoshop filter count 37/57; depth unchanged. ## Detailed missing items per area (2026-10-05 table, still current unless the area table above says otherwise) @@ -324,13 +330,13 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Drawing tools | 7 | 85% | rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, the freehand Tool Options' Keep selected, Alt to the Smooth tool, Blob Brush Merge Only with Selection and brush angle/roundness, Touch Type, Live Corners' Relative rounding (Curvature point display improved, #1236 in part) | 8–13 | | Selection, transform & align tools | 6 | 85% | Free Transform/Scale/Reflect along a rotated box, Start Global Edit, transform nuances (the rotated persistent bounding box is done; no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | | Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); remaining: Free Transform/Scale/Reflect along a rotated box, Start Global Edit, transform nuances (the rotated persistent bounding box is done) | 4–6 | -| Drawing tools | 7 | 85% | rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, the freehand Tool Options' Keep selected, Alt to the Smooth tool, Blob Brush Merge Only with Selection and brush angle/roundness, Touch Type, Live Corners' Relative rounding | 8–13 | +| Drawing tools | 7 | 86% | rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; Pencil: Alt key toggles to Smooth Tool (#2001); remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, Blob Brush Merge Only with Selection and brush angle/roundness, Touch Type, Live Corners' Relative rounding | 7–12 | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection, options (Tool Options dialog, clicking a stroke in merge mode) and Shift-drag marquee | 3–6 | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | freeform and mixed spot/process gradients in SVG/PDF (exported as stops or process colours), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | | Strokes, brushes, width profiles | 5 | 90% | the Art brush's Overlap, auto-generated Pattern brush corners and new tile art in Pattern Brush Options (Brush Options for every brush type done), brush libraries (generated in code), pen pressure on macOS (the windowing layer reports none there), brushes driven by pen tilt, bearing and barrel rotation (6D art pens) | 8–15 | | Appearance, transparency, graphic styles, masks | 5 | 98% | raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap, SVG Filters, the Transform effect's Transform Objects/Patterns and Scale Strokes & Effects options | 6–10 | -| Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 35% | ~36 Photoshop-style filters (Artistic, Brush Strokes, Sketch, Stylize), Texturizer's Load Texture and the Effect Gallery; Document Raster Effects Settings, raster effects in PDF, the pixel-filter pipeline, Radial Blur, Smart Blur (Normal, Edge Only and Overlay Edge), Unsharp Mask, Glowing Edges, Distort (Diffuse Glow, Glass, Ocean Ripple), Pixelate (Color Halftone, Crystallize, Mezzotint, Pointillize), Texture (Craquelure, Grain, Mosaic Tiles, Patchwork, Stained Glass, Texturizer) and Video (De-Interlace, NTSC Colors) are done | 19–31 | +| Raster effects (Effect Gallery, Document Raster Effects Settings) | 4 | 35% | ~36 Photoshop-style filters (Artistic, Brush Strokes, Sketch, Stylize), Texturizer's Load Texture and the Effect Gallery; Document Raster Effects Settings, raster effects in PDF, the pixel-filter pipeline, Radial Blur, Smart Blur (Normal, Edge Only and Overlay Edge), Unsharp Mask, Glowing Edges, Distort (Diffuse Glow, Glass, Ocean Ripple), Pixelate (Color Halftone, Crystallize, Mezzotint, Pointillize), Texture (Craquelure, Grain, Mosaic Tiles, Patchwork, Stained Glass, Texturizer) and Video (De-Interlace, NTSC Colors) are done | 8–14 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting; materials, light presets, shadows, ray tracing, 3D Classic and more complete visibility remain | 25–45 | | Type core | 9 | 80% | Middle Eastern features beyond bidi layout and Paragraph Direction (Character Direction, kashidas, the Middle Eastern composers, editable bidirectional SVG text, a split caret where directions meet); Hyphenation… and Justification… options (Every-line Composer for justified and ragged text, per object, is done; it is tuned by eye, not yet compared side by side with Illustrator; mixed type sizes in a paragraph still break single-line), Optical Margin Alignment, paragraph spacing limit for vertically justified area type, hidden characters, paragraph attributes in the Type tool's copy and paste (the characters keep their styles, the paragraphs take the destination's), mixed-value display in the Paragraph panel for a selection across differing paragraphs, partial selection of type-area anchors by marquee, optional font-size preservation during group scaling (scaled character controls fixed in #1034) | 14–19 | | Type advanced | 4 | 50% | CJK composition for vertical type (ruby, mojikumi beyond Line-end Punctuation Half Width — the other sets (and their paragraph-start bracket and indent rules), custom kinsoku sets (beyond Hard, Soft and None) and the Mojikumi Settings dialog —, manual tate-chu-yoko), variable font axis sliders (named instances are styles), tab leaders, spell check (open dictionary), Touch Type, Retype; vertical point/area/path type and Type Orientation have initial support (beyond parity, not scored: inline symbols in text) | 20–28 | @@ -345,7 +351,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Automation | 3 | 65% | scripting surface, batch (MCP drops malformed app replies without replay; Variables: text/visibility variables bound to objects, an object may carry several, dataset rows applied in one undo step, panel and Window › Variables with dialogs; image/graph kinds and dataset import/export open) | 6–10 | | UI chrome (panels, contextual Properties, workspaces, prefs) | 6 | 80% | macOS native menu dismissal fixed (M14.8); Variables, Links, Asset Export, CSS Properties, Attributes and the canvas context menu are done; remaining: SVG Interactivity, Properties per context, Consolidate All Windows, floating panels outside the app window and docked into any group, context menus beyond the canvas, about 13 Preferences options stored but not yet acted on (#394: Open Documents As Tabs, Real-time Drawing, hyphenation language, devices…) | 13–20 | | UI chrome (panels, contextual Properties, workspaces, prefs) | 6 | 80% | macOS native menu dismissal fixed (M14.8); Variables, Links, Asset Export, CSS Properties, Attributes and the canvas context menu are done; remaining: SVG Interactivity, Properties per context, Consolidate All Windows, floating panels outside the app window and docked into any group, context menus beyond the canvas, about 14 Preferences options stored but not yet acted on (#394: Highlight Alternate Glyphs, Open Documents As Tabs, Real-time Drawing, hyphenation language, devices…) | 13–20 | -| Libraries, Links, Package | 2 | 82% | the Libraries panel is local only (no cloud by design: libraries are files on this machine) and has no shared libraries, linked graphics or gradients and patterns as items yet; its graphics, colours and text styles (#745) and its search, groups and library export/import as `.vclibrary` files (#926) are done; Links and Package are done; placed VectorCraft documents are done (linked by default, vectors in every output, previews, Break Link, Expand, Edit Original, refresh on save) | 2–3 | +| Libraries, Links, Package | 2 | 82% | the Libraries panel is local only (no cloud by design: libraries are files on this machine) and has no shared libraries, linked graphics or gradients and patterns as items yet; its graphics, colours and text styles (#745), its search, groups and library export/import as `.vclibrary` files (#926), and a list that scrolls, with items and groups reordered by dragging and items dragged into and out of groups, are done; Links and Package are done; placed VectorCraft documents are done (linked by default, vectors in every output, previews, Break Link, Expand, Edit Original, refresh on save) | 2–3 | | **Feature parity** | **103** | **~75%** | | **~210–330** | | Interaction-fidelity pass (side by side with Illustrator: every tool modifier, cursor, dialog, Properties context) | | | | 60–90 | | Hardening (big-file corpus, fuzzing, cross-platform and browser QA, accessibility, packaging) | | | Bounded control socket waits (#1726); PngSuite pinned-file integrity and download budgets verified (#1729); RPM runtime capabilities and glibc floor checked (#1275); real-distro installation/start-up QA pending | 50–80 | @@ -369,7 +375,6 @@ switch" is a handful of large subsystems plus a fidelity pass, not a long tail o the only dimension measured against the reference app. Performance budgets haven't been re-run on an idle machine since 2026-10-01. - | Dimension | Estimate | Evidence and what's missing | |---|---|---| | **Breadth:** menus, tools and panels exist | ~90% | 13 menu items still stubbed; every tool implemented except Touch Type; 51 panel modules | @@ -388,6 +393,11 @@ since 2026-10-01. ## Evidence: what ships today, by area +- **Stable status-bar readouts:** The status message keeps its left anchor and clipping allocation as live values, canvas hover and background-job state change. Coordinate and spinner slots stay reserved; narrow windows hide optional diagnostics, then coordinates, to preserve message space. Widths are measured from the active font, translated labels and fixed numeric samples, never current readings. Coordinates through +/-9999.99 selected units, timings through 9999.9 ms and FPS through 9999 remain readable. Extreme values are elided with full tooltip/accessibility text; only elided fields show a tooltip. Coordinate inspection retains the last point per document and clears on PointerGone. Regressions cover message origin/clip/bounds/elision invariance, all registered languages and ten units, responsive layouts, coordinate inspection and document switching, and accessible busy transitions. The contributor rebuilt and confirmed the original status-bar issue is fixed with their own artwork on 2026-10-19; the subsequent upstream rebase is checked by regressions and full CI. The artwork stays local. Scores and estimates are unchanged. Sample widths use a bounded single-entry UI cache keyed by language, unit and pixels per point; two regressions verify reuse during live updates and invalidation after each display-setting change. + +- **Canvas review follow-up:** Cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission. Controlled-worker regression checks oversized width and height, high DPI and the render transform without allocating oversized images. Scores and estimates are unchanged. +- **Cached canvas frames during viewport changes:** Cached screen textures use their own raster dimensions and pixels-per-point when reprojected. `canvas::tests::cached_frames_keep_their_scale_during_resize_rotation_and_dpi_changes` holds the worker and checks every UV corner against the cached render transform, including isolated viewport-only resize at zero/30-degree rotation, fractional raster dimensions, zoom/pan, changed rotation, monitor-DPI changes in both directions, Pixel Preview and replacement-frame delivery. The contributor rebuilt and confirmed the original resize issue is fixed with their own artwork on 2026-10-19; the subsequent upstream rebase is checked by regressions and full CI. The artwork stays local. Scores and estimates are unchanged. +- **PDF editable import:** Place from bytes or a path with `link: false`, and `clipboard.importPdf` followed by Paste, preserve live type on the selected page. Place still honors `textAs: "outlines"`. Synthetic two-page regressions: `crates/engine/src/cmd/fileio/tests_pdffidelity.rs`. No change to the PDF reader's existing fallback rules. - **Selected Mirror Repeat handles:** a headless canvas regression creates the default mirror repeat and drags its Top bounding-box handle where the axis crosses it; the repeat grows vertically while its width stays fixed. Existing mirror-axis checks cover center movement and end-handle hit priority. The focused UI mirror tests pass. Scores and hours unchanged. - **Warp Options (#1760):** Effect > Warp and existing Appearance effect links share the fifteen existing styles, original schematic previews, orientation choices and percent Bend/Distortion controls. Focused tests passed for real numeric entry and slider input, Preview/Cancel, immediate Enter/OK, mixed-style edits, target/slot/visibility preservation and Undo/Redo. Each applied style stays unchanged until an explicit Style choice. Original style-menu and live-preview captures were reviewed; their numeric values were supplied programmatically. Public references: [Reshaping with effects](https://helpx.adobe.com/illustrator/using/reshaping-objects-effects.html) and [Using effects](https://helpx.adobe.com/illustrator/using/effects.html). Warp geometry, optional Properties integration and remembered defaults are unchanged; no broader parity claim. @@ -421,15 +431,18 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Names of new and renamed artboards, brushes and patterns:** `artboard.new` and `artboard.setProps` trim the white space around the name they are given, as the Artboards panel's rename does, and a blank name gives the artboard its default name, Artboard N for the Nth artboard. `brush.new`, `brush.duplicate`, `brush.options`, `object.pattern.make`, `object.pattern.saveCopy` and `pattern.options` trim the name as the Brush Options dialog and the Pattern Options panel do, and compare the trimmed name with the names there are; a blank name gives the name each command gives when there is none, and Brush Options and Pattern Options keep the name. Tests in `tests_panelcmds.rs`, `tests_brushsym.rs` and `tests_pattern.rs` cover each command. Public references: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html), [Brushes](https://web.archive.org/web/20251018101754/https://helpx.adobe.com/illustrator/using/brushes.html) and [Create and edit patterns](https://web.archive.org/web/20211031180358/https://helpx.adobe.com/illustrator/using/create-edit-patterns.html) (archived copies). - **Pattern names and swatch names:** `pattern.options` refuses a new name that another pattern, a swatch or a color group has. It takes a name that only the pattern's own swatches have. The reference page does not say what happens when the new name is taken; the refusal follows VectorCraft's rule that swatches and color groups share one namespace (`Document::swatch_name_taken`), which `swatch.new` and `swatch.edit` also follow. A rename gives the new name only to the pattern's swatches that had the old one; any other swatch with the old name keeps it, and art linked to that swatch stays linked. `object.pattern.make` and `object.pattern.saveCopy` number a color group's name as they number a swatch's. Tests in `tests_pattern.rs` cover each command. Public reference: [Create and edit patterns](https://web.archive.org/web/20211031180358/https://helpx.adobe.com/illustrator/using/create-edit-patterns.html) (archived copy). - **Edit Artboards in Properties:** the active artboard's name is a field. Typing a new name and pressing Enter or clicking elsewhere renames that artboard in one undo step, as the Artboards panel's rename does (`artboard.setProps {index, name}`); pressing Escape or leaving the field empty keeps the old name. A click on the Artboard Options icon beside the field opens Artboard Options for the active artboard, as double-clicking the Artboard tool's button does (`tool.options {tool: "artboard"}`). Pointer and key tests in `panels/properties.rs` cover both. Public references: [Resize artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/resize-artboards.html) and [Create and add new artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/add-new-artboards.html). +- **Resizing several artboards:** with several artboards selected with the Artboard tool, a new W or H in Properties, the Transform panel or the Control bar, a preset or an orientation in Properties or the Control bar, and a new Width or Height in Artboard Options resize every selected artboard in one undo step (`artboard.setProps {artboards}`); with Scale Artwork with Artboard on, Properties, the Transform panel and the Control bar scale each object once, with the artboard it was inside before the change. The Transform panel, the Control bar and Artboard Options resize each one about its own reference point, a preset sizes each one in its own orientation, and X and Y still move the active artboard alone. Pointer and key tests in `panels/properties.rs`, dialog tests in `dialogs/tests.rs` and an engine test in `tests_xform.rs` cover them. Public references: [Artboard Enhancements In Illustrator CC](https://blog.adobe.com/en/publish/2017/11/10/artboard-enhancements-in-illustrator-cc) ("modify them all in bulk by defining the height and width values") and [Using multiple artboards](https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (2019). - **Artboard Escape routing:** Escape leaves Artboard editing for Selection; during a drag it first cancels the gesture. Headless egui key events cover idle Escape, active-drag cancellation and a subsequent Escape in `tests_distortkeys.rs`. - **Artboard deletion keys:** Delete/Backspace delete selected boards in one Undo step, retaining the original first board in the current order when all are selected, as in the public [Delete artboards guide](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html). The last board and active drags stay protected; neither key clears selected artwork. Headless shortcut regressions in `tests_distortkeys.rs` cover reordered boards, artwork, saved state and Undo/Redo. - **Linux RPM packaging:** 64-bit runtime capabilities replace Fedora-specific required package names (#1275); glibc 2.35, libm and libgcc_s are declared alongside dynamically loaded xkbcommon and Vulkan/EGL. Generated x86_64/aarch64 metadata and isolated synthetic-provider resolution checked; real-distro install/start-up QA remains pending. +- **Linux file associations:** the desktop entry lists the MIME type of every format File › Open reads but PSD, PSB, `.ps` PostScript and Targa, `.ai`, `.ait` and EPS included, and the MIME package declares the types shared-mime-info lacks (VectorCraft documents and templates, `.ait`, Affinity), so file managers list VectorCraft under Open With for them, as Finder does on macOS. `the_linux_desktop_entry_opens_every_readable_format` in `apps/vectorcraft/src/main.rs` checks both files against `OPEN_EXTS`. On Debian 13, Ubuntu 24.04 and Fedora 42, `desktop-file-validate` accepts the desktop entry, `update-mime-database` accepts the MIME package, and `gio` registers the app for every one of these types. - **Architecture:** 19+ crates with enforced layering (`cargo xtask layers`). Every action is a command (~400 engine + ~50 UI). Undo is unlimited via structural sharing. `command.batch` runs several commands as one transaction. - **Automation:** - Variables: Update Data Set writes what the art holds into the active data set for the variables that data set holds, and keeps the data set's value for a variable whose objects are locked or inside a locked layer or group; `dataset.update {all: true}` also adds the other variables that the art reports a value for. - Variables: `dataset.select`, `dataset.next` and `dataset.prev` rewrite type and apply the other values on hidden objects and in hidden layers and groups, which stay hidden unless a visibility value shows them, so a layer shown later holds the selected data set's text; objects that are locked or in a locked layer or group are skipped. - Variables: `dataset.select`, `dataset.next` and `dataset.prev` name the area type and type on a path whose text they rewrote and that doesn't fit, in the reply's `overflow` key, as `text.setText` does. + - Variables: when no object is bound to a variable that the data set has a value for, for example after Import Data Sets… defines new variables without binding them, choosing the data set in the Variables panel or stepping to it with the panel's arrows shows a status message, and `dataset.select`, `dataset.next` and `dataset.prev` add the message to the reply as `warning`. - Variables: Lock Variables (`variable.lock`, in the Variables panel's bottom bar and menu) stops variables from being defined, deleted or renamed until they are unlocked, while objects can still be bound and unbound and data sets still change and apply; the lock is saved with the document. - Batch…: Override Save and Override Export name each file with the extension of the format the step writes, however the step spells the format (`.svg` and `SVG` give `.svg`, `png8` gives `.png`), in `action.batch`. - Actions panel (record/playback, persisted), generic parameter dialogs for every "…" command. @@ -540,10 +553,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Direct Selection (#1278):** clicking a segment picks its connection, with hollow endpoint anchors and only that curve's direction handles. Delete leaves the neighboring curves and appearance intact, opens/splits contours in one undo step, and another Delete removes the remaining selected path. A whole-path drag and deliberate anchor selection keep their existing behavior; egui frames and native control/art checked, OS mouse/visual QA pending. Where anchors of overlapping objects coincide, a click or drag takes the anchor of the selected object, also when another object lies over it (#1509, fixes #1508). Delete removes every selected anchor of a closed path (it used to remove the wrong ones), removes objects selected whole along with the selected anchors of others, and keeps the remainder selected so a second Delete removes it (#1674). In isolation mode Direct Selection and Group Selection pick only inside the isolated object (#1666). Escape cancels a Direct Selection drag (#1803, #1743). Double-clicking type (including type nested inside a group) switches to the Type tool and puts the caret at the clicked character. A path segment with a control point whose x or y is infinite or larger in size than `f64::MAX / 16` is measured by its control points, so its bounds hold the whole curve and the canvas check refuses an edit that leaves such a path selected (`path.create` included). With Direct Selection, the Pen and the anchor tools, a group, compound path or clip group selected whole shows the anchors of its paths filled, as a path selected whole does; the direction handles still show only on a path that is selected itself. Public references: [Adjust anchor point, handle, and bounding box display size](https://web.archive.org/web/20251114182206/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/adjust-anchor-point-handle-and-bounding-box-display-size.html) and [Drawing basics](https://web.archive.org/web/20231130064834/https://helpx.adobe.com/illustrator/using/drawing-basics.html) (archived copies). - `path.curvatureEdit`, `path.removeAnchor`, `path.convertAnchor`, `path.reshapeSegment`, `path.split`, `path.setHandle` and `path.insertAnchor` refuse a `subpath` that is not a whole number of 0 or more, and `path.split` refuses such an `anchor` or `segment`; without a `subpath` they edit subpath 0. + `path.curvatureEdit`, `path.removeAnchor`, `path.convertAnchor`, `path.reshapeSegment`, `path.split`, `path.setHandle`, `path.moveAnchor` and `path.insertAnchor` refuse a `subpath` that is not a whole number of 0 or more, and `path.split` refuses such an `anchor` or `segment`; without a `subpath` they edit subpath 0. `path.reshapeSegment` refuses a delta of 1e9 pt or longer, as `object.blend.spine.reshapeSegment` does, and `path.convertAnchor` and `path.freehand` refuse a point whose x or y is 1e9 pt or more in size. - **Group Selection (#2441):** a click picks one path of a compound path (its outline within the pick tolerance, else the innermost path whose area holds the click: the outer shape or a hole), Shift-click adds another, and a click on a selected path adds the compound path, as a click on a group member climbs to its group. A path selected this way moves, rotates and scales on its own; paint still goes to the compound path. - With Direct Selection, Shift pressed during the drag of a curved segment keeps both of its handles at right angles to the line between its anchors, on the same side and at the same length (`path.reshapeSegment {perpendicular}`). Shift held while any segment is dragged with the Anchor Point tool or the Pen with Alt does the same. A selected blend spine's segment dragged with the Anchor Point tool, or a curved one dragged with Direct Selection, bends the same way (`object.blend.spine.reshapeSegment`). + With Direct Selection, Shift pressed during the drag of a curved segment keeps both of its handles at right angles to the line between its anchors, on the same side and at the same length (`path.reshapeSegment {perpendicular}`). Shift held while any segment is dragged with the Anchor Point tool or the Pen with Alt does the same. With the Anchor Point tool, Shift held at the press on an anchor (or a selected blend's spine point) moves it, handles and all, instead of pulling out handles; Shift kept down keeps the move at 45° steps, and a Shift-click that doesn't move leaves the anchor as it was (`path.moveAnchor`). A selected blend spine's segment dragged with the Anchor Point tool, or a curved one dragged with Direct Selection, bends the same way (`object.blend.spine.reshapeSegment`). - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it for the Corners dialog, and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). A link toggle behind Corner Radius (the `singleCornerRadius` preference) switches the panels to a field for each corner of a live rectangle: Top Left, Top Right, Bottom Right and Bottom Left. Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two sides meet at an angle at an anchor that isn't smooth: curved sides too, trimmed to what the cut leaves of them (#1144). Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. With Direct Selection a click on a widget (no drag) selects its corner, as a click on the corner's anchor does, so the next drag on it rounds that corner alone; Shift-click toggles it (#1239). While a corner widget is dragged with the Selection tool the bounding box hides, so the rounding shows against the path alone (#1229). A round corner next to a curved side curves smoothly instead of sticking out of the shape (#1547, fixes #1512). View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. - **Blend spine Anchor Point tool (#2544):** on a selected blend, dragging a spine corner makes symmetric Smooth handles; the tool displays and picks existing spine handles when switched to, drags one independently or retracts it on click, and clicking a point with handles retracts both. The spine is edited live without moving its key objects. Windows native canvas checks and screenshots reviewed: symmetric and independent handles, corner/retraction, Shift constraints and perpendicular reshaping, tool switching, key preservation, Undo/Redo, save/reopen, hidden handles and overlapping Path/Blend priority (PR #2643). Behaviour reference: [public path-editing documentation](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html). @@ -573,6 +586,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Ctrl/Cmd+Alt-clicking an eye switches the other layers to Outline and the row's layer to Preview, or switches all layers back to Preview when the others are in Outline (`layer.outlineOthers`, `layer.previewAll`). Object › Arrange › Send to Current Layer returns the error "the target layer is locked or hidden" and leaves the selected objects where they are when the current layer is hidden or locked, or is inside a hidden or locked layer. Selected objects are deselected, the key object included, when a row drag moves them into a hidden layer or group, when `node.move` moves them into a hidden or locked layer or group, when Merge Selected moves them into a hidden or locked layer, when Collect in New Layer moves them into a new layer inside a hidden or locked layer, when Flatten Artwork moves them into a locked layer, and when applying a data set hides them. + Panel Options › Locate Selected Objects (beyond Illustrator, off by default): when the last selected object changes on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as Locate Object does, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off. - **Drawing aids:** Smart Guides and snapping (moving, with the Selection, Group Selection or Direct Selection tool, and resizing by the bounding-box handles with the Selection or Free Transform tool, Shift and Alt too: the dragged corner or side lands on the other objects' anchors and centres ("anchor", "center") or lines up with their edges and centres (a line and "align"); with Smart Guides › Spacing Guides, a moved selection that lines up with nothing along an axis lands as far from its neighbour as two other objects of its row or column are apart, or halfway between its two neighbours, the equal gaps marked; with View › Snap to Grid on, a moved selection lands on the grid instead, by whichever of its edges or its centre is nearest a gridline on each axis, #740; the Rotate, Scale, Shear and Reflect tools drag from the anchor they grab and snap the pointer the same way, so a corner dragged onto another object's anchor scales exactly onto it, #482; anchors dragged with Direct Selection: the one pressed on lands on other anchors, its own path's that stay put among them, on path segments or in line with them, the others following, Shift keeps 45° steps, and with Smart Guides off Snap to Point pulls it onto anchors; the Artboard tool snaps artboards, and their bleed, to other artboards, bleeds and art, the grid or whole pixels while moving, copying and resizing them, and the Transform panel shows and edits the active artboard's X/Y/W/H; drawn points, #506: hovering shows where the press goes, the point lands on the other objects' anchors, centres and paths ("anchor", "center", "path") or lines up with their anchors, edges and centres ("align"), the Pen's on the path being drawn too, near a construction guide through the anchor before it on that guide (Preferences › Smart Guides › Construction Guides and Angles), and with Shift kept to its 45° step or a square's diagonal it slides along that way into line; the targets are gathered once per document state, from the art in the window, and the anchors, centres and lines near the pointer are found by bisection, so hovering never rescans the document), guides dragged out of the rulers (#451: they snap as moved guides do, Shift to the ruler's ticks; with the Artboard tool they are artboard guides, which run across their artboard only and move, copy and delete with it, `guide.add {artboard}`) that the Selection, Direct Selection and Group Selection tools then pick and drag (#414: the selected guides highlight and move together, Alt copies them, Shift snaps the dragged one to the ticks, otherwise it snaps to pixels, the grid or the edges, centres (so the sides' midpoints) and anchors of the art and the artboards, or with Smart Guides off Snap to Point pulls it onto anchors; Shift-clicked they join the selected art, and Shift-added art keeps them, so guides and art are selected together in either order, Delete then deleting both in one step; the arrow keys nudge them, Delete deletes them, dragging one back onto its ruler deletes it, Lock Guides and Hide Guides leave them alone; `guide.list`, `guide.select`, `guide.move` and `guide.remove` reach agents), a right-click on either ruler or the origin box to pick the document's units (the current one checked; `document.setUnits`, one undo step, #528), and Draw Normal / Behind / Inside modes. Smart Guides: a point drawn with the Pen or a shape tool, and an anchor dragged with Direct Selection, snaps to where paths and ruler guides cross, labelled "intersect" (#1658, part of #1602; a moved selection's own anchors don't). A move that Shift keeps level, upright or diagonal stays on that line when it snaps, with the Selection, Group Selection or Direct Selection tool. It slides along the line until the selection lands on the grid or on whole pixels, lines up with the other objects or is spaced evenly with them, or until the line passes an anchor or crosses a ruler guide near the point the selection was grabbed by. A level or upright move snaps along its own axis only. A bounding-box handle dragged with the Selection or Free Transform tool snaps what it moves as a dragged point snaps (#2054). With View › Snap to Grid on, it snaps to the nearest gridline, and with Snap to Pixel on, it snaps to whole pixels. With Smart Guides off and Snap to Point on, it snaps to the other objects' anchors and the ruler guides within the Snap to Point distance. With Smart Guides and Snap to Point both on, it lines up with the ruler guides as well as the other objects. Shift still keeps the proportions, and Alt still scales about the center. @@ -604,6 +618,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Pathfinder (10 exact curve booleans; single-result shape operations retain source names and SVG IDs, #1293), Offset, Outline Stroke, Simplify, Clean Up, Split Into Grid, Divide Objects Below. With one group selected alone, the Pathfinder panel's buttons work on its members (among other selected objects a group still acts as one shape), and a greyed-out button says what it needs (#1450; behaviour reference: [combine objects using Pathfinder effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/combine-objects-using-pathfinder-effects.html); one plain path selected alone stays disabled, which the documentation doesn't settle). Split Into Grid takes the number, height or width, gutter and total of the rows and of the columns, Add Guides and Preview, and several selected paths become one grid painted as the topmost one (#1462, `object.path.splitIntoGrid`; behaviour reference: [divide or split objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/divide-or-split-objects.html); a typed height or width keeps the gutter and changes the total, our choice). Object › Path › Remove Anchor Points (`path.removeAnchors`) removes the direct-selected anchors without opening their paths (the Delete key still deletes them with their segments): the neighbours keep their handle directions and their facing handles are refitted so one cubic follows the two old segments, and straight sides stay straight. The Delete Anchor Point tool uses the same refit. The Control bar, the contextual task bar, the Properties quick actions and the canvas context menu offer it when anchors are selected. With anchors selected, the Control bar and the Properties panel also convert them to corner or smooth (`path.convertAnchors`), connect end points (Join) and cut the path at them (`path.cutAtAnchors`, also on the task bar and the context menu): a closed path opens there and an open one becomes one path per piece, each cut leaving one of its two coincident anchors selected so a drag pulls the path apart. In the Pathfinder panel a group selected alone counts its nested shapes, so an expanded stroked object keeps the Shape Modes enabled (#1642, #1635). - Divide uses open lines, bent paths and curves as cutting edges (#1307), preserving the frontmost filled face's appearance and holes. Engine tests cover implicit closure of filled open contours and unrelated objects; native automation confirms independent piece movement, one Undo/Redo, canvas/window captures and an exact saved-document read by a separate CLI process. The shared planar map retains its 4,096-segment cap and filled-area fallback; other Pathfinder operations are unchanged. - Type that Transform effects only move and copy (no scale, rotation, reflection or Random) exports as type in each place, and PDF export writes every copy as selectable, searchable text, when its characters are in solid colors without underline or strikethrough, the type object has no fills or strokes of its own, no inline graphics and no perspective, its transform does not scale or shear stroked characters, and the copies do not overlap. When the effect is on the type itself, the type can also have transparency, an opacity mask and raster effects. When the effect is on the group or layer holding the type, the type has no transparency or effects of its own and is not in a clipping path, the group or layer has no fill, stroke or Pathfinder effect of its own, and no group between them has a fill, stroke, Pathfinder or geometry effect. Type still exports as outlines when the effect stops its copies early, or when the copies would number more than 10,000 or take more than 20,000,000 bytes of document data, and so does other type under a geometry effect. + - Extrude & Bevel and Inflate treat strokes as outlined: each visible stroke builds a solid from its outline in its own paint beside the top fill's ([three-d.md](three-d.md#fills-and-strokes)). - Extrude & Bevel, Inflate and Rotate (Effect › 3D and Materials): live effects in the `three-d` crate with depth, twist, taper, solid or hollow caps, five original bevel shapes (width, height, repeat, spacing, inside, both sides), Inflate's volume, both sides, twist, taper and cap, Rotate's turned fills and strokes, Position presets, the rotation and light gizmos, SVG/PDF vector output and Expand Appearance; one 3D effect per object; covered by geometry, effect, canvas-versus-export, command and dialog tests ([three-d.md](three-d.md)). - Initial live Revolve (#605, #846): a portable geometry and shading crate (`three-d`), editable path and compound profiles, compact options with artboard rotation and light gizmos, SVG/PDF vector output and Expand Appearance that can trim covered faces. Open ends have continuous caps by default, shading is smooth with one to ten colored lights, and intersecting surfaces' visibility is approximate ([revolve.md](revolve.md)). - Live effects with previewing dialogs: Distort & Transform, Path, Convert to Shape, 15 Warp styles, Round Corners, Scribble, Effect → Pathfinder (all 10 operations, live on groups; several loose objects are grouped first, in one undo step), Color Adjustments (Brightness/Contrast, Curves, Levels, Hue/Saturation, Shift to Color, Temperature/Tint, on vectors, live type and embedded images), and raster drop shadow, glows and feather. SVG and PDF export keep live effects (geometry baked; SVG raster effects as filters). Zig Zag spaces its ridges evenly along each segment, so lines and curves get a regular wave in Corner and Smooth (#1558). Warp › Arc (the effect and Envelope › Make with Warp) bends in the object's real proportions: a circular arc with concentric edges and no fold-over at 100%, so Arc on art that isn't square draws differently from before (#1581, fixes #1578). `effect.apply` and `effect.setParams` give an error for a misspelt or wrongly typed effect parameter instead of running the effect with its default (#1623, #1592). Roughen with Smooth keeps turn-backs smooth instead of making cusps that draw as spikes (#1646, #1643). Scribble draws one zig-zag per region, with no lines across holes and notches; convex shapes are unchanged (#1651, #1648). On the canvas, in Expand Appearance and in exports, Effect → Pathfinder uses the glyph outlines of type in the group, and results painted like the type keep its opacity and blend mode. @@ -613,16 +628,15 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scribble (Effect › Stylize › Scribble…) has a Variation for each of Path Overlap, Curviness and Spacing ([Scribble options](https://helpx.adobe.com/illustrator/using/creating-sketches-mosaics.html)) (`overlapVariation`, `curvinessVariation`, `spacingVariation`), shown in its dialog and in the Appearance panel. A Scribble saved with the earlier single `variation` reads it as the Path Overlap and Spacing variations and draws as before. The angle is stored above -180° and up to 180°, so 270° is stored as -90°. - **Simplify feedback and component selection (#1272):** the existing tolerance dialog previews from the original interaction snapshot and shows original/new anchor counts. Preview off and Cancel restore the document and selection; OK is one Undo. A refit or Add Anchor Points clears component indexes only on paths whose geometry changes, keeping their objects selected whole and unchanged paths' components intact. Engine and real-egui frame regressions cover document/selection restoration and grouped paths. Public references: [Simplify benefits](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/simplify-path-benefits.html) and [advanced options](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/simplify-paths-advanced-options-overview.html). - Nearly unchanged appearance is expected when reducing points. Percentage/auto-simplify controls and Retain my latest settings are not implemented; the checklist is partial, without raising scores. + Nearly unchanged appearance is expected when reducing points. The checklist is partial, without raising scores. Simplify and Add Anchor Points record no undo step when they change no path, and a path they leave as it is keeps its live shape. The Simplify dialog also has Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path. The threshold is a slider from 0° to 180° and opens at 150°: an anchor whose corner is sharper than the threshold stays a corner, so moving the slider right keeps more corners, and the dialog sends `cornerAngle` as 180° less the threshold. While Preview is on, Show Original Path draws the paths as they were before the preview in a wide, faint band of their layer's color under the selection's outlines. -- **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches to the Selection tool (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). -- **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. A double-click on area type's bottom middle handle turns on Auto Size (#1940). Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches to the Selection tool (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). + Object › Path › Simplify opens a slider under the selection ([Manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html), [Auto simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/auto-simplify-paths.html)) with Auto-Simplify, a rail from the fewest anchor points to the closest fit, and More Options, which opens the dialog at the slider's tolerance. The rail's levels are VectorCraft's own scale (`object.path.simplify {level}`): level 50, where the slider opens, is 1 pt, and every 10 levels halve or double the tolerance, from 32 pt at 0 to 1/32 pt at 100. Auto-Simplify picks the lowest level whose tolerance is at most 1/400 of the selection's longer side, or level 100 when that side is under 12.5 pt. The dialog's "Open this dialog with these settings next time" makes the menu item open the dialog on the settings of its last OK. - **Devanagari shaping:** with an OpenType Devanagari font, Ka, virama and Ssa (क्ष) form one conjunct glyph, Ra and virama before a consonant (र्क) become a reph drawn after it, the i matra (कि) is drawn before its consonant, and Ka with a nukta is drawn like the precomposed क़ (U+0958), as [Microsoft's Devanagari shaping specification](https://learn.microsoft.com/en-us/typography/script-development/devanagari) describes. Each syllable is one cluster of its source bytes, and the arrow keys stop at its ends. A click inside a syllable drawn with several glyphs puts the caret at the syllable's nearer end, in point, area and path type. Tests: `crates/text/src/tests_devanagari.rs`; they print SKIPPED when no such font is installed. - **Vertical punctuation:** fullwidth `!` (U+FF01) and `?` (U+FF1F) use their nominal glyph upright when no vertical alternate is present, following the Tu fallback in [Unicode UAX #50 §3.1](https://www.unicode.org/reports/tr50/#vo). Code-built test fonts cover point and area type with and without `vert` alternates, retain the rotated fallback for a bracket and long vowel mark, and leave horizontal type unchanged. Tests: `crates/text/src/tests_vertical.rs`. - Free Distort's dialog (Effect › Distort & Transform › Free Distort…) shows a box in the proportions of the first selected object's bounds with a handle on each corner. Dragging a handle moves that corner. A handle focused by a click or Tab moves 1% of the box with each arrow key, and 10% with Shift. Reset puts the four corners back on the box. The preview and OK run `effect.apply`, or `effect.setParams` when the dialog edits an applied effect, and the Appearance panel's inline editor opens the dialog with Edit…. Behavior reference: Illustrator CC Help (2014, [PDF](https://help.adobe.com/archive/en/illustrator/cc/2014/illustrator_reference.pdf)), page 285 (PDF page 291). - **Kerning across style runs:** characters that differ only in fill, stroke, underline, strikethrough, overprint, character style name, leading, baseline shift, rotation, Character Alignment, kerning, or tracking that keeps or drops ligatures alike are shaped together, so restyling one character keeps the font's kerning pairs with its neighbors. A character with manual kerning that follows one with automatic kerning keeps the font's kerning with it (unless All Caps or Small Caps sets it as two letters, as ß becomes SS), and its value replaces the font's kerning after it. A ligature does not form across a change of style, and a change of font, size or OpenType features still shapes the characters apart. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) (public documentation). Tests: `crates/text/src/tests_typo.rs`, `crates/text/src/tests_bidi.rs`. -- **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches to the Selection tool (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). +- **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches to the Selection tool (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). The Character panel's Small Caps, Superscript and Subscript buttons and the panel menu's items of the same names turn small caps and the superscript or subscript position on and off for the selected type, or for the text the Type tool has selected (`text.setFormat` or `text.setRangeStyle` `{smallCaps, position}`), in Document Setup's proportions. Turning Superscript on turns Subscript off, and turning Subscript on turns Superscript off. A button or item shows as on when the first selected character (at a caret, the character before it) has its attribute. - **Paragraph alignment:** the shared Paragraph/Properties alignment row leaves every button unselected when the paragraphs it acts on differ. Auto resolves per paragraph; choosing an alignment uses the existing command. Headless paragraph_mixed_alignment_* regressions exercise mixed → Center → Undo, caret/uniform states, Unicode range boundaries, Auto/direction, split runs and grouped text. These regressions and full integration CI pass. Original captures confirm mixed → Center → Undo in the existing alignment-button layout. The [public Paragraph panel guide](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/paragraph-panel-overview.html) lists the seven controls, but does not specify mixed-state rendering. Other paragraph fields remain outside this change; scores and hours unchanged. For Auto Size area type in columns, the bisection for the frame's height runs on the lines of the one-column layout, and its result is checked with at most two layouts of the columns. When the text wraps around objects or does not fit the one-column layout, or when the check fails, the columns are laid out at every step of the bisection, as before. Typing at the start of a story of 50,000 characters in 2 columns took 1,670 ms a keystroke and now takes 292 ms (release build, `auto_height_in_columns_typing_timing`). @@ -631,6 +645,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The frames of threaded text share one Optical Margin Alignment setting: turning it on or off in one frame sets it in every frame, threading frames gives the thread its first frame's setting, and frames taken out of a thread keep it. Type › Optical Margin Alignment (`type.opticalMarginAlignment`) hangs the punctuation and letter edges at the ends of a type object's lines outside its margins: at the left of left-aligned lines, at the right of right-aligned lines, and at both ends of centered and justified lines, in point and area type of left-to-right paragraphs. Quotation marks, hyphens, full stops and commas hang wholly; asterisks, tildes, ellipses, en and em dashes, colons and semicolons hang by half; and A, V, W, Y, v, w and y hang by a tenth of their width. It is off by default and saved with the type object. The Paragraph panel menu's Hyphenation… (`ui.hyphenation`, `text.setFormat {wordsLongerThan, afterFirst, beforeLast, hyphenLimit, hyphenationZone, hyphenateCapitalized}`) sets each paragraph's hyphenation limits: the shortest word that breaks, the fewest letters on each side of the hyphen, the most hyphenated lines in a row, a zone at the right edge where the Single-line Composer breaks before a word instead of hyphenating it, and whether capitalized words break. The defaults are words longer than 5 letters, 3 letters on each side, no limit or zone, and capitalized words hyphenated; paragraph styles and the native file keep the options. + The Tabs panel's ruler is numbered in the General unit with the canvas rulers' label steps and a tick every tenth of a step. With the panel menu's Snap to Unit on, or Shift held, a tab stop placed by a click on the ruler or dragged on it lands on the nearest tick (`text.tabs.set`). The Tabs panel menu's Clear All Tabs (`text.tabs.clear`), Delete Tab and Repeat Tab (`text.tabs.set`) can be chosen while the panel's ruler shows tab stops. Delete Tab removes the stop selected on the ruler. Repeat Tab replaces the stops after the selected stop with up to 20 copies of it. The copies are spaced by the selected stop's distance from the stop before it, or from the paragraph's left indent when it is the first stop, and no copy is placed at 2,000 pt or beyond. Clear All Tabs removes every stop, so the default stops every ½ inch apply again. - **Interface languages, vertical type:** Preferences ▸ User Interface (or VectorCraft ▸ Language on macOS) picks Automatic (the system locale) or a registered language, persisted as `interfaceLanguage`. Translations come from per-language catalogs (`i18n/*.tsv`): Traditional and Simplified Chinese, Japanese, German (every `de-*` locale), Spanish (neutral international Spanish, for every `es-*` locale), French (every `fr-*` locale), Italian (every `it-*` locale) Russian (every `ru-*` locale) and Ukrainian (every `uk-*` locale) cover the whole interface, Czech every menu label; Czech, German, Greek, Spanish, French, Hungarian, Italian, Japanese, Korean, Vietnamese, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian and Finnish also translate status-bar and error messages as they are shown (`@msg` templates, every message literal tested; the messages themselves stay English for agents); untranslated text stays English. Japanese and Chinese glyphs come from the craft-fonts build input (release builds) or the installed fonts, Czech, German, Spanish, French, Italian, Russian and Ukrainian ones from the bundled UI fonts. The web app follows the browser's languages (or `?lang=`). The Basic toolbar's Type button holds Vertical Type in its flyout. Vertical Type, Vertical Area Type and Vertical Type on a Path create vertical text (columns right to left, upright CJK glyphs and marks with `vert` alternates, Latin and longer numbers on their side, two- and three-digit numbers set as tate-chu-yoko in one em of the column (kept whole when justified), upright glyphs centred on the column (tracked or justified too), point type's anchor on the first column's centre line); kinsoku applies to horizontal and vertical Japanese (Paragraph panel › Kinsoku Set, `text.setFormat {kinsoku}`: Hard, the default, keeps closing marks, iteration marks, the prolonged sound mark and small kana off the line start and opening brackets off its end; Soft lets 々, ー and small kana start a line as JLREQ's level 3 rules do; None turns it off), and justified Japanese lines spread their room between characters (not inside Latin words); Paragraph panel › Mojikumi Set (shown with Preferences › Type › Show East Asian Options, `text.setFormat {mojikumi}`): None or Line-end Punctuation Half Width (new type's default, as in Illustrator; older documents and imported text keep None) shares one half-em space between consecutive punctuation, sets a closing mark ending a line half width and an opening bracket starting a line flush with its start (a paragraph's first line at its first-line indent, JIS X 4051's principle in JLREQ 3.1.5), and puts a quarter em between Japanese and Latin letters or digits; Paragraph panel menu › Top-to-Top / Bottom-to-Bottom Leading measures leading from em box top to top (area type's first line touches the frame) or from baseline to baseline (new type in a Japanese interface starts top to top, with em box centre character alignment, #432); Paragraph panel menu › Burasagari None / Regular / Force (`text.setFormat {burasagari: "none"|"standard"|"forced"}`) hangs an East Asian comma or full stop (、。,.、。) ending an area type line outside it, Regular (new type's default) when it doesn't fit and Force always (the rest of the line then fills the measure; closing brackets and Latin punctuation don't hang); Character panel menu › Character Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {charAlign}`) lines characters smaller than the largest on their line up on the Roman baseline, the em box top/right, centre or bottom/left, or the ICF (ideographic character face) top/right or bottom/left, from the font's BASE table or, without one, the average ink box of some ideographs and kana; Proportional Metrics (the same menu; `{proportionalMetrics}`) sets full-width glyphs on the font's proportional widths (OpenType `palt`) in horizontal type and upright glyphs on its proportional heights (`vpal`, shaped top to bottom; fonts without vertical metrics keep their cells) in vertical type, and Line-end Punctuation Half Width takes nothing more off the punctuation they re-spaced; Type ▸ Type Orientation switches existing text; caret, selection, hit testing and arrow keys follow the writing direction. Vertical text exports to PDF as real text and to SVG as outlines. The interface is available in Polish (`pl`): menus, panels, dialogs and messages, with one/few/many plurals; AI-drafted, native review pending (#1498). - **Transparency:** opacity masks (clip/invert/disable/link), exported as SVG `` and PDF soft masks. The constant alpha soft mask that PDF and `.ai` export draw a CMYK page with transparency through is white, so applications that read every soft mask by its luminosity show the page too (#1359, part of #1286). @@ -650,11 +665,14 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own, and regions they bound merge without seams where the lines cross at rounded coordinates (#893); filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points is refused with advice rather than running out of memory, an image over 64 megapixels is traced scaled down to that size (aspect kept, paths at the image's own size) and one over 192 megapixels is refused, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image (a crop box on the image, starting on its part over the artboard, dragged by its handles or inside it, the outside dimmed, with X/Y/W/H, Apply and Cancel in the Control bar, Enter and Escape, #734; `object.cropImage {rect}` for agents, `{trim: true}` cuts an image to its pixels that aren't fully transparent, pixel for pixel) and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), View, the Image Trace panel and Expand, plus Release in Properties; the five View modes (Tracing Result, with Outlines, Outlines, Outlines with Source Image, Source Image) redraw a trace on screen without tracing again, are saved with it and `imageTrace.setView` sets them, while exports and Expand keep the result; the panel's Advanced section is a header that stays open or closed as it was left (part of #641); Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More), Automatic (flat art with its own colours, else Full Tone; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror). A single selected mirror repeat shows a prominent axis with a center move handle and two rotation handles. Drag the line or center to change spacing, or an end to change angle; Shift snaps rotation to 45°. The original artwork stays in place, the reflected copy previews live, Escape cancels and each drag takes one undo step through `object.repeat.options`. Controls follow zoom/view rotation and hide with edges or the bounding box. Engine and headless canvas regressions passed for gestures, history and visibility; native move, rotation and Escape screenshots were reviewed. [Public mirror-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-mirror-repeat-options.html). Object › Expand turns radial, grid and mirror repeats into groups of their instances (#1765, #1756). - Create Strokes uses exact squared Euclidean distances and Guo–Hall thinning in bounded per-blob crops. Maximal-disc pruning, split-crossing merges and degree-two joins simplify its skeleton graph. The whole-blob width rule and ink fitting remain; 46 code-drawn inputs measure ends and junctions in [`image-trace-quality.md`](image-trace-quality.md#centre-lines). Junction degrees measure 44/45 correct in each input variant; remaining spurs are recorded. This is a measured skeleton improvement; the Image Trace score, missing per-feature selection and width controls, and estimates remain unchanged. Live Paint Gap Options (Object › Live Paint › Gap Options…, `livePaint.gapOptions`): with Gap Detection on, paint stops at the gaps that run from a loose end of a path to the nearest path, up to Small (3 pt), Medium (6 pt), Large (12 pt) or a custom size; Close Gaps With Paths adds an unpainted path across each gap; Preview applies the options live and draws the gaps in the Gap Preview Color. The options are saved, copied and undone with the group, and Merge keeps the bottom group's options when its Gap Detection is on, or else turns Gap Detection on with Small when another merged group has it on. When Gap Detection is off in every merged group, it stays off. + Double-clicking the Live Paint Selection tool opens its Tool Options ([Live Paint Selection tool options](https://web.archive.org/web/20250904012025/https://helpx.adobe.com/illustrator/using/selecting-objects.html)): with Select Fills off, a click selects an edge instead of a face; with Select Strokes off, Alt-click selects a face instead of an edge; Color and Width set the color and width of the highlight on the face or edge under the pointer (red and 4 px by default). The options last across tool switches and are saved with the preferences (`tool.setOption {tool: "livePaintSelection"}`). Window › Blend opens the Blend panel: Make, the selected blend's Spacing and Orientation (with no blend selected, the options new blends start with), Reverse Front to Back, Reverse Spine, Replace Spine, Expand and Release, each running its Object › Blend command. Make is dimmed until two or more objects are selected. Spacing and Orientation are dimmed until a blend or two or more objects are selected, and the other buttons are dimmed until a blend is selected. + Objects on Path (#2545): a click with the Objects on Path tool (in Edit Toolbar's Modify section and the Blend tool's flyout; Object › Objects on Path › Attach and the context menu with two or more objects selected choose it) attaches the selected objects to the path clicked, open or closed, in an Objects on Path group with the path at its bottom. The objects go along the path column by column from left to right, spread evenly from its first anchor (the last one sits on the end of an open path), each turned to the path at its attachment point; Pivot and Rotate set where each one attaches and how far it tilts (`object.objectsOnPath.attach`, `object.objectsOnPath.options`). Editing the path moves the objects, an object moved on its own goes back, objects moved into or out of the group in the Layers panel join or leave the path, and Object › Objects on Path › Expand leaves a plain group. The group saves and reopens live and exports as plain art. The Space, Move All, Rotate All and Select/Move widgets, Detach, the tool's options dialog and the Properties panel section are missing. - **Paint and appearance (M3):** - **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries and five gradient libraries in a library panel, saved as `.vcswatches`, `.gpl`, swatch exchange (`.ase`) or CSS, and loaded from `.vcswatches`, `.gpl` and `.ase` files (`.ase` both ways: RGB, CMYK, Lab and Gray; global, spot and process; groups) and from color books (`.acb`, read only: the RGB, CMYK or Lab colors of a book such as a Pantone book a user owns, named with its prefix and suffix, spot unless it says process, #831); `swatch.library.copyToUser` copies a loaded library into the User Defined folder without replacing a file, and a file with the same extension and bytes as a User Defined library opens as that library. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate. - **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel shows a selected colour in its own model and, with nothing selected, the new-art defaults in the mode picked last, which it keeps between sessions; Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). An ICC CMYK profile converts straight into the RGB working space (not through sRGB, so a wider space such as Wide Gamut RGB keeps colours sRGB can't hold) with the colour settings' black-point compensation, on the canvas and in RGB exports alike (the built-in Generic CMYK compensates both ways, so RGB black separated to a rich black displays as black again). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB greys separate into four-colour greys and a rich black as Illustrator does, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`). View › Proof Setup › Color blindness – Tritanopia-type turns Proof Colors on and proofs the canvas with the tritanopia simulation of Brettel, Viénot and Mollon (1997). The Separations Preview panel's Proof Setup list offers the same target (`view.proofSetup {target: "tritanopia"}`). Grays keep their value. + - **Color Picker layout (#2008):** a centered draggable header, equal-width actions above aligned HSB/RGB/Hex and Lab/CMYK fields, compact field and slider, and warnings below the preview. No horizontal scrolling; narrow windows stack the sections with vertical scrolling. Tests in `dialogs/color_picker.rs` cover actual pointer/key input, typed values before OK/Enter, Cancel/Escape rollback, one Undo step, mode-size stability, warnings and layout at two UI scales. The screen sampler sits above the field and the upstream two-grid Tab order is retained. AccessKit regressions check the action names and each channel slider's displayed value, units and range. German and enlarged English UI renders were reviewed locally; no reference images are shipped. This is a layout improvement, with no change to scores or remaining-hour estimates. - **Eyedropper sources (#1251):** ordinary and Shift clicks, Shift+Alt appearance append, raster pixels and gradient-stop sampling can read visible locked/template art and sources outside isolation. Sampling leaves the source and selection intact; Alt reverse still uses editable hits, and hidden art stays excluded. Engine/tool/hit regressions cover the editing boundary, color models and one-step Undo/Redo. The general object/image workflow is described in [public HelpX](https://helpx.adobe.com/illustrator/using/tool-techniques/eyedropper-tool.html); the lock/isolation expectations come from the user report and these regressions, without a new full-parity measurement. - **Eyedropper colors in a CMYK document (#2276):** a CMYK image (a four-component JPEG, or an 8- or 16-bit chunky CMYK TIFF) gives its ink amounts as they are, and an RGB image's pixel or an RGB color given to `paint.setFill`, `paint.setStroke`, `paint.sampleColor` or `swatch.new {color}` (hex input and gradient stops included) is separated through the color settings' CMYK working space and intent, as Document Color Mode converts it. With the default Generic CMYK, RGB 83/170/223 separates to C59 M12 Y3 K0, where the profile-free formula gave C63 M24 Y0 K13. - **RGB input to other commands in a CMYK document:** type colors (`text.create`, `text.setStyle`, `text.setRangeStyle`), a Shape Builder hex fill, `paint.editGradient` stops, freeform gradient points, gradient mesh points (the Mesh tool gives a new point the fill's color in its own model), the Symbol Stainer's color and the swatch commands (`swatch.new {colors}`, `swatch.newGroup`, `swatch.editGroup`, `swatch.edit`) separate RGB through the color settings as `paint.setFill` does: with Generic CMYK, `text.setStyle {fill: "#53aadf"}` gives C59 M12 Y3 K0. A color a swatch already has keeps its model, and a swatch color given with `mode` is converted into that mode only. @@ -668,6 +686,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In the Brushes panel, Shift-click selects a range of brushes and Ctrl/Cmd-click adds or removes one. Delete Brush and Duplicate Brush then act on all of them (`brush.delete {names}`, `brush.duplicate {names}`). - **Appearance:** the Appearance panel's selected row drives every paint, stroke, gradient and transparency edit (`item` on the commands); effects apply to one fill or stroke; per-item Opacity popups, whose blend-mode list and opacity slider stay open inside them (#430; the Control bar's Stroke popover too); Mixed Appearances, Layers target dots and basic-appearance rules. Effects can be reordered, moved between items and copied by dragging; Show All Hidden Attributes; clicking an effect edits it in place; the object thumbnail drags onto art; effects render on type, images, symbols, blends, envelopes, meshes and repeats, and per-item raster effects export. Groups, layers and type have their own fills, strokes and effects (Contents and Characters rows); the Layers panel's target circles target layers, groups and objects; Expand Appearance turns fills, strokes, effects and brushes into objects. Fill and stroke paint (Fill, Stroke, None, Apply Last Color and Apply Last Gradient, also on characters selected with the Type tool), the Stroke panel's options, gradient and freeform point edits, Swap Fill and Stroke, Default Fill and Stroke, the Eyedropper, and the Appearance panel's item edits, Clear Appearance, Reduce to Basic Appearance, Remove Item, item reordering and Move Appearance record no undo step when they change nothing. + An image's own fills and strokes draw the shape that a Convert to Shape or Outline Object effect on them gives them (the image's box or its frame, reshaped by the effects after it), under or over the image as its Contents row says, on the canvas, in exports and through Expand Appearance; new fills and strokes on an image go under it. Without one of those effects they draw nothing, and Use Preview Bounds measures an image by its frame. A geometry effect on one of type's own fills or strokes reshapes the whole outline that the fill or stroke paints, on the canvas and in exports; PDF, SVG, EPS and the other vector exports write such type as paths. On type that holds inline graphics, those effects are drawn and exported only when the type has a geometry effect or perspective of its own. The Appearance panel's inline effect editor labels each parameter as the effect dialogs' generic fields do, without the colon ("Max. Radius", "Channel 1", "Create New Fields by"). Roughen's and Zig Zag's Points, Offset Path's Joins, Inner Glow's Source and the menus of Radial Blur, Smart Blur, Sprayed Strokes, Glass, Mezzotint, Halftone Pattern, Grain, Texturizer and De-Interlace are dropdowns with the dialog's labels that send the dialog's values, and a plug-in's choice is a dropdown of the plug-in's values. Revolve's edge, Extrude & Bevel's bevel, every Warp style's orientation, Rasterize's Color Model, Background and Anti-aliasing and the channel of Levels and Curves are dropdowns too, with the labels their own dialogs show. `effect.apply` and `effect.setParams` refuse a Levels or Curves `channel` other than `rgb`, `red`, `green` or `blue` (or `r`, `g` and `b`, in any letter case). @@ -692,6 +711,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A font family removed while the app runs leaves the font menus when the app scans the font folders again (when its window comes to the front after a font folder changed, or Refresh Font List), also when type had used it: that type then draws in the fallback font and Find Font lists the font as missing, until the font is installed again and the folders are scanned. - **Files (M4):** - PDF export and print composition use the optional shared guarded writer ([pdf-backend.md](pdf-backend.md)); app drawing and output policy and desktop printer submission remain in their existing layers. The shared reader keeps the app-owned import adapter; synthetic tests cover layer and overprint state across windows, long operands, inline images, failed decoding, document limits and incomplete tails. Empty and populated metadata key presence is regression-tested, and CI checks the immutable backend source. + Invisible text in a PDF (rendering mode 3, which carries a scanned page's recognized text over the scan) opens as type with no fill or stroke, a run of its own beside visible text on the same line; text that can't come in as type (opened as outlines, Type 3 fonts) is left out with a warning. PDF export, and printing, write characters with no fill or stroke as real text in rendering mode 3, so they draw nothing but stay selectable and searchable, also in PDF/X-1a and PDF/A-2b (#2675, `pdf/src/tests_import_fidelity.rs`, `pdf/src/tests_realtext.rs`). A PDF, or a `.ai` read through its PDF part, whose spot inks have the same values but different names opens with a spot swatch for each ink. The solid fills and strokes of paths and type, and the stops of gradients on paths, link to the swatch of the ink they are painted in, the points of a gradient mesh in one of these inks keep the ink's color, and PDF export writes each of these inks as its own separation (`pdf/src/tests_import_color.rs`). Paint in these inks inside pattern cells, soft masks and type 3 glyphs, and gradients on type in these inks, still import as RGB. Type in one of these inks can also import as RGB when type in another Separation or DeviceN ink is shown with no path drawn between them. - `.vectorcraft` (lossless JSON, compressed, atomic saves, save down to v1), Save As with a format chooser, Save a Copy, Revert, templates, Data Recovery after a crash (browser tabs hold their copies with Web Locks too, so a background tab's copies are never taken for a crash's, and a tab repairs copies another removed when it resumes: #367), background save and export. The desktop app writes its warnings and errors (graphics adapter, a lost graphics device, panics the guard recovered from) to standard error and to `logs/vectorcraft.log` next to the preferences, the two previous runs kept and each file capped at 16 MiB, so a launch without a terminal still leaves something to attach to a bug report (#465). Native documents with a lot of path data (traced or generated art, in layers, symbols or patterns) are saved as compact JSON, about a fifth of the size; small documents stay pretty-printed (#1492). Saving to a network drive on macOS falls back to a plain fsync when the share refuses a full flush (#1625, part of #1620; not confirmed on a real share), and a save still succeeds when a folder refuses the temporary file, the rename over the document or copying permissions: the content is written elsewhere first and copied in, and a failed copy keeps the temporary file and names it (#1649, part of #1620). A document opened by a relative path finds its relatively linked images, and `vectorcraft-cli convert` lists what reading the input left out as `importWarnings` (#1606, fixes #1604). A name typed in the desktop save panel without the file type's extension gets it, and when a file of that name exists, which the panel did not ask about, Save, Save As, Save a Copy, Save as Template, the exports and every other write through a save panel ask before replacing it (dialog `replaceFile`; Cancel writes nothing). @@ -726,7 +746,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - EPS and PostScript import keeps a CMYK image's ink amounts, as PDF import does: the samples of `image` and `colorimage` in a CMYK color space, and of a CMYK JPEG read through `DCTDecode`, come in as a CMYK TIFF, read through the image's Decode array, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask (`crates/eps/src/import/tests_images.rs`). Such images came in as RGB PNGs. - EPS and PostScript import reads image data through `CCITTFaxDecode`: Group 4 (ITU-T T.6) and Group 3 one-dimensional and mixed (ITU-T T.4) data, with the filter's `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1` parameters, decodes to 1-bit rows for `image` and `imagemask`. Damaged data keeps the rows decoded before it (damage in the first row is a PostScript `ioerror`), and parameters out of range or past the 256 MiB limit on decoded data are refused (`crates/eps/src/import/tests_images.rs`). Reading such a file stopped at an error naming the filter, and the file opened from a fallback, such as its preview or the art drawn before the image, or did not open. - EPS and PostScript `.ai` import undoes the TIFF predictor (`/Predictor 2`) of `FlateDecode` and `LZWDecode` data at 1, 2, 4 and 16 bits a component as well as 8: each component adds the same component of the pixel to its left within its bit width, 16-bit components add as big-endian numbers, and each row starts again (ISO 32000-1 §7.4.4.4; `crates/eps/src/import/tests_images.rs`, `crates/engine/src/cmd/fileio/tests_epsimport.rs`). At those depths the image drew the stored differences instead of its samples. - - DXF control-point SPLINE import honors its closed flag (#1299 follow-up after #1320 fixed export), including rational curves; open curves whose endpoints meet stay open. Own-fixture regressions cover controls/knots, fit-point fallback and all export versions (`crates/cad/src/import/tests.rs`, `crates/cad/src/tests.rs`); native save/read checked; CIRCLE/ARC fitting, CNC preset and VCarve QA remain pending. + - DXF control-point SPLINE import honors its closed flag (#1299 follow-up after #1320 fixed export), including rational curves; open curves whose endpoints meet stay open. Own-fixture regressions cover controls/knots, fit-point fallback and all export versions (`crates/cad/src/import/tests.rs`, `crates/cad/src/tests.rs`); native save/read checked. Circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE, and a non-circular ellipse keeps the existing fallback (`crates/cad/src/tests.rs`); CNC preset and VCarve QA remain pending. - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. - File › Place with Bounding Box (`file.place {crop: "bounding"}`) measures the art that shows, with its strokes and effects, as an export does: hidden objects, guides and template layers do not count, a group whose only part on the page or artboard is hidden is not placed, and symbol instances are measured by their art, for `at`, `rect`, the place cursor and `file.place.info` (`crates/engine/src/tests_place.rs`). @@ -744,7 +764,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - In the Links panel, Shift-click selects a range of links and Ctrl/Cmd-click adds or removes one. - Linked files another app changes while their document is open follow Preferences › File Handling › Update Links, as they do when it opens: Automatically reads them again (an Update Links undo step), Ask When Modified offers to, Manually leaves them modified in the Links panel. The desktop app compares the active document’s linked files by size and modification time every two seconds and when its window comes back to the front, on a worker thread; a file still being written is tried again (`links.updateChanged`). - Import and paste, 2026-10-13: a multi-artboard `.ai` with notes beside its artboards opens from its editing data, a page's art past its artboard no longer lying over the page before it (#1528); a `.ai` gradient whose stops are listed upwards keeps each midpoint on the stop that starts its part of the ramp (#1530); SVG text on a path follows basic shapes (circle, ellipse, rect, line, polyline, polygon) as their SVG 2 equivalent paths (#1531, fixes #1527); PDFs whose alpha soft masks are drawn as images import with the mask instead of empty art (#1551); EPS and PostScript type set in Type 42 (TrueType) fonts imports at its size instead of 1000 times too large (#1553); PDF and EPS import keep a clipping path whose bounding box covers the page but whose shape doesn't (#1544, fixes #1542). Opening or placing a file with an image too large to decode says so, and the Links panel shows it on the row (#1540, part of #1479). Paste takes a PDF or EPS another app copied as editable vector art: from the macOS pasteboard (with SVG), EPS on Windows beside PDF, and `.eps` files copied in a file manager, with the new command `clipboard.importEps` (#1538, fixes #1499). - - A `.ai` or `.ait` file copied in a file manager pastes as its art: one that holds a PDF pastes as a copied `.pdf` file does, and one saved as PostScript pastes as a copied `.eps` file does. + - A `.ai` or `.ait` file copied in a file manager pastes as its art: one that holds a PDF pastes the objects of its editing data, and one saved as PostScript pastes as a copied `.eps` file does. + - A copied `.ai` or `.ait` file that holds a PDF pastes the objects of its editing data as File › Open reads them: every layer's objects go into the active layer in their stacking order, with their names, hidden objects and type objects, instead of the PDF page's art with its type as outlines. When the editing data can't be read, the file pastes its page as before (`clipboard.importPdf {editingData}`). The objects of a hidden layer come in hidden, from a pasted EPS too. - Import and export, later 2026-10-13 merges: SVGs that move objects with a CSS transform (`translate(100px, 0)`, `rotate(45deg)`) or style type with the `font` shorthand import as drawn (#1565); SVG symbols whose shapes use percentage lengths import at the size and place they are drawn, the percentages being of the symbol's `viewBox` (#1596); Inkscape's flowed text (`flowRoot`) opens as area type in its rectangle, a paragraph per `flowPara`, instead of being dropped, and a region that can't be read is left out with a warning (#1569, fixes #1568); the warning for an unsupported SVG filter names the filter, its primitives and the object, and says the object is drawn without it (#1599, fixes #1598); the pages of an Inkscape multi-page SVG become artboards, named by their labels (#1603, fixes #1601); SVG export with CSS classes or style entities stays fast in documents with many distinct styles (#1567); PDF and `.ai` import: evenly letter-spaced or tightened type on a path keeps its length along the path instead of closing up to the font's advances (#1586), and type on a path whose stroke is written glyph by glyph comes in as one text object with its stroke, not one object per glyph (#1585); the ICC profiles embedded in JPEG, TIFF and PSD exports have every tag on a 4-byte boundary (ICC.1 §7.1.2), so strict readers accept them (#1589, fixes #1584); GIF, PNG-8 and other indexed exports find each pixel's palette colour through an index instead of a scan, with identical output (#1576); a zero-length subpath draws its round cap as a dot and its projecting cap as a square, so dots in imported `.ai` and SVG files show (#1619, fixes #1613). - Files and untrusted input, 2026-10-14 merges: EPS import: a stitched shading keeps its hard colour changes (#1654, #1653). WMF/EMF import refuses an oversized embedded PNG or JPEG from its header, before any pixels are decoded (#1776). PDF open no longer takes exponential time on a crafted name tree with shared nodes when it looks for the editing data (#1781). The size limits on a native file's embedded data also apply to files read from memory, not only streamed ones (#1783). Saving over a private file on Unix no longer leaves a readable temporary copy beside it while the file is written (#1778). An Export for Screens suffix can no longer place files outside the export folder (#1777). Package refuses a folder where it would overwrite the open document or one of its linked files (#1786). ruzstd 0.9.1 fixes a decompression bomb (RUSTSEC-2026-0344) reachable from EPS/`.ai` and Affinity import (#1807). File Info dates are stamped only after a save succeeds, so a failed save no longer changes them (#1774). Linked files that change during a drag are updated after the drag instead of being missed (#1773). - **Fields, search and window, 2026-10-14 merges:** Fields commit what was typed when you click away or move to another field, as Enter does; Escape still discards it (#1787). Up and Down move through the command search results and Enter runs the highlighted one (#1798, #1757). Slider rails show on Medium Dark (#1808, #1662). On Windows the custom title bar's window stays truly borderless, so the pointer lines up with what is drawn on systems where the hidden caption offset it (#1791, #1758; awaiting the reporter's confirmation). @@ -795,6 +816,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Smart Blur modes:** Effect › Blur › Smart Blur… has a Mode menu with Normal, Edge Only and Overlay Edge (`blurMode`: `normal`, `edgeOnly` or `overlayEdge`; an effect saved without it draws as Normal). Edge Only draws the edges in white on black, and Overlay Edge draws them in white over the Normal blur. A pixel is on an edge when one of the pixels the search reads within Radius of it differs from it by more than Threshold in a channel and its channels, alpha included, add up to at least that pixel's. The search reads neighbors as the Normal blur does, kept within Radius, and always the four nearest pixels, so a color step gives a line about as wide as Radius, and at least one pixel wide, on the side with the larger sum (lines on both sides when the sums are equal). The white and the black keep each pixel's coverage. Behavior reference: [Summary of effects](https://helpx.adobe.com/illustrator/using/summary-effects.html). - **Dragging objects with raster effects when zoomed in (#2558):** during a drag with a tool on the canvas, the renderer draws filtered content (Gaussian Blur, Feather and the Photoshop-style filters) within 1,000,000 pixels, at a lower resolution where it would need more, unless it can draw the content from an earlier frame's raster. In the desktop app it does the same for drop shadows, outer glows and inner glows. No raster made that way is kept. The frame after the drag renders them as a still frame does, and a dialog's preview, exports and printing render as before. `zoomed_drag_perf` times a drag's frames at 100% to 6400%. +- **Dragging other art over a wide blur (#2558):** an effect raster too large to keep whole (a wide blur, a shadow or glow, or any blur zoomed in) is cropped to what can show in the view, or made at a lower resolution and resampled to the view's pixels, and kept while the view stays the same, so dragging other art over the object draws its effects from the still frame instead of re-rendering them at the drag's lower resolution. A drag stays on the render worker once the worker drew the frame shown, since only that renderer holds the rasters. `tests_viewraster` covers each effect, and `a_drag_over_a_wide_blur_draws_the_blur_from_the_still_frame` the canvas on and off the worker. Not yet: a worker frame shows one display frame after the overlays, and the first frame of an interaction can land on the renderer that has not made the rasters yet (follow-up: render every canvas frame on the worker, waiting briefly for fast ones). - **Moving objects with raster effects (#1257):** during a drag or a dialog's preview, an object whose content only moved draws its cached drop shadows, outer glows and filtered content (Gaussian Blur, Feather and the Photoshop-style filters) from the rasters of an earlier frame at the nearest whole pixel, without running the effects again. The renderer first draws the moved content where the old content lies in its raster and compares the pixels. De-Interlace runs again. The frame after the drag runs the effects again and draws what a fresh renderer draws; on the desktop, the canvas renders that frame on the render worker. `texture_drag_perf` times a drag's frames and the frame after it. @@ -810,8 +832,15 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Blend, mesh and envelope numbers given as text:** `object.blend.make` and `object.blend.options` (`steps`, `distance`, `value`), `object.envelope.makeWithWarp`, `resetWithWarp` and `options` (`bend`, `h`, `v`, `horizontalDistortion`, `verticalDistortion`), `object.envelope.makeWithMesh` and `resetWithMesh` (`rows`, `cols`, `columns`), `object.envelope.options` (`fidelity`), `object.mesh.create` (`rows`, `cols`, `columns`, `highlight`) and `object.mesh.setPointColor` (`opacity`) refuse a value other than a number or null, such as `"8"`, and change nothing. `object.mesh.create` refuses an `at` that is not `[x, y]`. +- **Exporter plug-ins (G17):** a WebAssembly plug-in of kind `exporter` adds a write-only file format. File › Export › Export As lists it after the built-in formats, with Use Artboards greyed out (the plug-in writes the whole document) and its parameters in a generated dialog once the file is picked; `document.export` writes it by its format id, `plugin.`, or by one of its extensions, and built-in formats keep theirs. The plug-in is given the native file's JSON (large images without their data) and `_context` (`mode`, `extension`, `name`), with 10 G instructions plus 4,000 per byte of input and 300 s, and Background Export's Cancel stops it between two slices of that budget. A decline or invalid output writes nothing; its warnings come back with the export's. Regressions: `crates/engine/tests/plugin_export.rs`, `crates/plugins/tests/abi.rs`, `crates/ui-egui/src/dialogs/tests_plugin_export.rs`. Scores and hours unchanged. + +- **Plug-in parameters as their manifest presents them (G17):** each parameter may have a `label`, a `unit` shown after its value, `help` on its label and a `helpUrl` page opened from a button, a `group` (sections that fold, after the parameters outside any group) and a `visibleWhen` that shows it only while the checkboxes and choices it names have one of the listed values (a hidden parameter still goes to the plug-in). `string` and `numberList` parameters join number, int, bool and choice, and a plug-in declares up to 256 parameters, at most 64 outside groups. The filter, live-effect and exporter dialogs use these keys, and the Appearance panel's effect editor the labels, units, help and conditions; hosts from before them ignore them. Regressions: `crates/plugins/src/dialog.rs`, `crates/plugins/src/manifest.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`, `crates/ui-egui/src/panels/appearance.rs`. Scores and hours unchanged. +- **Live-effect plug-ins read their object's paints (G17):** a live effect is given the object's `fills` and `strokes` as a filter gets them, read only, and `_context.item` (`"object"`, or the fill or stroke whose own effects hold it); the result is cached by paint too, so a change of paint runs it again. Regressions: `crates/engine/src/tests_plugins.rs`, `crates/plugins/src/effect.rs`. Scores and hours unchanged. + - **Plug-in effects after a plug-in changes:** when a plug-in is installed for the first time, installed again or removed (`plugin.install`, `plugin.reload`, `plugin.remove`, File › Open of a `.wasm` file, the Additional Plug-ins Folder preference), the next frame the canvas draws uses the plug-ins then installed for objects with a plug-in effect and their raster effects, for the blends, envelopes and repeats that show such objects, and for pattern tiles and symbol instances whose art holds one. +- **Effect art after font and color settings changes:** when a font becomes available (fonts added, Refresh Font List, `text.rescanFonts`), the next frame the canvas draws outlines type in it where a geometry effect reshapes the type, a group that holds it or a symbol instance whose art holds it. When the color settings change (Edit › Color Settings, `edit.colorSettings`), the next frame shades objects with Revolve, Extrude & Bevel, Inflate or Rotate, and recolors objects and groups with a color adjustment, through the new settings. + - **Full font names (#1258):** OpenType name ID 4 identifies its face alongside family/legacy/PostScript names, including localized names, for loaded fonts, cataloged files and Missing Fonts searches. Synthetic name-table regressions cover full names distinct from their PostScript name, real-family precedence and variable fonts' default faces. Windows font-service activation remains unverified; scores and hours are unchanged. ### Corpus integrity evidence @@ -823,6 +852,18 @@ Evidence for the shared light Color: geometry tests in `tests_lighting`, effect | Date | Change | Summary | |---|---|---| +| 2026-10-19 | minor | Plug-ins: live effects are given their object's fills and strokes, read only, and the item they sit on (G17); engine and unit regressions. Scores and hours unchanged. | +| 2026-10-19 | minor | Plug-ins: parameters with labels, units, help, groups and conditions in their dialogs, `string` and `numberList` types, up to 256 per plug-in (G17); manifest and kittest dialog regressions. Scores and hours unchanged. | +| 2026-10-19 | minor | Plug-ins: exporter plug-ins add write-only file formats to Export As and `document.export` (G17); engine, ABI and headless Export As regressions. Scores and hours unchanged. | +| 2026-10-19 | minor | Libraries panel: the list fills the panel and scrolls (also while a drag nears its edges); items drag before or after others of their kind and into or out of groups, and groups drag by their headers (`library.moveItem` `before`/`after`, `library.moveGroup`). Scores and estimates unchanged. | +| 2026-10-19 | minor | Cache status-readout sample widths per UI, language, document unit and pixels per point; regressions check reuse across live frames and refresh after display-setting changes. Scores and estimates unchanged. | +| 2026-10-19 | minor | Status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates. Contributor original-file acceptance confirmed; scores and estimates unchanged. | +| 2026-10-19 | minor | Cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission. Regression coverage; scores and estimates unchanged. | +| 2026-10-19 | minor | Cached canvas reprojection preserves scale during resize, rotation and DPI changes. Contributor original-file acceptance confirmed; scores and estimates unchanged. | +| 2026-10-18 | minor | PDF Place and clipboard paste use Open's live-text choice instead of forcing outlines; synthetic regressions cover page selection and explicit outlines. Scores and hours unchanged. | +| 2026-10-18 | minor | File formats: PDF invisible text (rendering mode 3, a scanned page's recognized text) opens as type with no fill or stroke instead of being dropped without a warning, and characters with no fill or stroke export as invisible text, so a scanned PDF opened and saved keeps its searchable text (#2675); own-fixture tests; scores and hours unchanged (estimated) | +| 2026-10-19 | minor | Effect rasters cropped to the view or made coarser are kept while the view stays the same: a drag over a 500 pt blur draws it from the still frame on this thread and on the worker, and an interaction stays on the worker that drew the frame shown (#2558). Scores and hours unchanged. | +| 2026-10-19 | minor | Color Picker layout (#2008): compact controls, centered header, stacked actions and aligned inputs; screen-reader channel values, current shared button names and styling, screen sampler and model-by-model Tab order retained. Narrow windows scroll vertically; scores and hours unchanged. | | 2026-10-18 | minor | Mirror Repeat shows its axis when selected (#2877): drag the line or center handle to move it, drag an end handle to rotate it (Shift: 45°), Escape cancels and each drag is one undo step. Engine and headless canvas gesture regressions passed; native move, rotation and Escape screenshots reviewed. Formatting, Clippy, WASM and repository checks passed; the undo label reuses translated Repeat Options. (#2877) Scores and hours unchanged. | | 2026-10-18 | minor | Bounding-box handles take priority where a selected Mirror Repeat axis crosses them: the Top handle scales the repeat, while the center still moves it and the ends still rotate it. Headless canvas regression confirms vertical scaling without width change; scores and hours unchanged. | | 2026-10-17 | minor | Blend spine Anchor Point conversions, selection/stacking priority and Shift regression coverage (#2544); scores and hours unchanged. Windows native canvas checks and screenshots reviewed in PR #2643. | @@ -849,6 +890,8 @@ Evidence for the shared light Color: geometry tests in `tests_lighting`, effect | 2026-10-16 | minor | Type: localized legacy family names remain available when typographic names are English-only (#2208); loaded and catalog paths tested. Scores and estimates unchanged. | | 2026-10-16 | minor | Batch exporting in Export for Screens (#1935): a file name pattern (document and item names, a counter, the date), folders per format, item or both, Layers and Selection tabs with thumbnails, EPS, AI and VectorCraft rows, a PDF row with printer's marks, and export presets (built-in Logo Package and Print-Ready PDF, saved ones); scores and hours unchanged (estimated) | | 2026-10-16 | minor | Align Stroke on live type (beyond Illustrator): the characters' stroke goes inside or outside the glyphs without creating outlines (#2294); scores and hours unchanged | +| 2026-10-16 | minor | G2: Effect › Artistic › Smudge Stick, Sponge and Watercolor (original approximations with their documented options); measured Photoshop filters 36/57 with Cutout, Neon Glow and Poster Edges, 21 remaining (19–31 h); area score unchanged (49%, estimated). | +| 2026-10-16 | minor | G2: Effect › Sketch › Bas Relief, Charcoal, Photocopy and Stamp (#2527); measured Photoshop filters 37/57 with Cutout, Neon Glow and Poster Edges, 20 remaining (18–30 h). Scores unchanged. | | 2026-10-16 | minor | G2: Effect › Sketch › Halftone Pattern (Size, Contrast, Pattern Type Circle, Dot or Line; black ink on white paper, Size in points at any Document Raster Effects resolution); measured Photoshop filters 30/57, 27 remaining (22–38 h). | | 2026-10-16 | minor | Symbols: Symbol Options › Export Type (Graphic / Movie Clip) with Registration; Symbols score 85% → 87% (estimated) | | 2026-10-15 | minor | Evidence: 36 more tool states get cursors of their own (node editing, Anchor Point, Curvature, side-shear drawn; the rest borrowed until drawn), listed in `crates/tools/src/cursors.toml`; scores unchanged | diff --git a/docs/three-d.md b/docs/three-d.md index b8278818d3..c95ab93097 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -52,6 +52,24 @@ middle. The surface starts with a grid of 48 cells across the larger side, halved or quartered where it rises steeply near the outline. White-light Inflate retains the existing clipped polygon cells, shading, paint composition and seam joins. With colored lights, simple cells are triangulated with shared border samples, and lighting interpolates shared membrane normals through ordinary RGB vector gradients, including on a puffed back. Solid fills batch those triangles into three channel groups and one coverage clip for the whole surface. Source gradients retain per-facet vector composition and apply transparent coverage once. Seam widths retain the 0.05 to 0.75 pt bounds; colored facets use round joins. Shading is automatic, with no additional dialog option. +## Fills and strokes + +Extrude & Bevel and Inflate build a solid from the path for the object's top fill, and one from the outline of +each visible stroke (with its caps, joins, dashes, alignment and arrowheads), each in its own paint. An admin's +reply on the reference app's bug forum says that strokes "will be treated as outlined when applying 3D" +([August 2024](https://illustrator.uservoice.com/forums/601447-illustrator-desktop-bugs/suggestions/48755201-expanding-a-3d-extruded-object-with-a-stroke-as-a)). +The rest is our reading: + +- When the fill and every stroke are opaque with Normal blending, the faces of all the solids are drawn in one + back-to-front order, and the caps turned toward the viewer are drawn last, the lower item's first. Otherwise + each solid is drawn on its own with its opacity and blending, the lower item's first. With a light that is not + white, each solid is also drawn on its own when one of them is a puffed, shaded Inflate surface in a solid color + (drawn as one composite) or is painted with a gradient that has transparent stops (drawn with an opacity mask). +- The solids turn, twist and taper about the center of the bounds of all their shapes, Inflate's grid covers + those bounds, and with Perspective one eye sees every solid. A stroke too narrow to hold a point of Inflate's + grid stays flat. +- A stroke whose outline takes more than 2,048 points is left out, and the fill's solid still draws. + ## Rotate The flat art turned in 3D about the centre of its bounds. Every fill and stroke is turned with its own paint (a @@ -121,19 +139,19 @@ pages, and the archived Extrude & Bevel option list (depth 0–2,000, cap on/off out, perspective). No Adobe software, assets, presets or bevel shapes were used. - **Materials** (base, Adobe Substance and graphics), light presets, **shadows** - and **ray-traced rendering** are not built: shading uses directional lights, painted with the - object's top fill (else its top stroke) for Extrude & Bevel and Inflate. + and **ray-traced rendering** are not built: shading uses directional lights, in the paint of the fill or + stroke the solid is built for ([Fills and strokes](#fills-and-strokes)). - The bevel shapes and their names are our own; custom bevel paths are not supported. -- Visibility is a painter's algorithm: faces of a closed solid turned away are left out, the rest drawn back to - front. Concave solids seen at steep angles can overlap wrongly; open (hollow) solids show both sides. - Twisted walls and bevels are drawn in pieces about as long as a wall slice is wide (fewer near the limit of - 32,768 facets), and a cap or flat back turned toward the viewer is drawn over them. The piece drawn on top can - still lie a few points behind another nearby piece. +- Visibility is a painter's algorithm: faces of a closed solid turned away are left out, and the rest are drawn + back to front, with a flat cap or flat back turned toward the viewer drawn after all of them. Concave solids + seen at steep angles can overlap wrongly; open (hollow) solids show both sides. Twisted walls and bevels are + drawn in pieces about as long as a wall slice is wide (fewer near the limit of 32,768 facets). The piece drawn + on top can still lie a few points behind another nearby piece. - Extrude & Bevel and Rotate retain planar shading. Colored Inflate uses smooth vector lighting; white-light Inflate keeps its original polygon shading; bounded cell triangulation leaves a cell flat when it contains a complete hole or an unusually complex/degenerate contour. Its geometric silhouette is still a polygon approximation. - Paths and compound paths only: convert type, images and groups to outlines first. One 3D effect per object. - Curves are followed within 1/2000 of the shape's size (at least 0.05 pt), so a small curve takes a few points - and a large one up to 32. Extrude & Bevel and Inflate take up to 2,048 outline points, Rotate (which only turns - the outline) 65,536. + and a large one up to 32. Extrude & Bevel and Inflate take up to 2,048 outline points (a stroke's outline is + counted on its own), Rotate (which only turns the outline) 65,536. - **3D (Classic)** (the track cube, surface types, blend steps, map art), Turntable and 3D export are separate, unbuilt items. diff --git a/docs/type-parity.md b/docs/type-parity.md index 4c5721fbd4..07ec457c6a 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -68,7 +68,6 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | 2026-10-17 | minor | A click on area type's red out port loads the Selection tool with the overflow text; the next click threads it into a closed path or a new frame of the same shape there, a drag into a new rectangle (`text.thread.add`, #2572 in part). The out port moved up the frame's right side, clear of the corner handle. Scores and hours unchanged. | | 2026-10-16 | minor | Native font-family labels fall back from English-only typographic names to localized legacy names (#2208). English labels and native typographic precedence are preserved; synthetic loaded/catalog tests. Scores and estimates unchanged. | | 2026-10-16 | minor | Align Stroke on live type: the characters' stroke goes inside or outside the glyphs without creating outlines, for every run or a range; kept in the native file and in canvas, PDF, EPS and SVG output (#2294); beyond Illustrator, scores and hours unchanged | -| 2026-10-14 | minor | Cmd+Shift+C (Align center) works on Windows and Linux too, where egui reported it as a copy (#1940); scores and hours unchanged | | 2026-10-14 | minor | Cmd+Shift+C (Align center) works on Windows and Linux too, where egui reported it as a copy; a double-click on area type's bottom middle handle turns on Auto Size (#1940); scores and hours unchanged | | 2026-10-14 | minor | MCP `add_text` exposes the existing `vertical` option for point, area and path type; horizontal remains the default; scores and hours unchanged. | | 2026-10-14 | minor | Vertical fullwidth question and exclamation marks keep their nominal glyph upright when the font has no vertical alternate; scores and hours unchanged. | diff --git a/docs/typography-lettering.md b/docs/typography-lettering.md new file mode 100644 index 0000000000..373f92b964 --- /dev/null +++ b/docs/typography-lettering.md @@ -0,0 +1,114 @@ +# Typography and Custom Lettering in VectorCraft + +## What you can do + +- **Typesetting:** use an available font to create editable text, then adjust its size, style and spacing. +- **Custom lettering:** convert text to vector outlines and reshape the letters for a title or logo. +- **Reusable font files:** VectorCraft does not currently create or export installable TTF or OTF fonts. + +This guide covers the first two workflows. The steps apply to the v0.13.1 release; the desktop app +can use installed system fonts, while the web app uses the fonts supplied by its deployment. + +## Getting started with the Type Tool + +1. Create a document with **File → New…**, or open an existing one. +2. Select **Type Tool** in the toolbar, or press **T** when you are not typing in a text field. +3. Click an empty part of the artboard and type a short heading, such as `MOON`. A click creates + point text, which grows as you type. To create text that wraps inside a frame, drag a rectangle + instead. If placeholder text appears selected, typing replaces it. +4. Press **Escape** to finish typing. Select **Selection Tool** (**V**) and click the text object. + This lets you format the whole heading rather than just characters selected while typing. +5. Open **Window → Type → Character**. Use the font family menu at the top of the panel to search + for a font and click its name to apply it. The menu below it chooses an available style, such as + Regular, Bold or Italic; the choices depend on the font. **Type → Font** also lists available fonts. +6. Adjust **Font Size** (the field beside **T**) and **Tracking** (beside **VA↔**) in the Character + panel. Hover a field's label to see its name. For example, enter `72 pt` for a large heading and + try tracking `50` to spread its letters slightly. Positive tracking adds space; negative tracking + tightens it. **Leading** controls the spacing between lines; **Kerning (0 = Auto)** adjusts pairs. +7. To change only part of the text, select **Type Tool**, click into the text and drag across the + characters before using the Character panel. Press **Escape** when finished. Keep the text + editable until its wording, font and spacing are settled. +8. Choose **File → Save As…**, select the **VectorCraft** format, and save the document as + `lettering-editable.vectorcraft`. + +The desktop app scans system fonts and loads faces as needed. If you install a font while it is +open, use **Refresh Font List** in the Character panel's menu. On the web, installing a font on your +computer does not add it to VectorCraft's font menu; the available fonts depend on the hosted build. + +## Turning text into editable outlines + +Create Outlines replaces text with vector paths. You can reshape those paths, but you can no longer +edit the words or choose a different font for them with the Type Tool. + +1. Keep the editable file saved above. Choose **File → Save As…** again, select **VectorCraft**, + and save as `lettering-outlines.vectorcraft`. Continue in this second file so later saves do not + overwrite your editable original. +2. With **Selection Tool** (**V**), select the text object you want to convert. +3. Choose **Type → Create Outlines**. The default shortcut is **Ctrl+Shift+O** on Windows and Linux, + or **Cmd+Shift+O** on macOS. +4. Select **Direct Selection Tool** (**A**) and click a letter's edge to inspect its paths and anchors. + The text has become a group of paths, one compound path per glyph. A compound path can include + both a letter's outer edge and its inner holes, such as the middle of an `O`. + +Conversion uses the font currently drawn. Resolve missing or substituted fonts before outlining, +or the paths will capture the substitute's shapes. + +## Customizing individual letters + +Try making the final `N` in `MOON` taller to give the heading a distinctive ending. + +1. Select **Direct Selection Tool** (**A**). Click empty canvas to clear the current selection, + then click an anchor on the outlined `N`. Anchors are the points that define a path's shape; + Direct Selection can reach paths inside the group without ungrouping the letters. +2. Drag the anchor a short distance to change that part of the letter. To move several anchors + together, Shift-click them before dragging, or drag a selection rectangle around them from + empty canvas. For the taller `N`, select its top anchors and move them up slightly. +3. On a curved letter such as `O`, select an anchor on a curve. Drag the end of a visible direction + handle to change the curve's bend. These Bézier handles control how the curve leaves or enters + the anchor. Straight corners may have no handles to drag. +4. Switch to **Selection Tool** (**V**) to inspect the whole heading. Use **Edit → Undo** if a change + distorts the letter or closes an inner hole, then try a smaller adjustment. + +These changes affect the artwork in this document. They do not change the installed font or other +text using it. A glyph is not always one typed character: for example, a font may join letters into +a ligature, which becomes a single glyph outline. + +## Saving and exporting your artwork + +- **Keep the project:** use **File → Save** to save `lettering-outlines.vectorcraft`. Retain + `lettering-editable.vectorcraft` separately for future wording or font changes. A native file keeps + editable text only where you have left text objects unconverted. +- **Export vector artwork:** choose **File → Export → Export As…**, select **SVG** or **PDF**, and + continue through the export options. The outlined letters are vector shapes in the output, not + keyboard-editable text. Check **Use Artboards** if you want the artboard bounds rather than the + bounds of the visible artwork. +- **Create an installable font:** SVG and PDF exports are artwork, not TTF/OTF files. Renaming their + extension does not turn them into fonts. + +## Can VectorCraft create a font file? + +No. VectorCraft does not currently provide a complete font-authoring workflow or TTF/OTF export. +It does not turn your letter paths into a reusable font with character encoding, glyph metrics and +font-wide kerning definitions. Character panel spacing changes format the text in your drawing; +they do not edit a font's kerning tables. + +To make an installable typeface, use a dedicated font editor to assign glyphs to characters, set +metrics and spacing, and generate the font file. VectorCraft's outline tools are useful for custom +lettering artwork, but exporting that artwork is only one part of making a font. + +## Troubleshooting + +- **I cannot find my font.** On desktop, check that it is installed, clear the font menu's search + and filters, then choose **Refresh Font List** from the Character panel menu. **Type → Find Font…** + lists fonts used by the document and marks missing ones; it can replace them with available fonts. + A missing family, style or character may use a fallback, so check the result before outlining. + On the web, the site must supply the font; system-font scanning and the desktop refresh option + are unavailable there. +- **I cannot change the words after Create Outlines.** The result is paths, not text. Use + **Edit → Undo** if the conversion is still in the undo history, or reopen your editable original. +- **I cannot install my modified letters as a font.** They are drawing objects. SVG/PDF export + does not add the structure required by an installable font; see [Can VectorCraft create a font + file?](#can-vectorcraft-create-a-font-file). +- **How do I keep text editable?** Save the text in a native `.vectorcraft` file before outlining, + then use a different file name for the outlined version. Saving paths in the native format does + not turn them back into text. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e4eee210b8..d366c1021e 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-18 · **Change:** minor (on-canvas Mirror Repeat axis, #2877; Background Export progress dialog with Cancel, #2564; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; Blend spine Anchor Point conversions, selection/stacking priority and Shift regression coverage (#2544); scores and hours unchanged; Artboard Options' X and Y with a reference point, #1876; scores unchanged; library panels: one per library, dockable and tabbable, with Persistent, #2603; the Selection tool threads text from the out port, #2572 in part; scores unchanged; Group Selection picks and moves one path of a compound path, #2441 in part; the Move dialog opens on the last move and its last checkboxes; scores unchanged; transparency grid visibility saved in native documents, #1968; Live Corners radius up to the neighbouring cuts, #2332; Image Trace quick presets: wording corrected to the shipped behaviour, the Image Trace button opens the controls; batch exporting, #1935; document window scroll bars, #2322; Anchor Point tool: a click on a handle end retracts that handle only, #2267; scores unchanged; Smart Guides: the dragged end of a straight segment keeps to its extension at any angle, #2120; Warp Options controls verified by focused checks and original-image review; estimates unchanged; existing-guide Escape cancellation validated 2026-10-14; scores and hours unchanged; open-path anchor Delete keeps surviving runs separate; estimates unchanged; Artboard tab-switch follow-up historically validated on `a0671777`; scores and hours unchanged; Artboard clean active-tab close/Delete follow-up validated 2026-10-15; Curvature curve geometry, #1236 in part; Width-point finite-arithmetic follow-up validated; scores and hours unchanged; Image Trace adjustment discovery; later 2026-10-14 merges: macOS save sheet Format menu back to missing, #1855, #866 reopened; anchor X/Y/W/H in the Transform panel, Properties and Control bar, #1824; Snap to Grid over Snap to Pixel, #1816; toolbar labels, columns and the All Tools drawer, #1751; Actions panel selection, #1629 in part; scores unchanged; 2026-10-14 merges: anchor Align and Distribute, #1636; Delete on closed paths and whole objects, #1674; selection inside isolation, #1666; Escape in a Direct Selection drag and while typing, #1743, #1686; Pen clicks under 3 px, #1663; [ and ] on more tools, #1661 in part; fields commit on click away, #1787; command search keys, #1757; a guide's position in the Transform panel is a convenience with no parity claim, #1659; scores unchanged; intersect Smart Guides for drawn points and dragged anchors, #1602 in part; a ruler guide's position in the Transform panel, #1597 in part; Symbol Options before New Symbol, #1560; tool flyout widths, #1616; Pathfinder Trim, Merge and Crop strokes, #1570; scores unchanged; G1/M11: Artboard deletion and history selection normalization; history regressions and full workspace CI pass; scores and hours unchanged; Width Point Edit: Shift-double-click enables adjoining adjustment; plain double-click keeps it off; scores and hours unchanged; per-corner radius fields with a link toggle, split from #1594; Join merges anchors lying on one another, #1533; correction: Average and Join with a corner or smooth choice is missing, not done; guide objects take the guide colour and style and Lock Guides, #1534; Keyboard Shortcuts lists commands outside the menus, #1539; round corners next to curves and the Smooth tool's reach, #1512; Make Compound Path on a group, #1537; dialog slider rails, #1483; template layers stay in Preview in Outline view, #1486; Direct Selection takes the selected object's anchor where anchors coincide, #1508; Tabs panel stop drags, #1458; Split Into Grid dialog, #1462; Transform Objects and Reflect's angle, #1448 and #1460; Pathfinder panel on a group, #1450; value fields: readable selection, #1465 in part, and a focused field follows its value, #1457; scores unchanged; Transform dialogs have a live Preview and step with the arrow keys, #1412; transform tools, dialogs and Move act on direct-selected anchors, #1408; the bounding box hides during a corner drag, #1229; scores unchanged; dialogs focus their first field on every open, #1367, and a first field that starts greyed out once it is enabled, #1395; scores unchanged; Rectangular Grid and Polar Grid click dialogs take the skew, frame, compound path and Fill Grid options, #1377 in part, score unchanged; Live Corners: a Direct Selection click on a widget selects its corner, #1239; custom ruler origin, #1212; Artboard tool clicks fit the topmost editable object in one undo step (#1227); scores unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; DXF control-point SPLINE closure read, #1299 follow-up; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; Simplify preview/counts and valid rewritten-path selection (#1272); parity remains partial; Texture-effect drag redraws optimized (#1257); idle Windows interaction still unverified; scores unchanged; Curvature point display improved (#1236, in part); scores unchanged; Direct Selection: no-op anchor Align preserves Undo, Redo and saved state (#1180 follow-up); Eyedropper cursor distinguished from precise crosshair (#1269); scores unchanged; Eyedropper can read visible locked and outside-isolation sources (#1251); scores unchanged; Direct Selection: independent segment picks and Delete (#1278); scores unchanged; Adding paint to an unpainted zero-width stroke restores the 1 pt default (#1253); scores unchanged; macOS save sheets offer a Format menu, #866; Attributes fill-rule controls edit the compound when a member is selected, #1197; a marquee needs to touch a path, not just lie inside its fill, #1103; earlier: Live Corners round corners between curved sides, #1144; interactive Mirror Repeat axis; Background Export progress dialog with Cancel, #2564; scores unchanged; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; Blend spine Anchor Point conversions, selection/stacking priority and Shift regression coverage (#2544); scores and hours unchanged; Artboard Options' X and Y with a reference point, #1876; scores unchanged; library panels: one per library, dockable and tabbable, with Persistent, #2603; the Selection tool threads text from the out port, #2572 in part; scores unchanged; Group Selection picks and moves one path of a compound path, #2441 in part; the Move dialog opens on the last move and its last checkboxes; scores unchanged; transparency grid visibility saved in native documents, #1968; Live Corners radius up to the neighbouring cuts, #2332; Image Trace quick presets: wording corrected to the shipped behaviour, the Image Trace button opens the controls; batch exporting, #1935; document window scroll bars, #2322; Anchor Point tool: a click on a handle end retracts that handle only, #2267; scores unchanged; Smart Guides: the dragged end of a straight segment keeps to its extension at any angle, #2120; Warp Options controls verified by focused checks and original-image review; estimates unchanged; existing-guide Escape cancellation validated 2026-10-14; scores and hours unchanged; open-path anchor Delete keeps surviving runs separate; estimates unchanged; Artboard tab-switch follow-up historically validated on `a0671777`; scores and hours unchanged; Artboard clean active-tab close/Delete follow-up validated 2026-10-15; Curvature curve geometry, #1236 in part; Width-point finite-arithmetic follow-up validated; scores and hours unchanged; Image Trace adjustment discovery; later 2026-10-14 merges: macOS save sheet Format menu back to missing, #1855, #866 reopened; anchor X/Y/W/H in the Transform panel, Properties and Control bar, #1824; Snap to Grid over Snap to Pixel, #1816; toolbar labels, columns and the All Tools drawer, #1751; Actions panel selection, #1629 in part; scores unchanged; 2026-10-14 merges: anchor Align and Distribute, #1636; Delete on closed paths and whole objects, #1674; selection inside isolation, #1666; Escape in a Direct Selection drag and while typing, #1743, #1686; Pen clicks under 3 px, #1663; [ and ] on more tools, #1661 in part; fields commit on click away, #1787; command search keys, #1757; a guide's position in the Transform panel is a convenience with no parity claim, #1659; scores unchanged; intersect Smart Guides for drawn points and dragged anchors, #1602 in part; a ruler guide's position in the Transform panel, #1597 in part; Symbol Options before New Symbol, #1560; tool flyout widths, #1616; Pathfinder Trim, Merge and Crop strokes, #1570; scores unchanged; G1/M11: Artboard deletion and history selection normalization; history regressions and full workspace CI pass; scores and hours unchanged; Width Point Edit: Shift-double-click enables adjoining adjustment; plain double-click keeps it off; scores and hours unchanged; per-corner radius fields with a link toggle, split from #1594; Join merges anchors lying on one another, #1533; correction: Average and Join with a corner or smooth choice is missing, not done; guide objects take the guide colour and style and Lock Guides, #1534; Keyboard Shortcuts lists commands outside the menus, #1539; round corners next to curves and the Smooth tool's reach, #1512; Make Compound Path on a group, #1537; dialog slider rails, #1483; template layers stay in Preview in Outline view, #1486; Direct Selection takes the selected object's anchor where anchors coincide, #1508; Tabs panel stop drags, #1458; Split Into Grid dialog, #1462; Transform Objects and Reflect's angle, #1448 and #1460; Pathfinder panel on a group, #1450; value fields: readable selection, #1465 in part, and a focused field follows its value, #1457; scores unchanged; Transform dialogs have a live Preview and step with the arrow keys, #1412; transform tools, dialogs and Move act on direct-selected anchors, #1408; the bounding box hides during a corner drag, #1229; scores unchanged; dialogs focus their first field on every open, #1367, and a first field that starts greyed out once it is enabled, #1395; scores unchanged; Rectangular Grid and Polar Grid click dialogs take the skew, frame, compound path and Fill Grid options, #1377 in part, score unchanged; Live Corners: a Direct Selection click on a widget selects its corner, #1239; custom ruler origin, #1212; Artboard tool clicks fit the topmost editable object in one undo step (#1227); scores unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; DXF control-point SPLINE closure read, #1299 follow-up; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; Simplify preview/counts and valid rewritten-path selection (#1272); parity remains partial; Texture-effect drag redraws optimized (#1257); idle Windows interaction still unverified; scores unchanged; Curvature point display improved (#1236, in part); scores unchanged; Direct Selection: no-op anchor Align preserves Undo, Redo and saved state (#1180 follow-up); Eyedropper cursor distinguished from precise crosshair (#1269); scores unchanged; Eyedropper can read visible locked and outside-isolation sources (#1251); scores unchanged; Direct Selection: independent segment picks and Delete (#1278); scores unchanged; Adding paint to an unpainted zero-width stroke restores the 1 pt default (#1253); scores unchanged; macOS save sheets offer a Format menu, #866; Attributes fill-rule controls edit the compound when a member is selected, #1197; a marquee needs to touch a path, not just lie inside its fill, #1103; earlier: Live Corners round corners between curved sides, #1144) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-19 · **Change:** minor (a ruler guide can be the key object Align aligns to, and selected guides align to a key object, #2143; Pencil: Alt key toggles to Smooth Tool, #2001; status-readout sample widths cached by language, document unit and pixels per point; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; cached canvas reprojection preserves scale during resize, rotation and DPI changes; on-canvas Mirror Repeat axis, #2877; Background Export progress dialog with Cancel, #2564; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; Blend spine Anchor Point conversions, selection/stacking priority and Shift regression coverage (#2544); scores and hours unchanged; Artboard Options' X and Y with a reference point, #1876; scores unchanged; library panels: one per library, dockable and tabbable, with Persistent, #2603; the Selection tool threads text from the out port, #2572 in part; scores unchanged; Group Selection picks and moves one path of a compound path, #2441 in part; the Move dialog opens on the last move and its last checkboxes; scores unchanged; transparency grid visibility saved in native documents, #1968; Live Corners radius up to the neighbouring cuts, #2332; Image Trace quick presets: wording corrected to the shipped behaviour, the Image Trace button opens the controls; batch exporting, #1935; document window scroll bars, #2322; Anchor Point tool: a click on a handle end retracts that handle only, #2267; scores unchanged; Smart Guides: the dragged end of a straight segment keeps to its extension at any angle, #2120; Warp Options controls verified by focused checks and original-image review; estimates unchanged; existing-guide Escape cancellation validated 2026-10-14; scores and hours unchanged; open-path anchor Delete keeps surviving runs separate; estimates unchanged; Artboard tab-switch follow-up historically validated on `a0671777`; scores and hours unchanged; Artboard clean active-tab close/Delete follow-up validated 2026-10-15; Curvature curve geometry, #1236 in part; Width-point finite-arithmetic follow-up validated; scores and hours unchanged; Image Trace adjustment discovery; later 2026-10-14 merges: macOS save sheet Format menu back to missing, #1855, #866 reopened; anchor X/Y/W/H in the Transform panel, Properties and Control bar, #1824; Snap to Grid over Snap to Pixel, #1816; toolbar labels, columns and the All Tools drawer, #1751; Actions panel selection, #1629 in part; scores unchanged; 2026-10-14 merges: anchor Align and Distribute, #1636; Delete on closed paths and whole objects, #1674; selection inside isolation, #1666; Escape in a Direct Selection drag and while typing, #1743, #1686; Pen clicks under 3 px, #1663; [ and ] on more tools, #1661 in part; fields commit on click away, #1787; command search keys, #1757; a guide's position in the Transform panel is a convenience with no parity claim, #1659; scores unchanged; intersect Smart Guides for drawn points and dragged anchors, #1602 in part; a ruler guide's position in the Transform panel, #1597 in part; Symbol Options before New Symbol, #1560; tool flyout widths, #1616; Pathfinder Trim, Merge and Crop strokes, #1570; scores unchanged; G1/M11: Artboard deletion and history selection normalization; history regressions and full workspace CI pass; scores and hours unchanged; Width Point Edit: Shift-double-click enables adjoining adjustment; plain double-click keeps it off; scores and hours unchanged; per-corner radius fields with a link toggle, split from #1594; Join merges anchors lying on one another, #1533; correction: Average and Join with a corner or smooth choice is missing, not done; guide objects take the guide colour and style and Lock Guides, #1534; Keyboard Shortcuts lists commands outside the menus, #1539; round corners next to curves and the Smooth tool's reach, #1512; Make Compound Path on a group, #1537; dialog slider rails, #1483; template layers stay in Preview in Outline view, #1486; Direct Selection takes the selected object's anchor where anchors coincide, #1508; Tabs panel stop drags, #1458; Split Into Grid dialog, #1462; Transform Objects and Reflect's angle, #1448 and #1460; Pathfinder panel on a group, #1450; value fields: readable selection, #1465 in part, and a focused field follows its value, #1457; scores unchanged; Transform dialogs have a live Preview and step with the arrow keys, #1412; transform tools, dialogs and Move act on direct-selected anchors, #1408; the bounding box hides during a corner drag, #1229; scores unchanged; dialogs focus their first field on every open, #1367, and a first field that starts greyed out once it is enabled, #1395; scores unchanged; Rectangular Grid and Polar Grid click dialogs take the skew, frame, compound path and Fill Grid options, #1377 in part, score unchanged; Live Corners: a Direct Selection click on a widget selects its corner, #1239; custom ruler origin, #1212; Artboard tool clicks fit the topmost editable object in one undo step (#1227); scores unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; DXF control-point SPLINE closure read, #1299 follow-up; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; Simplify preview/counts and valid rewritten-path selection (#1272); parity remains partial; Texture-effect drag redraws optimized (#1257); idle Windows interaction still unverified; scores unchanged; Curvature point display improved (#1236, in part); scores unchanged; Direct Selection: no-op anchor Align preserves Undo, Redo and saved state (#1180 follow-up); Eyedropper cursor distinguished from precise crosshair (#1269); scores unchanged; Eyedropper can read visible locked and outside-isolation sources (#1251); scores unchanged; Direct Selection: independent segment picks and Delete (#1278); scores unchanged; Adding paint to an unpainted zero-width stroke restores the 1 pt default (#1253); scores unchanged; macOS save sheets offer a Format menu, #866; Attributes fill-rule controls edit the compound when a member is selected, #1197; a marquee needs to touch a path, not just lie inside its fill, #1103; earlier: Live Corners round corners between curved sides, #1144; interactive Mirror Repeat axis; Background Export progress dialog with Cancel, #2564; scores unchanged; 3D lighting: one to ten colored lights, smooth colored Inflate, legacy white-light appearance preserved; surface batching and restored seam minimum; scores and estimates unchanged; Blend spine Anchor Point conversions, selection/stacking priority and Shift regression coverage (#2544); scores and hours unchanged; Artboard Options' X and Y with a reference point, #1876; scores unchanged; library panels: one per library, dockable and tabbable, with Persistent, #2603; the Selection tool threads text from the out port, #2572 in part; scores unchanged; Group Selection picks and moves one path of a compound path, #2441 in part; the Move dialog opens on the last move and its last checkboxes; scores unchanged; transparency grid visibility saved in native documents, #1968; Live Corners radius up to the neighbouring cuts, #2332; Image Trace quick presets: wording corrected to the shipped behaviour, the Image Trace button opens the controls; batch exporting, #1935; document window scroll bars, #2322; Anchor Point tool: a click on a handle end retracts that handle only, #2267; scores unchanged; Smart Guides: the dragged end of a straight segment keeps to its extension at any angle, #2120; Warp Options controls verified by focused checks and original-image review; estimates unchanged; existing-guide Escape cancellation validated 2026-10-14; scores and hours unchanged; open-path anchor Delete keeps surviving runs separate; estimates unchanged; Artboard tab-switch follow-up historically validated on `a0671777`; scores and hours unchanged; Artboard clean active-tab close/Delete follow-up validated 2026-10-15; Curvature curve geometry, #1236 in part; Width-point finite-arithmetic follow-up validated; scores and hours unchanged; Image Trace adjustment discovery; later 2026-10-14 merges: macOS save sheet Format menu back to missing, #1855, #866 reopened; anchor X/Y/W/H in the Transform panel, Properties and Control bar, #1824; Snap to Grid over Snap to Pixel, #1816; toolbar labels, columns and the All Tools drawer, #1751; Actions panel selection, #1629 in part; scores unchanged; 2026-10-14 merges: anchor Align and Distribute, #1636; Delete on closed paths and whole objects, #1674; selection inside isolation, #1666; Escape in a Direct Selection drag and while typing, #1743, #1686; Pen clicks under 3 px, #1663; [ and ] on more tools, #1661 in part; fields commit on click away, #1787; command search keys, #1757; a guide's position in the Transform panel is a convenience with no parity claim, #1659; scores unchanged; intersect Smart Guides for drawn points and dragged anchors, #1602 in part; a ruler guide's position in the Transform panel, #1597 in part; Symbol Options before New Symbol, #1560; tool flyout widths, #1616; Pathfinder Trim, Merge and Crop strokes, #1570; scores unchanged; G1/M11: Artboard deletion and history selection normalization; history regressions and full workspace CI pass; scores and hours unchanged; Width Point Edit: Shift-double-click enables adjoining adjustment; plain double-click keeps it off; scores and hours unchanged; per-corner radius fields with a link toggle, split from #1594; Join merges anchors lying on one another, #1533; correction: Average and Join with a corner or smooth choice is missing, not done; guide objects take the guide colour and style and Lock Guides, #1534; Keyboard Shortcuts lists commands outside the menus, #1539; round corners next to curves and the Smooth tool's reach, #1512; Make Compound Path on a group, #1537; dialog slider rails, #1483; template layers stay in Preview in Outline view, #1486; Direct Selection takes the selected object's anchor where anchors coincide, #1508; Tabs panel stop drags, #1458; Split Into Grid dialog, #1462; Transform Objects and Reflect's angle, #1448 and #1460; Pathfinder panel on a group, #1450; value fields: readable selection, #1465 in part, and a focused field follows its value, #1457; scores unchanged; Transform dialogs have a live Preview and step with the arrow keys, #1412; transform tools, dialogs and Move act on direct-selected anchors, #1408; the bounding box hides during a corner drag, #1229; scores unchanged; dialogs focus their first field on every open, #1367, and a first field that starts greyed out once it is enabled, #1395; scores unchanged; Rectangular Grid and Polar Grid click dialogs take the skew, frame, compound path and Fill Grid options, #1377 in part, score unchanged; Live Corners: a Direct Selection click on a widget selects its corner, #1239; custom ruler origin, #1212; Artboard tool clicks fit the topmost editable object in one undo step (#1227); scores unchanged; Pathfinder single-result source names and SVG IDs retained, #1293; DXF control-point SPLINE closure read, #1299 follow-up; Document Setup: Edit Artboards closes the modal after applying valid settings; pointer-click regressions; scores and hours unchanged; Artboards: Escape exits editing; an active drag cancels first; shortcut-routing regression; scores and hours unchanged; Simplify preview/counts and valid rewritten-path selection (#1272); parity remains partial; Texture-effect drag redraws optimized (#1257); idle Windows interaction still unverified; scores unchanged; Curvature point display improved (#1236, in part); scores unchanged; Direct Selection: no-op anchor Align preserves Undo, Redo and saved state (#1180 follow-up); Eyedropper cursor distinguished from precise crosshair (#1269); scores unchanged; Eyedropper can read visible locked and outside-isolation sources (#1251); scores unchanged; Direct Selection: independent segment picks and Delete (#1278); scores unchanged; Adding paint to an unpainted zero-width stroke restores the 1 pt default (#1253); scores unchanged; macOS save sheets offer a Format menu, #866; Attributes fill-rule controls edit the compound when a member is selected, #1197; a marquee needs to touch a path, not just lie inside its fill, #1103; earlier: Live Corners round corners between curved sides, #1144) · **Target:** Adobe Illustrator 2026 (30.x) How VectorCraft's tools, handles, snapping and panels behave next to Illustrator's. A vector illustrator's trust is in the details: where a handle lands, what Shift and Alt do mid-drag, what a smart guide snaps to, @@ -59,12 +59,13 @@ tools, never checked side by side) isn't captured row by row. | Each anchor snaps to Smart Guides and construction angles | done | `DrawSnap` | | Curvature tool: click/drag points, double-click or Alt-click for a corner, temporary Direct Selection, point conversion | partial | circular point markers without direction handles or duplicate markers, Anchor Size and Hide Edges regression-tested (#1236, in part); curve geometry: each stretch of three points follows the circle through them (handles along its tangent, chord/(3·cos²(α/2)) long, shorter in a turn tighter than 30°), open ends curving in, the same rule for the rubber band, dragged, inserted and converted points (#1236, in part); neighbours of a point dragged on an existing path keep their tangents, and modifiers requested in #975 remain | | Blend spine Anchor Point conversion and handle editing (#2544) | implemented | symmetric handles, independent drag/retraction, visible-handle policy and selection/stacking covered by tool and engine regressions; Windows native canvas checks and screenshots reviewed in PR #2643 | -| Add/Delete/Anchor Point tools; Anchor Point tool drags segments to reshape | done | #2267: a click on a handle end retracts that handle and leaves the anchor a corner with the other one | +| Add/Delete/Anchor Point tools; Anchor Point tool drags segments to reshape | done | #2267: a click on a handle end retracts that handle and leaves the anchor a corner with the other one; Shift held at the press on an anchor moves it, handles and all (Shift kept down: at 45° steps) instead of pulling out handles | +| Pencil: Fidelity, Keep selected, Alt to Smooth, edit selected paths, close by proximity | done | Alt key toggles to Smooth Tool (#2001); Edit Selected Paths continues a selected path from an end and, from a stroke that starts and ends on a selected path, redraws the section between (the shorter way round a closed path, #2850); with Keep selected (Pencil and Paintbrush, on by default) off, the path a stroke draws or continues is not selected afterwards; a filled Pencil path keeps a stroke of None (#1804, part of #1679) | | Pencil: Fidelity, Keep selected, Alt to Smooth, edit selected paths, close by proximity | partial | Alt to Smooth is missing; Edit Selected Paths continues a selected path from an end and, from a stroke that starts and ends on a selected path, redraws the section between (the shorter way round a closed path, #2850); with Keep selected (Pencil and Paintbrush, on by default) off, the path a stroke draws or continues is not selected afterwards; a filled Pencil path keeps a stroke of None (#1804, part of #1679) | | Join tool scrubbing, Average, Join | done | Join merges the direct-selected anchors lying on one another along a path, as after Average, into one (#1533) | -| Average and Join in one step, with a corner or smooth choice for the joined anchor | missing | `path.join` and `path.average` are separate commands, and Join has no corner/smooth choice; [gap 1](gaps.md) | +| Average and Join in one step, with a corner or smooth choice for the joined anchor | partial | `path.join` accepts `to: corner|smooth` on the merged anchor; Average and Join are still separate commands; [gap 1](gaps.md) | | Smooth tool smooths only the stretch of path under the drag | done | #1512 | -| Simplify (slider, auto, corner angle threshold) | partial | Tolerance, default-on Preview and original/new point counts (#1272); Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path; slider, auto-simplify and Retain my latest settings remain missing | +| Simplify (slider, auto, corner angle threshold) | partial | Tolerance, default-on Preview and original/new point counts (#1272); Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path; the slider under the selection with Auto-Simplify and More Options, and the dialog's option to open it directly with its last settings; the slider opens at 1 pt rather than at the Auto-Simplify level, and simplifying only a Direct Selection part of a path remains missing | ## Direct Selection, anchors and handles @@ -73,6 +74,8 @@ tools, never checked side by side) isn't captured row by row. | Click/Shift-click anchors; marquee toggles with Shift | done | #483 | | Align selected anchors to their bounds or the artboard; repeating an alignment that moves nothing keeps Undo, Redo and saved state | done | #1180 follow-up; engine regressions include rounding-only moves and unchanged handles; #1641 (fixes #1636): Align and Distribute act on the anchors selected with Direct Selection, the points of one path aligning to each other and Distribute spacing them | | Align selected anchors to a key anchor | missing | #1636 | +| A ruler guide as the key object: a click on a guide selected with objects (or Align to Key Object with one object and a guide) makes it the key, drawn thicker; Align lines the objects (or selected anchors) up on it and the guide stays put | done | #2143; `select.key {guide}`; a vertical guide sets x only, a horizontal one y; Distribute Spacing doesn't space from a key guide | +| Ruler guides align to a key object: a click on an object selected with guides makes it the key (one object is enough); Align moves the selected guides to its edge or centre (vertical guides to left, centre or right, horizontal ones to top, centre or bottom) and the key stays put | done | #2143; aligning to the selection or the artboard leaves guides alone | | A marquee selects the objects whose paths it touches (anchors or segments): drawn inside a filled shape, over a background, it leaves that shape (Preview and Outline) | done | #1103 | | Click a segment independently of its endpoint anchors; only its direction handles show | done | #1278: hollow endpoint squares, selected edge emphasized; headless egui checked | | Drag a curved segment to bend it, a straight one to move its anchors | done | | @@ -83,7 +86,7 @@ tools, never checked side by side) isn't captured row by row. | Convert selected anchors to corner/smooth from the Control bar and Properties | done | | | Cut path at selected anchors, Remove Anchor Points, Delete removes segments | done | Open-path anchor Delete removes adjoining segments without bridging the gap; targeted core and full-frame Delete/Backspace regressions pass for survivor selection and Undo/Redo. Explicit Remove Anchor Points keeps its reconnect/refit behavior; #1278: segment Delete preserves neighboring edges and endpoint anchors; a second Delete removes the remainder; explicit anchor Delete retains its behavior; #1674: Delete removes every selected anchor of a closed path and objects selected whole along with them, and keeps the remainder selected; #2241: Remove Anchor Points then selects the next anchor along the path (the one before at an open end), so it can be run again without picking each anchor | | Direct Selection and Group Selection pick only inside the isolated object in isolation mode | done | #1666 | -| Group Selection picks one path of a compound path (the outer shape or a hole) and moves it on its own; a second click adds the compound path | done | #2441, in part (Shift-click to deselect is not covered) | +| Group Selection picks one path of a compound path (the outer shape or a hole) and moves it on its own; a second click adds the compound path | done | #2441; Shift-click on a selected member deselects it on release | | Escape cancels a Direct Selection drag | done | #1803 (#1743) | | Live Corners widgets (radius readout, Alt-click cycles kind, double-click the Corners dialog) | done | a Direct Selection click on a widget selects its corner (#1239); a press-and-drag on a widget of a path selected whole still rounds every corner (#908), and adding widgets to the selection by Shift-click (#1232) is missing; the bounding box hides while a widget is dragged with the Selection tool (#1229); a round corner next to a curved side curves smoothly instead of sticking out of the shape (#1512); a corner rounds until its cut reaches its neighbours' cuts, so one corner of a square alone reaches the whole side (#2332) | | Corners between curved sides (#1144), Relative rounding | partial | Relative rounding missing | @@ -102,7 +105,7 @@ tools, never checked side by side) isn't captured row by row. | Construction guides at preference angles while drawing | done | #506 | | Line extension: the dragged end of a straight segment snaps to the segment's own direction at any angle, past its other end or short of it, with the guide along it | done | #2120; Direct Selection and Curvature, one anchor dragged (with several, the move has no single direction); nearer the horizontal or vertical through the other end, the point lines up with it ("align"), so a nearly level segment can still be straightened | | Measurement labels while drawing, moving and resizing | partial | sizes and offsets; angle and distance readouts while drawing missing | -| Spacing guides (equal distances) | partial | for moves (#394); not for resizing or drawing | +| Spacing guides (equal distances) | partial | for moves and bounding-box resizes (#394); not while drawing | | Snapping tolerance preference | done | | | Snap to Point, Snap to Grid, Snap to Pixel; Pixel Preview | done | #1840: with Snap to Grid on, anchors and objects snap to the grid even when Snap to Pixel is also ticked (#1816 waits for the reporter) | | Snap to Glyph | missing | menu stub | @@ -115,8 +118,8 @@ tools, never checked side by side) isn't captured row by row. | Ruler guides as Layers rows: shown, hidden, locked and deleted with their layer; rows dragged to another layer | done | `guide.setLayer`; guides from older files go on a layer | | Objects made into guides: drawn in the guide colour and style of Preferences; Lock Guides locks them too (no select, move or delete); a dragged selection snaps to ruler guides with Smart Guides on | done | #1534 (#1543, #1583) | | A selected ruler guide's X or Y in the Transform panel; typing a value moves it | not scored | #1659 (part of #1597); several guides move together; not in Properties or the Control bar. Not established by the documentation we could find: the help pages on guides, rulers and the Transform, Control and Properties panels (read again on 2026-10-14) don't describe it, and the one public statement is a user's [community answer](https://community.adobe.com/questions-652/adding-a-new-custom-guide-785586), which is not documentation. Kept as a convenience pending the owner's decision; no parity claim | -| Alt swaps a ruler guide's orientation while dragging | missing | | -| Alt swaps a new ruler guide's orientation while dragging | done | Both rulers; preview, snapping and final placement follow the current modifier; existing-guide Alt-copy is unchanged. | +| Alt swaps a ruler guide's orientation while dragging | missing | Alt-drag copies the selected guides ([Use rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html)); `guide.move` `{copy: true}` | +| Alt swaps a new ruler guide's orientation while dragging | done | Both rulers; preview, snapping and final placement follow the current modifier ([public shortcut reference](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). | | Global/artboard ruler mode switch (View › Rulers › Change to Global / Artboard Rulers, Cmd+Alt+R) | done | `view.globalRulers`; a new document has artboard rulers, counting from the active artboard's top-left corner or the zero point set for it (kept relative to the artboard); global rulers keep one document zero point. Rulers, Transform, Properties, Control and Info X/Y, guide readouts and Shift ruler-tick snapping follow the mode; saved with the document, older files open with global rulers. Behaviour from [About rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/about-rulers.html) and [Use rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html) | | Video rulers | missing | menu stub | @@ -237,6 +240,10 @@ panel-menu commands such as Break Link to Symbol), so they can be given shortcut ## Look and feel +- [x] Status messages and bounded readouts remain stable as values, canvas hover and background jobs change; ordinary values fit all registered languages and units, and optional groups yield in narrow windows (regressions; contributor rebuilt and confirmed the original-file status-bar scenario on 2026-10-19). Sample widths are cached per UI and refreshed only when language, document units or pixels per point changes. + +- [x] Cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (controlled-worker regression). +- [x] Cached canvas frames keep their document scale during panel/window resize, including rotated views and DPI changes (controlled-worker regression; contributor rebuilt and confirmed the original-file resize scenario on 2026-10-19). Medium Dark theme and four brightness levels, the categorized and Advanced toolbars, 35 pt document tabs, 33 pt panel tabs, hint bar, contextual task bar and native macOS menus, restyled to values measured from public screenshots on 2026-10-02 (~75–80% then). Missing: a System theme that follows the OS (#825), a @@ -244,10 +251,18 @@ re-measure of the panels added since. Slider rails show on Medium Dark (#1808, # - [x] Native saves restore Show Transparency Grid (#1968), without dirtying the document or adding an undo step. +- [x] Compact Color Picker with a distinct header, stacked actions and aligned input groups. #2008; translated action widths, visible warnings, stable mode switching and vertical scrolling in narrow windows; real egui events and two UI scales covered; German and enlarged English renders reviewed locally. Scores unchanged + ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-10-19 | minor | A ruler guide selected with objects can be the key object (#2143): the Selection tool's click on it, or Align to Key Object with one object; drawn thicker; Align lines the objects up on it and the guide stays put; the other way round, selected guides align to a key object, which one object selected with guides can be; scores unchanged | +| 2026-10-19 | minor | Cache status-readout sample widths per UI, language, document unit and pixels per point; regressions check reuse across live frames and refresh after display-setting changes. Scores and estimates unchanged. | +| 2026-10-19 | minor | Status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates. Contributor original-file acceptance confirmed; scores and estimates unchanged. | +| 2026-10-19 | minor | Cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission. Regression coverage; scores and estimates unchanged. | +| 2026-10-19 | minor | Cached canvas reprojection preserves scale during resize, rotation and DPI changes. Contributor original-file acceptance confirmed; scores and estimates unchanged. | +| 2026-10-19 | minor | Color Picker layout (#2008): compact controls, centered header, stacked actions and aligned inputs; screen-reader channel values, current shared button names and styling, screen sampler and model-by-model Tab order retained. Narrow windows scroll vertically; scores and hours unchanged. | | 2026-10-18 | minor | Mirror Repeat shows its axis when selected (#2877): drag the line or center handle to move it, drag an end handle to rotate it (Shift: 45°), Escape cancels and each drag is one undo step. Engine and headless canvas gesture regressions passed; native move, rotation and Escape screenshots reviewed. Formatting, Clippy, WASM and repository checks passed; the undo label reuses translated Repeat Options. (#2877) Scores and hours unchanged. | | 2026-10-18 | minor | Bounding-box handles take priority where a selected Mirror Repeat axis crosses them: the Top handle scales the repeat, while the center still moves it and the ends still rotate it. A headless canvas regression confirms height changes while width stays fixed; scores and hours unchanged. | | 2026-10-17 | minor | Blend spine Anchor Point conversions, selection/stacking priority and Shift regression coverage (#2544); scores and hours unchanged. Windows native canvas checks and screenshots reviewed in PR #2643. | @@ -258,7 +273,6 @@ re-measure of the panels added since. Slider rails show on Medium Dark (#1808, # | 2026-10-17 | minor | Group Selection picks one path of a compound path (the outer shape or a hole) and moves it on its own; a second click adds the compound path (#2441, in part) | | 2026-10-16 | minor | The Move dialog opens on the offset of the last drag or Move and with the checkboxes it was last confirmed with; scores unchanged | | 2026-10-16 | minor | Native documents restore transparency grid visibility (#1968); save/open regression covers on/off, old files and SVG; scores and hours unchanged (estimated) | -| 2026-10-17 | minor | Group Selection picks one path of a compound path (the outer shape or a hole), and a second click adds the compound path (#2441, in part) | | 2026-10-16 | minor | Live Corners: a corner rounds until its cut reaches the neighbouring anchors or their cuts, so one corner of a 100 pt square alone reaches a 100 pt radius instead of 50 (#2332); score unchanged (estimated) | | 2026-10-16 | minor | Correction: quick Image Trace presets trace at once and leave the panel as it was (the 2026-10-14 row below said a quick preset reveals it; the later change in `baadbe2c6` made the button the way in); the Image Trace button in the Control bar or Properties opens the controls, as the public documentation describes. Wording only; scores and hours unchanged. | | 2026-10-16 | minor | Batch exporting in Export for Screens (#1935): a file name pattern (document and item names, a counter, the date), folders per format, item or both, Layers and Selection tabs with thumbnails, EPS, AI and VectorCraft rows, a PDF row with printer's marks, and export presets (built-in Logo Package and Print-Ready PDF, saved ones); scores and hours unchanged (estimated) | diff --git a/packaging/linux/ai.storyteller.vectorcraft.desktop b/packaging/linux/ai.storyteller.vectorcraft.desktop index af34553000..29d3ec84fa 100644 --- a/packaging/linux/ai.storyteller.vectorcraft.desktop +++ b/packaging/linux/ai.storyteller.vectorcraft.desktop @@ -11,4 +11,6 @@ StartupNotify=true StartupWMClass=ai.storyteller.vectorcraft Categories=Graphics;2DGraphics;VectorGraphics; Keywords=vector;illustration;svg;pdf;drawing;bezier; -MimeType=image/svg+xml;application/pdf; +# MimeType lists the formats File › Open reads that Info.plist.in declares for macOS. The type of .ai +# files is shared-mime-info's application/illustrator (brand-ok). +MimeType=image/svg+xml;application/pdf;application/x-vectorcraft;image/svg+xml-compressed;application/illustrator;application/x-ai-template;image/png;image/jpeg;image/gif;image/webp;image/tiff;image/bmp;application/x-vectorcraft-template;image/vnd.dxf;image/emf;image/wmf;image/x-eps;application/x-affinity; diff --git a/packaging/linux/ai.storyteller.vectorcraft.mime.xml b/packaging/linux/ai.storyteller.vectorcraft.mime.xml index be4dcc220e..eb6db8ce21 100644 --- a/packaging/linux/ai.storyteller.vectorcraft.mime.xml +++ b/packaging/linux/ai.storyteller.vectorcraft.mime.xml @@ -1,3 +1,34 @@ + + + VectorCraft document + + + + + + VectorCraft template + + + + + PDF-compatible .ait template + + + + + + Affinity document + + + + + + + + diff --git a/packaging/linux/flatpak/ai.storyteller.vectorcraft.yml b/packaging/linux/flatpak/ai.storyteller.vectorcraft.yml index cbee5b7204..c2a00eab15 100644 --- a/packaging/linux/flatpak/ai.storyteller.vectorcraft.yml +++ b/packaging/linux/flatpak/ai.storyteller.vectorcraft.yml @@ -43,6 +43,7 @@ modules: build-commands: - cargo --offline build --release --locked -p vectorcraft - install -Dm755 target/release/vectorcraft /app/bin/vectorcraft + - install -Dm644 NOTICE /app/share/doc/vectorcraft/NOTICE - install -Dm644 packaging/linux/ai.storyteller.vectorcraft.desktop /app/share/applications/ai.storyteller.vectorcraft.desktop - install -Dm644 packaging/linux/ai.storyteller.vectorcraft.mime.xml /app/share/mime/packages/ai.storyteller.vectorcraft.xml - mkdir -p /app/share/icons && cp -R assets/app-icon/hicolor /app/share/icons/ diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index 7efbaf44ee..65dd1e03ad 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -106,6 +106,8 @@ if has appimage; then APPDIR="$WORK/VectorCraft.AppDir" cp -R "$STAGE" "$APPDIR" mv "$APPDIR/usr/share/doc" "$WORK/doc-unused" + # Keep the third-party runtime notice after dropping the full documentation tree. + install -Dm644 "$ROOT/NOTICE" "$APPDIR/usr/share/doc/vectorcraft/NOTICE" ln -s usr/bin/vectorcraft "$APPDIR/AppRun" cp "$HERE/$APP_ID.desktop" "$APPDIR/$APP_ID.desktop" cp "$ROOT/assets/app-icon/hicolor/256x256/apps/$APP_ID.png" "$APPDIR/$APP_ID.png" diff --git a/xtask/src/brands.rs b/xtask/src/brands.rs index 9e722aa9e9..1d3b8f430c 100644 --- a/xtask/src/brands.rs +++ b/xtask/src/brands.rs @@ -10,8 +10,9 @@ //! * every text file under `packaging/`, and under `docs/` except Markdown pages: Markdown docs //! (like `README.md` and `ROADMAP.md`) may name the reference app and compare against it. //! -//! A line that has to keep an old name (an alias that old files or preferences still use) says -//! `brand-ok` in a comment on that line. +//! A line that has to keep an old name (an alias that old files or preferences still use) or a +//! name another project defines (a shared MIME type) says `brand-ok` in a comment on that line or, +//! in a file listed in `MARK_ABOVE`, on a `#` comment line just above it. use std::path::Path; @@ -42,6 +43,10 @@ const SELF: &str = "xtask/src/brands.rs"; /// The cursor manifest, which designers read. const CURSOR_MANIFEST: &str = "crates/tools/src/cursors.toml"; +/// Packaging files whose comments take whole lines (a desktop entry has no end-of-line comments): +/// in these, a `#` line marked `brand-ok` also covers the line just below it. +const MARK_ABOVE: &[&str] = &["packaging/linux/ai.storyteller.vectorcraft.desktop"]; + /// A denied name found in a file. #[derive(Debug, PartialEq)] pub struct Hit { @@ -77,8 +82,8 @@ pub fn scan(root: &Path, files: &[String]) -> Vec { let Ok(text) = std::fs::read_to_string(root.join(path)) else { continue }; let found = match kind { Kind::Rust => scan_rust(&text), - Kind::Manifest => scan_lines(&text, |l| l.trim_start().starts_with("description")), - Kind::Text => scan_lines(&text, |_| true), + Kind::Manifest => scan_lines(&text, |l| l.trim_start().starts_with("description"), false), + Kind::Text => scan_lines(&text, |_| true, MARK_ABOVE.contains(&path.as_str())), }; hits.extend(found.into_iter().map(|(line, term, context)| Hit { path: path.clone(), line, term, context })); } @@ -110,11 +115,16 @@ fn is_test_path(path: &str) -> bool { file == "tests.rs" || file.starts_with("tests_") || file.ends_with("_tests.rs") || parts.any(|d| d == "tests" || d == "benches") } -/// (line, term, line text) for each denied name on the lines `keep` selects. -fn scan_lines(text: &str, keep: impl Fn(&str) -> bool) -> Vec<(usize, &'static str, String)> { - text.lines() +/// (line, term, line text) for each denied name on the lines `keep` selects, but those marked +/// `brand-ok` on the line or, with `mark_above`, on a `#` comment line just above. +fn scan_lines(text: &str, keep: impl Fn(&str) -> bool, mark_above: bool) -> Vec<(usize, &'static str, String)> { + let lines: Vec<&str> = text.lines().collect(); + let marked_above = + |i: usize| mark_above && i.checked_sub(1).and_then(|j| lines.get(j)).is_some_and(|l| l.trim_start().starts_with('#') && l.contains(ALLOW)); + lines + .iter() .enumerate() - .filter(|(_, l)| keep(l) && !l.contains(ALLOW)) + .filter(|&(i, l)| keep(l) && !l.contains(ALLOW) && !marked_above(i)) .flat_map(|(i, l)| terms_in(l, DENY).into_iter().map(move |t| (i + 1, t, l.trim().to_string()))) .collect() } @@ -335,11 +345,16 @@ line Pantone"; } #[test] fn docs_packaging_and_manifests() { - let lines = |text: &str, keep: fn(&str) -> bool| -> Vec<(usize, &'static str)> { - scan_lines(text, keep).into_iter().map(|(l, t, _)| (l, t)).collect() + let scan = |text: &str, keep: fn(&str) -> bool, mark_above: bool| -> Vec<(usize, &'static str)> { + scan_lines(text, keep, mark_above).into_iter().map(|(l, t, _)| (l, t)).collect() }; + let lines = |text: &str, keep: fn(&str) -> bool| scan(text, keep, false); assert_eq!(lines("Keywords=vector;illustrator;\n", |_| true), [(1, "illustrator")]); assert_eq!(lines("Like Adobe apps\nnot here: Adobe # brand-ok\n", |_| true), [(1, "adobe")]); + let desktop = "# shared type (brand-ok)\nMimeType=application/illustrator;\n# a comment\nMimeType=application/illustrator;\n"; + assert_eq!(scan(desktop, |_| true, true), [(4, "illustrator")], "a `#` line marks the line below it only"); + assert_eq!(lines(desktop, |_| true), [(2, "illustrator"), (4, "illustrator")], "only `MARK_ABOVE` files take a mark from the line above"); + assert_eq!(scan("x = 1 # brand-ok\nIllustrator\n", |_| true, true), [(2, "illustrator")], "a code line's comment marks that line only"); let manifest = "name = \"adobe-thing\"\ndescription = \"Illustrator-style UI\"\n"; assert_eq!(lines(manifest, |l| l.trim_start().starts_with("description")), [(2, "illustrator")]); } @@ -373,12 +388,26 @@ line Pantone"; } file("docs/x.md", "Works like Photoshop.\n"); file("docs/x.txt", "Works like Photoshop.\n"); file("packaging/x.desktop", "Keywords=vector;illustrator;\n"); + let marked = "# shared type (brand-ok)\nMimeType=application/illustrator;\n"; + file(MARK_ABOVE[0], marked); + file("packaging/x.yaml", marked); file("README.md", "Adobe trademark notice\n"); - let files: Vec = ["crates/x/src/lib.rs", "docs/x.md", "docs/x.txt", "packaging/x.desktop", "README.md"].map(String::from).to_vec(); + let files: Vec = + ["crates/x/src/lib.rs", "docs/x.md", "docs/x.txt", "packaging/x.desktop", MARK_ABOVE[0], "packaging/x.yaml", "README.md"] + .map(String::from) + .to_vec(); let hits = scan(&dir, &files); let _ = std::fs::remove_dir_all(&dir); let found: Vec<(&str, usize, &str)> = hits.iter().map(|h| (h.path.as_str(), h.line, h.term)).collect(); - assert_eq!(found, [("crates/x/src/lib.rs", 1, "illustrator"), ("docs/x.txt", 1, "photoshop"), ("packaging/x.desktop", 1, "illustrator")]); + assert_eq!( + found, + [ + ("crates/x/src/lib.rs", 1, "illustrator"), + ("docs/x.txt", 1, "photoshop"), + ("packaging/x.desktop", 1, "illustrator"), + ("packaging/x.yaml", 2, "illustrator") + ] + ); } #[test]